JavaScript Fetch API: Making HTTP Requests
Master the Fetch API. Learn to make GET, POST requests, handle responses, and work with APIs.
JavaScript Fetch API
What is Fetch?
Fetch is a modern way to make HTTP requests. Get data from servers.
``` ┌─────────────────────┐ │ Your JavaScript │ │ ┌───────────────┐ │ │ │ fetch(url) │ │ │ └───────────────┘ │ └──────────┬──────────┘ │ ┌───────────▼───────────┐ │ Server │ │ (API endpoint) │ └──────────┬─────────────┘ │ ┌───────────▼───────────┐ │ Response │ │ (JSON data) │ └───────────────────────┘ ```
GET Request
```javascript fetch('https://api.example.com/users') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ```
POST Request
```javascript fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', email: 'john@example.com' }) }) .then(response => response.json()) .then(data => console.log(data)); ```
With async/await
```javascript async function getUsers() { try { const response = await fetch('https://api.example.com/users'); const users = await response.json(); return users; } catch (error) { console.error('Error:', error); } } ```
Key Takeaway
Fetch makes HTTP requests. Returns a Promise. Use then() or async/await. Essential for getting data from APIs.