Coding

What Is an API? A Plain Explanation With a Real Request

An API (Application Programming Interface) is a defined way for one piece of software to request data or actions from another, without knowing how the other side works inside. A weather app asking a weather service for tomorrow's forecast, and getting back structured data instead of a web page, is using an API.

MDN's definition puts it as "a set of features and rules" that let software interact with an application, "as opposed to a human user interface". The API is the contract: which requests are allowed, what they must contain, and what comes back.

A real API request and response

The quickest way to understand an API is to call one. JSONPlaceholder is a free practice API that returns fake data. Run this in a terminal. macOS and Linux have curl, and Windows 11 ships curl.exe; in Windows PowerShell 5.1 type curl.exe, because plain curl there is an alias for Invoke-WebRequest.

curl -i https://jsonplaceholder.typicode.com/todos/1

Real output (headers shortened):

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

That exchange contains every part of a typical web API call:

  • The endpoint: https://jsonplaceholder.typicode.com/todos/1, the address of one resource, to-do item number 1.
  • The method: curl sends GET by default, which means "read".
  • The status code: 200 OK means it worked. Ask for an item that doesn't exist (/todos/999999) and you get HTTP/1.1 404 Not Found instead.
  • The format: Content-Type: application/json says the body is JSON, which any programming language can parse into objects.

Sending data to an API

To create something, you send a different method and a body. The quoting below is for macOS, Linux, WSL or Git Bash; Windows shells handle the quotes differently:

curl -i -X POST https://jsonplaceholder.typicode.com/todos \
  -H "Content-Type: application/json" \
  -d '{"title":"buy milk","completed":false,"userId":1}'

Real output (headers shortened):

HTTP/1.1 201 Created

{
  "title": "buy milk",
  "completed": false,
  "userId": 1,
  "id": 201
}

201 Created and the new id are what a real API returns. JSONPlaceholder's guide notes the resource "is not really created on the server, but the response is faked as if", so it's safe to experiment with. In code, the same call is a few lines; see Python requests POST JSON.

The HTTP methods an API uses

Web APIs reuse the methods defined in HTTP. RFC 9110 defines which ones are "safe" (read-only) and which are "idempotent" (repeating the request has the same effect as sending it once), which matters when a client retries after a network error.

MethodTypical useSafeIdempotent
GETRead a resource or listYesYes
POSTCreate something, or trigger an actionNoNo
PUTReplace a resource completelyNoYes
PATCHChange some fields of a resourceNoNot guaranteed
DELETERemove a resourceNoYes

RFC 9110 states it directly: "the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe", and "PUT, DELETE, and safe request methods are idempotent". PATCH is defined separately in RFC 5789, which says it "is neither safe nor idempotent", although a particular PATCH request can be designed to be. The status code tells you what happened; HTTP status codes explained lists the common ones.

APIs that aren't web APIs

"API" is older than web services. Any program or library that exposes functions for other code to call has an API:

  • Library APIs. Python's json.loads() is part of the API of the json module. You call it with a string and get back Python objects, without knowing how the parser works.
  • Browser APIs. MDN separates these from web services: browser APIs "are built into your web browser", such as fetch(), the DOM and geolocation, while third-party APIs live on someone else's server.
  • Operating system APIs. Opening a file, creating a window or reading the clock all go through functions the OS provides to programs.

MDN's analogy is the power socket. You plug an appliance into the socket instead of wiring it into the mains yourself. The socket is a fixed, documented interface; what happens behind the wall can change without breaking your toaster.

API styles: REST, GraphQL and others

Web APIs follow a few common designs:

  • REST: one URL per resource and the HTTP methods above. The JSONPlaceholder examples are REST-style.
  • GraphQL: one endpoint, and the client sends a query listing the fields it wants. REST vs GraphQL compares the two with real requests.
  • RPC-style (gRPC, JSON-RPC): you call named functions rather than addressing resources.
  • Webhooks: the reverse direction. You give a service a URL, and it sends a request to you when something happens, such as a payment succeeding.

Many REST APIs publish an OpenAPI document, which the specification describes as "a standard, programming language-agnostic interface description for HTTP APIs". Tools read it to generate documentation pages and client code.

API keys and authentication

Most real APIs need to know who is calling, to apply rate limits, bill usage and protect data. The common methods:

  • API key: a long secret string sent in a header such as Authorization: Bearer sk_... or X-API-Key: .... Treat it like a password: keep it in an environment variable, never in code you commit. If one leaks, follow what to do with a leaked API key.
  • OAuth access token: used when an app acts on behalf of a user, such as reading your calendar. The user approves it and the app never sees their password.

APIs also enforce rate limits. Go over them and you'll typically get 429 Too Many Requests; slow down and retry after the delay the response suggests.

Common API errors and what they mean

StatusUsual causeWhat to check
400 Bad RequestThe body or parameters are malformedJSON syntax, required fields, Content-Type header
401 UnauthorizedNo credentials, or invalid onesThe key is present, current and in the header the docs specify
403 ForbiddenValid credentials without permission for this actionThe key's scopes or plan
404 Not FoundWrong URL or IDTypos, API version in the path, trailing slashes
429 Too Many RequestsRate limit hitBack off and retry later
500-504Server-side problemRetry with a delay; check the provider's status page

In a browser, an extra failure appears that curl never shows: the page's JavaScript is blocked from reading another site's API response. That's the CORS check, explained in CORS error explained.

Frequently asked questions

What does API stand for?
Application Programming Interface. 'Interface' is the key word: an API is the agreed set of requests a program accepts and the responses it gives back, as opposed to a user interface, which is meant for people.
Is an API the same as a website?
No, although a web API usually runs on the same kind of server. A website returns HTML for a browser to display to a person. A web API returns data, usually JSON, for another program to read. Many services have both: the website for people and the API for software.
Do I need to know how to code to use an API?
To call one by hand, no: a single curl command or a tool like a REST client is enough to send a request and read the JSON. To use an API inside an app or automation, you need some code, or a no-code tool that makes the API calls for you.
Are APIs free?
It depends on the provider. Some are free with rate limits, many have a free tier and paid usage above it, and some are paid only. Most require an API key even when free, so the provider can apply limits and bill for usage.
What is an API endpoint?
An endpoint is one specific address in a web API that does one job, such as GET /todos/1 to fetch a to-do item or POST /todos to create one. An API is the whole set of endpoints plus the rules for using them.

Sources