Making API calls
Every web app needs to communicate with a backend. JavaScript’sfetch() function handles HTTP requests - GET to retrieve data, POST to create data, PUT to update, DELETE to remove.
You’ll use this pattern in almost every React component that needs backend data.
Basic GET request
fetch() returns a Promise, so you need await. The response needs to be converted to JSON with .json().
The
.json() method also returns a Promise, which is why it needs await too. It reads the response body and parses it as JSON.Handling errors
response.ok before parsing. A 404 or 500 status won’t throw an error automatically - you have to check for it.
POST request with data
method: 'POST'- tells the server you’re creating dataheaderswithContent-Type: application/json- tells the server you’re sending JSONbodywithJSON.stringify()- converts your JavaScript object to a JSON string
PUT and DELETE requests
Using environment variables
.env file so you can change it between development and production without modifying code.
In Vite (the build tool we’ll use), environment variables must start with
VITE_ to be exposed to your code. In your .env file: VITE_API_URL=http://localhost:8000Complete example with error handling
api/users.js
Common mistakes
Forgetting to await fetch
Forgetting to await fetch
Not checking response.ok
Not checking response.ok
Forgetting JSON.stringify for POST/PUT
Forgetting JSON.stringify for POST/PUT
Not using try/catch
Not using try/catch
What’s next?
You can now fetch data from your FastAPI backend. Next, let’s learn how to work with the responses you get back — status codes, headers, and different response formats.Handling responses
Parse API responses and work with different formats