JSON Web APIs: Complete RESTful API Guide
Master JSON Web APIs! Learn how to consume and create RESTful APIs using JSON. Includes HTTP methods, authentication, error handling, and best practices.
What is a JSON Web API?
A JSON Web API (Application Programming Interface) is a service that exchanges data in JSON format over HTTP. RESTful APIs use standard HTTP methods:
- GET - Retrieve data
- POST - Create new data
- PUT/PATCH - Update existing data
- DELETE - Remove data
Making API Requests with Fetch
GET Request - Fetching Data
// Simple GET request
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Modern async/await
async function getUsers() {
try {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error('Error fetching users:', error);
}
}
POST Request - Creating Data
async function createUser(userData) {
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const newUser = await response.json();
console.log('Created:', newUser);
return newUser;
} catch (error) {
console.error('Error:', error);
}
}
// Usage
createUser({
name: "John Doe",
email: "john@example.com"
});
PUT Request - Updating Data
async function updateUser(userId, updates) {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates)
});
return await response.json();
}
// Usage
updateUser(123, { name: "Jane Doe" });
DELETE Request - Removing Data
async function deleteUser(userId) {
const response = await fetch(`https://api.example.com/users/${userId}`, {
method: 'DELETE'
});
if (response.ok) {
console.log('User deleted successfully');
}
}
API Authentication
API Key Authentication
const API_KEY = 'your-api-key-here';
fetch('https://api.example.com/data', {
headers: {
'X-API-Key': API_KEY
}
})
.then(response => response.json())
.then(data => console.log(data));
Bearer Token (JWT) Authentication
const token = 'your-jwt-token';
fetch('https://api.example.com/protected', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data));
RESTful API Response Structure
Successful Response
{
"success": true,
"data": {
"id": 123,
"name": "John Doe",
"email": "john@example.com"
},
"message": "User retrieved successfully"
}
Error Response
{
"success": false,
"error": {
"code": "USER_NOT_FOUND",
"message": "User with ID 123 not found",
"status": 404
}
}
Error Handling Best Practices
async function apiRequest(url, options = {}) {
try {
const response = await fetch(url, options);
// Check HTTP status
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || 'Request failed');
}
// Parse JSON response
const data = await response.json();
// Check application-level errors
if (!data.success) {
throw new Error(data.error?.message || 'Operation failed');
}
return data;
} catch (error) {
// Network errors
if (error instanceof TypeError) {
console.error('Network error:', error);
throw new Error('Network connection failed');
}
// Re-throw other errors
throw error;
}
}
Rate Limiting and Pagination
Handling Pagination
async function getAllUsers() {
const allUsers = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const response = await fetch(
`https://api.example.com/users?page=${page}&limit=100`
);
const data = await response.json();
allUsers.push(...data.users);
hasMore = data.pagination.hasNextPage;
page++;
}
return allUsers;
}
Rate Limiting
// Respect rate limits
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function batchRequests(urls) {
const results = [];
for (const url of urls) {
const response = await fetch(url);
results.push(await response.json());
// Wait 1 second between requests
await sleep(1000);
}
return results;
}
API Best Practices
- Always use HTTPS for secure communication
- Include proper error handling for network failures
- Validate API responses before using data
- Cache responses when appropriate
- Respect rate limits to avoid blocking
- Use environment variables for API keys
- Implement retry logic for failed requests
Testing APIs: Use our JSON validator tool to validate and format API responses before using them in your application!
Summary
- JSON APIs use HTTP methods (GET, POST, PUT, DELETE) for CRUD operations
- Use the Fetch API for making HTTP requests in JavaScript
- Always handle errors and check response status
- Implement authentication using API keys or JWT tokens
- Follow pagination patterns for large datasets
- Respect rate limits and implement retry logic