A restaurant menu is a handy way to picture an API. It lists what you can order and how to ask for it, while the kitchen stays out of sight. You do not need to know how the chef cooks; you place an order in the expected format and receive a dish. An API offers programs that same deal: it publishes the requests it accepts and the responses it returns, and hides the internal workings.
The term covers more than websites. The functions a library exposes form its API, and so do the services an operating system provides to apps. In everyday web development, though, "API" usually means a web API: a server that answers HTTP requests, typically with JSON data.
Example
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json(); // parse the JSON body
}
getUser(42).then(user => console.log(user.name));
The code sends a request to an endpoint, checks the HTTP status code, and turns the JSON reply into a JavaScript object.
What an API contract includes
A well-documented web API specifies its endpoints (URLs), the HTTP methods each one accepts (GET to read, POST to create, and so on), the required parameters, the shape of each response, and how errors are reported. Many also require an API key or token to identify the caller, and apply rate limits that cap how many requests you can send.
API vs library vs framework
These terms overlap. A library is code you install and call directly inside your program, and its API is the set of functions it makes public. A web API runs on someone else's server, so you reach it over the network. A framework differs again: it calls your code rather than the other way round.
Learn more
- Make API responses readable with the JSON formatter.
- Experiment with JSON shapes in the JSON editor.
- Follow the full-stack developer roadmap.
Last updated