Intermediate level · Module 5: Connecting Front End and API · Lesson 1 of 3
An API Client for the Front End
Put all API calls in one module with shared error handling, and use it from React components.
In this lesson you will
- Write a front-end API client module
- Handle HTTP errors consistently in one place
Key concepts
API client modulebase URLshared error handlingseparation of concerns
The lesson
Rather than calling fetch in many components, create api.js with functions such as getCourses and createEnquiry. Components then call functions with clear names, and changes to the API affect one file.
The client checks response.ok, parses JSON and throws a meaningful error — for example an ApiError carrying the status and the field errors returned by the server.
Read the API's base URL from configuration rather than writing it into every call, so the same code works locally and in production.
Step by step
- Create api.js with getCourses and getCourse.
- Replace direct fetch calls in components with the client.
- Throw an ApiError for non-OK responses.
- Read the base URL from configuration.
Practice activity
Move all of the catalogue's API calls into a client module.
Expected result: Components contain no fetch calls and errors are handled consistently.
Check your understanding
-
Why put all API calls in one module?
Show answer
Components stay simple and API changes are made in one place.
-
Why read the base URL from configuration?
Show answer
So the same code works in development and production.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.