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.

JavaScript Editor
Response Properties:
  • response.ok - True for status 200-299
  • response.status - HTTP status code
  • response.statusText - Status message
  • response.headers - Response headers
  • response.url - Final URL after redirects

šŸ“Ø POST Request with JSON

Sending data to a server using POST method with JSON payload.

JavaScript Editor
Common Headers:
  • Content-Type - Type of data being sent
  • Authorization - Authentication tokens
  • Accept - What type of response you accept
  • User-Agent - Client information

šŸ”„ All HTTP Methods

Fetch API supports all HTTP methods: GET, POST, PUT, PATCH, DELETE, etc.

JavaScript Editor
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.

JavaScript Editor
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.

JavaScript Editor
šŸ’” Best Practices:
  • Always check response.ok or 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.