A REST API Exposes Resources at Endpoints and Acts on Them with HTTP Methods

In progress

An API (Application Programming Interface) is the contract two programs agree on to exchange data, without a user interface in between: a frontend asking a backend for data is the typical case. REST is the most common style for web APIs: each resource has an address (an endpoint, a URI), and standard HTTP methods say what to do with it.

Methods and What They Promise

Method Action Safe (no change) Idempotent (repeatable)
GET /users read a collection or a resource yes yes
POST /users create a resource no no: two calls create two users
PUT /users/42 replace the resource entirely no yes
PATCH /users/42 change part of the resource no not necessarily
DELETE /users/42 remove it no yes

Idempotent means repeating the request leaves the server in the same state as sending it once, which is what makes automatic retries safe. That is why a client may retry a timed-out PUT but must not blindly retry a POST.

Status Codes Carry the Outcome

200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Unprocessable Content, 500 Internal Server Error. A body saying {"error": ...} with a 200 status breaks every client that trusts the code.

A successful POST that creates something should answer 201 Created with a Location header naming the new resource (Location: /books/42), so the client can fetch or update it without guessing the URL. In FastAPI, declare response: Response in the handler and set response.headers["Location"], with status_code=201 on the route.

References

Review cards

Flashcard Why may a client retry a timed-out `PUT` but not a `POST`?

PUT replaces the resource with the same content, so sending it twice leaves the same state (idempotent). Each POST creates a new resource, so a retry can create a duplicate.

Flashcard What should a REST API return after a `POST` creates a resource?

201 Created, with a Location header naming the new resource (Location: /books/42), so the client can fetch or update it without guessing the URL.

Quiz Which property sets `POST` apart from `PUT` and `DELETE`?
  • It isn't idempotent: two calls create two resources
  • It's safe: it doesn't change server state
  • It replaces the resource entirely
  • It only reads a collection

PUT and DELETE are idempotent; POST isn't. None of the three is safe, and replacing is PUT's job.

Flashcard How does a FastAPI endpoint return `201` with a `Location` header?

Set status_code=201 on the route, declare response: Response in the handler, and set response.headers["Location"].