Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 50 ยท Getting started

REST principles with FastAPI

Learn the ideas behind REST (resources, HTTP verbs, status codes, idempotency, statelessness) and see each one in a runnable FastAPI example, plus REST versus RPC and GraphQL.

FastAPI makes it easy to write endpoints. It does not decide what the endpoints should be. Two APIs can both work and still be very different to use: one guessable and consistent, the other a pile of /getUser, /doDelete and /updateStuff2. REST is the set of ideas that most web APIs use to avoid that mess.

This lesson explains those ideas in plain terms and shows each one in a small runnable FastAPI program. It is a concepts lesson: you do not need to remember every rule, but knowing the reasons will make your design decisions in the rest of the course faster.

What REST means

REST stands for Representational State Transfer. It is a style described in a 2000 PhD thesis by Roy Fielding, describing how the web itself works. A service is called RESTful when it follows a handful of constraints:

The REST constraints

Client-server UI and data are separate concerns.
Stateless Each request carries everything needed.
Cacheable Responses say if they can be reused.
Uniform interface Same verbs and URLs everywhere.
1 / 2

Most people say "REST API" for any JSON-over-HTTP API that uses these practical conventions: resources in URLs, HTTP methods as the verbs, status codes for results, and no server-side session state between requests. Strict REST also demands hypermedia links (HATEOAS), which few real APIs implement; do not worry about it at this stage.

Resources: nouns in the URL

A resource is a thing your API knows about: a user, an order, a book. Each has a URL, and the URL names the thing, not the action.

Good Bad
GET /books GET /getAllBooks
GET /books/42 POST /fetchBook?id=42
POST /books POST /createNewBook
DELETE /books/42 GET /books/42/delete
GET /authors/7/books GET /booksByAuthor?a=7

Conventions that keep URLs predictable:

  • Use plural nouns for collections (/books) and the id for one member (/books/42).
  • Nest to show ownership, but stay shallow: /authors/7/books is fine, /a/7/b/3/c/2/d is not. Once an item has its own id, /books/42 is enough.
  • Use query parameters for filtering, sorting and paging (/books?genre=sf&sort=-year&limit=20), not for naming the resource.
  • Use lowercase and hyphens: /order-items, not /OrderItems.

Verbs: HTTP methods

The method says what to do to the resource. The meaning is the same for every resource, which is the "uniform interface".

Method Typical use Safe? Idempotent? Body
GET read yes yes no
POST create (or run an action) no no yes
PUT replace completely no yes yes
PATCH change some fields no usually not guaranteed yes
DELETE remove no yes no

Two properties matter a lot:

  • Safe means "does not change anything". Browsers, crawlers and caches may call GET freely, so a GET that deletes data is a bug waiting to happen.
  • Idempotent means "doing it twice has the same effect as doing it once". That is a gift to clients: if a network error leaves them unsure whether a PUT arrived, they can simply send it again. POST is not idempotent, so a retry may create a second record.

Seeing idempotency

The program below stores books in a dictionary. Watch what happens when each request is repeated.

Python Safe and idempotent methods in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that sending the same POST twice created two books with different ids, while the PUT repeated three times left exactly one book. The second DELETE returned 404: the state of the server is identical either way (the book is gone), which is what idempotent means. The status code is allowed to differ.

POST returned 201 Created with a Location header pointing to the new resource. That header is a REST nicety clients appreciate because it tells them where the new thing lives.

If you need a safely retryable POST (payments, orders), accept an idempotency key: the client sends a unique Idempotency-Key header, and the server remembers the result for that key and returns it again instead of repeating the action.

Status codes tell the story

The status code is part of the contract. A client should not have to parse the body to know whether the call worked.

Code Meaning When
200 OK successful read or update
201 Created new resource made (include Location)
204 No Content success with nothing to return (usual for DELETE)
400 Bad Request malformed request
401 Unauthorized missing or invalid credentials
403 Forbidden known user, not allowed
404 Not Found no such resource
409 Conflict clashes with current state (duplicate email)
422 Unprocessable Content well-formed but invalid data (FastAPI's validation errors)
429 Too Many Requests rate limit
500 Server Error your bug

FastAPI sets 422 for you when validation fails, and the errors lesson shows how to raise the others cleanly.

Statelessness

In a stateless API every request contains all the information needed to handle it: who you are (a token), what you want (URL, method, body). The server does not remember "the user is on step 3 of the wizard" in memory between calls.

Why it matters: any server in a pool can answer any request, so you can add servers or restart them freely, and requests are easy to test, retry and cache. This is why the authentication in this course uses a token sent on every request, as in OAuth2 and JWT, rather than server-side sessions kept in memory.

State still exists, of course. It lives in the database (or a cache), not in the process.

Representations and content negotiation

You never get "the book"; you get a representation of it, usually JSON. The same resource could also be offered as XML or CSV, and the client asks for the format it wants with an Accept header. Most APIs simply offer JSON, and FastAPI makes JSON the default. Content negotiation matters more with downloads, as in the response classes lesson.

Python One URL, two representations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

REST, RPC and GraphQL

REST is not the only way to design an API. Knowing the alternatives helps you choose.

Style Idea Strengths Weaknesses
REST Resources with URLs and standard verbs Simple, cacheable, works with any HTTP tool Over- and under-fetching; many round trips for related data
RPC (JSON-RPC, gRPC) Call named functions: POST /createInvoice Natural for actions; gRPC is fast and typed Less uniform; harder to cache
GraphQL One endpoint; client asks for the exact fields No over-fetching; great for complex UIs Caching and security are harder; more tooling

A pragmatic rule: use REST for CRUD-style resources, accept an occasional RPC-flavoured action endpoint for things that are not resources (POST /orders/42/cancel), and consider GraphQL only when many different clients need very different slices of the data. FastAPI can also host GraphQL (through the Strawberry library) and WebSockets next to ordinary REST endpoints.

Designing a good REST API: a checklist

  • Name resources with plural nouns; never put verbs in paths.
  • Use the right method and the right status code; return 201 and Location after creating.
  • Keep GET safe, make PUT and DELETE idempotent, and think about retries for POST.
  • Filter, sort and paginate with query parameters (see CRUD and pagination).
  • Return a consistent error shape.
  • Do not leak internals: use response models (Response models).
  • Plan for change: start with /v1 (API versioning).
  • Document it. FastAPI does this automatically through OpenAPI.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL follows REST naming conventions for 'delete book 42'?

    The URL names the resource (/books/42) and the HTTP method carries the action.
  2. 2. What does it mean that PUT is idempotent?

    Idempotent is about the effect on the server's state, which makes retries safe.
  3. 3. A client creates a resource with POST /books. Which response is the best practice?

    201 signals creation and Location tells the client where the new resource lives.
  4. 4. Why is a stateless API easier to scale?

    Without per-client memory on a specific server, you can add, remove or restart servers freely.
  5. 5. Which API style lets the client choose exactly which fields it receives from a single endpoint?

    GraphQL queries name the fields they want, which avoids over-fetching.

Summary

  • REST is a style: resources in URLs, HTTP methods as verbs, status codes for outcomes, stateless requests, cacheable responses.
  • Use plural nouns, shallow nesting and query parameters for filters; keep verbs out of paths.
  • GET is safe; GET, PUT and DELETE are idempotent; POST is not, so consider idempotency keys for risky retries.
  • Return meaningful status codes: 201 with Location on create, 204 on delete, 404, 409, 422 for the right problems.
  • Statelessness keeps state in the database or tokens, not in server memory.
  • REST fits resource CRUD, RPC fits actions, GraphQL fits flexible client-driven queries.

Next: compare frameworks in FastAPI vs Flask vs Django.