Fetch API in JavaScript
The Fetch API provides a modern, promise-based way to make HTTP requests in the browser. It's more powerful and flexible than the older XMLHttpRequest.
š¤ What is Fetch API?
Fetch API is a modern interface for fetching resources across the network. It provides a more powerful and flexible feature set than XMLHttpRequest.
- Promise-based - Uses Promises for async operations
- Streaming responses - Handle large responses efficiently
- Request/Response objects - Detailed control over HTTP calls
- Built into browsers - No external libraries needed
š” Key Features
- Simple, cleaner syntax than XMLHttpRequest
- Streaming and chunked responses
- Service Worker integration
- CORS and credentials control
- AbortController for request cancellation
Browser Support
All modern browsers support Fetch API. For older browsers, use polyfills or fallback to XMLHttpRequest.
š Basic GET Request
The simplest use of Fetch API - making a GET request to retrieve data.
Response Properties:
response.ok- True for status 200-299response.status- HTTP status coderesponse.statusText- Status messageresponse.headers- Response headersresponse.url- Final URL after redirects
šØ POST Request with JSON
Sending data to a server using POST method with JSON payload.
Common Headers:
Content-Type- Type of data being sentAuthorization- Authentication tokensAccept- What type of response you acceptUser-Agent- Client information
š All HTTP Methods
Fetch API supports all HTTP methods: GET, POST, PUT, PATCH, DELETE, etc.
HTTP Methods:
- GET - Retrieve data
- POST - Create new resource
- PUT - Update entire resource
- PATCH - Partial update
- DELETE - Remove resource
When to Use:
- Use POST for creating
- Use PUT for full updates
- Use PATCH for partial updates
- Use DELETE for removal
šØ Advanced Error Handling
Comprehensive error handling with retry logic and status code management.
HTTP Status Code Groups:
- 1xx - Informational
- 2xx - Success (200 OK, 201 Created)
- 3xx - Redirection
- 4xx - Client Errors (400 Bad Request, 404 Not Found)
- 5xx - Server Errors
šÆ Practical Example: GitHub API
Real-world example integrating with GitHub API to fetch user data and repositories.
š” Best Practices:
- Always check
response.okor status codes - Handle network errors and timeouts
- Use appropriate headers
- Implement retry logic for transient failures
- Cancel requests when component unmounts
- Use environment variables for API keys
Next Steps
Now that you can make HTTP requests, learn about JSON - the data format that powers most web APIs.