What is the Fetch API?
Fetch is a built-in browser function for making HTTP requests (GET, POST, PUT, DELETE) to remote servers (APIs).Basic GET Request
main.ts
The Fetch Process
Step 1: Send Request
Response object with:
response.status- HTTP status code (200, 404, 500, etc.)response.ok-trueif status is 200-299response.headers- Response headers- Methods to get body:
.json(),.text(),.blob()
Step 2: Check Status
main.ts
Step 3: Parse Response Body
URL Building with Template Literals
main.ts
Multiple Query Parameters
HTTP Status Codes
Success Codes (2xx)
| Code | Meaning |
|---|---|
| 200 | OK - Request succeeded |
| 201 | Created - Resource created successfully |
| 204 | No Content - Success but no data to return |
Client Error Codes (4xx)
| Code | Meaning |
|---|---|
| 400 | Bad Request - Invalid data sent |
| 401 | Unauthorized - Need to authenticate |
| 403 | Forbidden - Not allowed to access |
| 404 | Not Found - Resource doesn’t exist |
Server Error Codes (5xx)
| Code | Meaning |
|---|---|
| 500 | Internal Server Error - Server problem |
| 503 | Service Unavailable - Server down/overloaded |
Checking Status
Error Handling
main.ts
Types of Errors
- Network Error - No internet connection
- HTTP Error - Server returned error status (404, 500)
- Parse Error - Response isn’t valid JSON
- Timeout - Request took too long
POST Requests
Sending data to the server:PUT Request (Update)
DELETE Request
Request Headers
Send additional information with requests:Common Headers
| Header | Purpose |
|---|---|
Content-Type | Format of data being sent |
Authorization | Authentication credentials |
Accept | Format of data you want back |
User-Agent | Info about your app |
JSON Parsing
response.json()
Parses JSON and returns JavaScript object/array:main.ts
Type Assertion with ‘as’
Manual JSON Parsing
Timeout Handling
Fetch doesn’t have built-in timeout. Use AbortController:Response Data Validation
Always validate data from external sources:Loading States with Fetch
Combine fetch with state management:main.ts
CORS (Cross-Origin Resource Sharing)
If fetching from a different domain, the server must allow CORS:Access to fetch at '...' has been blocked by CORS policy
Solution: The API server must include CORS headers. You can’t fix this from the client.
Best Practices
1. Always Check response.ok
2. Use Try/Catch
3. Type Your Responses
4. Provide User Feedback
5. Log for Debugging
main.ts
Next Steps
- Async/Await - Deeper dive into async operations
- Interfaces - Type your API responses
- DOM Manipulation - Display fetched data