Examples
This section contains practical examples of how to use the JSONPlaceholder API in different programming languages and tools.
Available Examples
- JavaScript/Fetch - Using the modern Fetch API
- cURL - Command line examples
- Python - Using the requests library
- Node.js - Server-side JavaScript
Common Patterns
Basic CRUD Operations
Most examples follow the same pattern for CRUD operations:
- Create (POST) - Add new resources
- Read (GET) - Retrieve resources
- Update (PUT/PATCH) - Modify existing resources
- Delete (DELETE) - Remove resources
Error Handling
Always handle potential errors in your API calls:
javascript
try {
const response = await fetch('https://api.jsonplaceholder.dev/posts/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const post = await response.json();
console.log(post);
} catch (error) {
console.error('Error fetching post:', error);
}
Working with Relationships
JSONPlaceholder supports resource relationships:
- Users have posts, albums, and todos
- Posts have comments
- Albums have photos
javascript
// Get a user's posts
const userPosts = await fetch('https://api.jsonplaceholder.dev/users/1/posts')
.then(res => res.json());
// Get post comments
const comments = await fetch('https://api.jsonplaceholder.dev/posts/1/comments')
.then(res => res.json());
Testing Tips
- Use the API to test your error handling with non-existent IDs
- Try different HTTP methods to understand the full CRUD operations
- Test pagination by requesting different ranges of resources
- Practice with filtering using query parameters
Base URLs
Remember to use the appropriate base URL for your environment:
javascript
const BASE_URL = 'https://api.jsonplaceholder.dev';
javascript
const BASE_URL = 'http://localhost:3000';