Ready-to-use code templates for REST and GraphQL APIs. Includes authentication patterns, error handling, and common operations.
Basic GET request to retrieve data from an API endpoint.
async function fetchData(url) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
// Usage
const users = await fetchData('https://api.example.com/users');
Create new resources by sending data to the server.
async function postData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error('Error posting data:', error);
throw error;
}
}
// Usage
const newUser = await postData('https://api.example.com/users', {
name: 'John Doe',
email: 'john@example.com'
});
Update existing resources. Use PUT for full updates, PATCH for partial updates.
async function updateData(url, data, method = 'PATCH') {
try {
const response = await fetch(url, {
method: method, // 'PUT' or 'PATCH'
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (error) {
console.error('Error updating data:', error);
throw error;
}
}
// Usage (partial update)
const updated = await updateData('https://api.example.com/users/123', {
email: 'newemail@example.com'
}, 'PATCH');
Delete resources from the server.
async function deleteData(url) {
try {
const response = await fetch(url, {
method: 'DELETE',
headers: {
'Accept': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// DELETE may return 204 No Content
if (response.status === 204) {
return { success: true };
}
const result = await response.json();
return result;
} catch (error) {
console.error('Error deleting data:', error);
throw error;
}
}
// Usage
await deleteData('https://api.example.com/users/123');
Create a configured Axios instance with base URL and default headers.
npm install axios
import axios from 'axios';
// Create axios instance with default config
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
// Add request interceptor (for auth tokens)
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Add response interceptor (for error handling)
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
// Handle unauthorized
console.log('Unauthorized - redirect to login');
}
return Promise.reject(error);
}
);
export default api;
Complete CRUD (Create, Read, Update, Delete) operations using Axios.
import api from './apiConfig'; // Import configured instance
// GET - Read data
async function getUsers() {
try {
const response = await api.get('/users');
return response.data;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// POST - Create data
async function createUser(userData) {
try {
const response = await api.post('/users', userData);
return response.data;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// PUT/PATCH - Update data
async function updateUser(userId, userData) {
try {
const response = await api.patch(`/users/${userId}`, userData);
return response.data;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// DELETE - Delete data
async function deleteUser(userId) {
try {
const response = await api.delete(`/users/${userId}`);
return response.data;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}
// Parallel requests
async function getMultipleResources() {
try {
const [users, posts, comments] = await Promise.all([
api.get('/users'),
api.get('/posts'),
api.get('/comments')
]);
return {
users: users.data,
posts: posts.data,
comments: comments.data
};
} catch (error) {
console.error('Error:', error);
throw error;
}
}
Fetch data using GraphQL queries.
async function graphqlQuery(query, variables = {}) {
try {
const response = await fetch('https://api.example.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
query,
variables
})
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
return result.data;
} catch (error) {
console.error('GraphQL Error:', error);
throw error;
}
}
// Example query
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
posts {
id
title
content
}
}
}
`;
// Usage
const data = await graphqlQuery(query, { id: '123' });
console.log(data.user);
Create, update, or delete data using GraphQL mutations.
async function graphqlMutation(mutation, variables = {}) {
try {
const response = await fetch('https://api.example.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
query: mutation,
variables
})
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
return result.data;
} catch (error) {
console.error('GraphQL Mutation Error:', error);
throw error;
}
}
// Example mutation
const createUserMutation = `
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
createdAt
}
}
`;
// Usage
const newUser = await graphqlMutation(createUserMutation, {
input: {
name: 'John Doe',
email: 'john@example.com'
}
});
console.log(newUser.createUser);
Authentication using JSON Web Tokens (JWT).
// Login and store token
async function login(email, password) {
try {
const response = await fetch('https://api.example.com/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
});
const data = await response.json();
if (data.token) {
// Store token in localStorage
localStorage.setItem('token', data.token);
localStorage.setItem('user', JSON.stringify(data.user));
}
return data;
} catch (error) {
console.error('Login error:', error);
throw error;
}
}
// Make authenticated requests
async function fetchWithAuth(url) {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No authentication token found');
}
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (response.status === 401) {
// Token expired or invalid
localStorage.removeItem('token');
localStorage.removeItem('user');
throw new Error('Session expired. Please login again.');
}
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
// Logout
function logout() {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
}
// Check if user is authenticated
function isAuthenticated() {
return !!localStorage.getItem('token');
}
Simple API key authentication for public APIs.
// Store API key in environment variable (recommended)
const API_KEY = process.env.API_KEY || 'your-api-key-here';
async function fetchWithApiKey(url) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY // or 'Authorization': `Api-Key ${API_KEY}`
}
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Usage
const data = await fetchWithApiKey('https://api.example.com/data');