A comprehensive collection of exercises and examples demonstrating REST API consumption in JavaScript. This project showcases different methods, patterns, and best practices for working with external APIs using modern JavaScript techniques.
This repository contains practical exercises focused on understanding and implementing API consumption patterns. It covers everything from basic fetch operations to advanced error handling and data manipulation techniques, serving as both a learning resource and reference implementation.
Through this project, I've explored and implemented:
- HTTP Methods: GET, POST, PUT, PATCH, DELETE operations
- Async Programming: Promises, async/await, and callback patterns
- Error Handling: Comprehensive error management strategies
- Data Formats: Working with JSON, XML, and other response types
- Authentication: API keys, Bearer tokens, and OAuth basics
- Rate Limiting: Understanding and handling API rate limits
- CORS: Cross-Origin Resource Sharing concepts and solutions
- JavaScript ES6+ - Modern JavaScript features
- Fetch API - Native browser API for HTTP requests
- Axios - Promise-based HTTP client
- XMLHttpRequest - Traditional AJAX approach (for comparison)
- JSONPlaceholder - Fake REST API for testing
- GitHub API - Real-world API integration
- OpenWeather API - Weather data consumption
- REST Countries - Country information API
- PokeAPI - Pokemon data for fun exercises
- Random User API - User data generation
api-consumption/
βββ exercises/
β βββ 01-basic-fetch/
β β βββ index.html
β β βββ script.js
β β βββ README.md
β βββ 02-async-await/
β β βββ index.html
β β βββ script.js
β β βββ README.md
β βββ 03-error-handling/
β β βββ index.html
β β βββ script.js
β β βββ README.md
β βββ 04-axios-examples/
β β βββ index.html
β β βββ script.js
β β βββ README.md
β βββ 05-authentication/
β β βββ index.html
β β βββ script.js
β β βββ README.md
β βββ 06-advanced-patterns/
β βββ index.html
β βββ script.js
β βββ README.md
βββ projects/
β βββ weather-app/
β βββ github-explorer/
β βββ user-directory/
βββ utils/
β βββ api-wrapper.js
β βββ error-handler.js
β βββ data-transformer.js
βββ docs/
β βββ API-GUIDE.md
β βββ BEST-PRACTICES.md
β βββ TROUBLESHOOTING.md
βββ package.json
βββ README.md
Learn the fundamentals of the Fetch API with simple GET requests.
// Basic GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));Modern approach using async/await for cleaner code.
// Using async/await
async function fetchUser(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) throw new Error('User not found');
const user = await response.json();
return user;
} catch (error) {
console.error('Error fetching user:', error);
}
}Comprehensive error handling strategies for robust applications.
// Advanced error handling
class APIError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
}
async function fetchWithErrorHandling(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new APIError(
`HTTP error! status: ${response.status}`,
response.status
);
}
return await response.json();
} catch (error) {
if (error instanceof APIError) {
// Handle API errors
console.error('API Error:', error.message);
} else if (error instanceof TypeError) {
// Handle network errors
console.error('Network Error:', error.message);
} else {
// Handle other errors
console.error('Unknown Error:', error);
}
throw error;
}
}Using Axios for more features and better browser compatibility.
// Axios with interceptors
import axios from 'axios';
// Create instance with default config
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {'X-Custom-Header': 'value'}
});
// Request interceptor
api.interceptors.request.use(
config => {
// Add auth token to requests
config.headers.Authorization = `Bearer ${getToken()}`;
return config;
},
error => Promise.reject(error)
);
// Response interceptor
api.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// Handle authentication errors
redirectToLogin();
}
return Promise.reject(error);
}
);Different authentication strategies for API consumption.
// API Key Authentication
fetch('https://api.example.com/data', {
headers: {
'X-API-Key': process.env.API_KEY
}
});
// Bearer Token Authentication
fetch('https://api.example.com/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
});
// Basic Authentication
const credentials = btoa(`${username}:${password}`);
fetch('https://api.example.com/secure', {
headers: {
'Authorization': `Basic ${credentials}`
}
});Complex scenarios and optimization techniques.
// Parallel requests with Promise.all
async function fetchMultipleResources() {
try {
const [users, posts, comments] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/comments').then(r => r.json())
]);
return { users, posts, comments };
} catch (error) {
console.error('Error fetching resources:', error);
}
}
// Request with retry logic
async function fetchWithRetry(url, options = {}, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.ok) return response.json();
throw new Error(`HTTP ${response.status}`);
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
}
}
}- GET - Retrieve data
- POST - Create new resources
- PUT - Update entire resources
- PATCH - Partial updates
- DELETE - Remove resources
- Content-Type: application/json
- Accept: application/json
- Authorization headers
- Custom headers
- Status codes interpretation
- JSON parsing
- Stream handling
- Binary data
- Network errors
- HTTP error statuses
- Timeout handling
- Retry strategies
- Request batching
- Caching strategies
- Debouncing/Throttling
- Lazy loading
-
Clone the repository
git clone https://github.com/jefercort/api-consumption.git cd api-consumption -
Install dependencies (if using Axios)
npm install
-
Open exercises
- Navigate to any exercise folder
- Open
index.htmlin your browser - Check the console for outputs
- Start with basics: Begin with Exercise 1 to understand fundamental concepts
- Progress gradually: Move through exercises in order as they build upon each other
- Read the docs: Each exercise has its own README with detailed explanations
- Experiment: Modify the code and try different APIs
- Build projects: Apply learned concepts in the mini-projects
- Add GraphQL examples
- WebSocket implementation
- Server-Sent Events (SSE)
- Rate limiting implementation
- Request queue management
- Offline support with service workers
- API response caching strategies
- Unit tests for all exercises
- TypeScript migration
- React/Vue integration examples
Contributions are welcome! Feel free to:
- Fork the repository
- Create a feature branch (
git checkout -b feature/new-exercise) - Commit your changes (
git commit -m 'Add new exercise') - Push to the branch (
git push origin feature/new-exercise) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Kevin Cortes
- GitHub: @jefercort
- LinkedIn: Kevin Cortes PRO
- Thanks to all the free API providers used in this project
- MDN Web Docs for excellent documentation
- The JavaScript community for continuous learning resources
β Found this helpful? Star the repository to help others discover it!
π Check out the complete documentation for detailed API consumption patterns and best practices.