Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes

An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Explain an API and what REST adds: a resource address plus an HTTP method
  • Send GET, POST, PUT, PATCH and DELETE requests from Python and read the JSON reply
  • Explain why REST requests are stateless
  • Read a status code by its family: 2xx worked, 4xx your request, 5xx the server

Before you start

  • Python functions and dictionaries
  • JSON in Python

So far your programs have run on their own, on one machine. But most useful programs talk to another program over a network, and REST is the most common way they do it.

Think about a restaurant. You're at your table and you want a burger. You don't walk into the kitchen; you tell the waiter, and your order goes to the kitchen. The kitchen makes the burger, and the waiter brings it back. You're the client, the kitchen is the server, the order is the request, the burger coming back is the response. And the waiter is the API: an application programming interface, an agreed way for one program to ask another for something.

What REST adds

REST (representational state transfer) is a style for building APIs over HTTP. Everything on the server is a resource, and each resource has its own address, like /api/users/42. The HTTP method says what you want done with it:

MethodDoesExample
GETReadsOpen a profile
POSTCreatesSign up, add a comment
PUTReplaces the whole thingSend the full record
PATCHChanges a partEdit your bio
DELETERemovesDelete an account

What comes back is a copy of that resource, usually as JSON. That copy is the "representation" in the name. So: an address for the thing, and a method for the action. That's most of REST.

One request, one response, and the status code families clientserverUSERS[42] request: GET /api/users/42 response: 200, application/json {"id": 42, "name": "Alice", ...} 2xx: it worked200 OK, 201 created, 204 done 4xx: your request400 bad, 401 who are you, 404 5xx: the server500 error, 503 unavailable
An address and a method go out; a status code, headers and a JSON copy come back. The first digit of the code tells you where to look.

A tiny server to talk to

Every request in this lesson goes to shop_api.py, a tiny server built from Python's standard library. Calling start() runs it in a thread on your own machine (127.0.0.1) and returns its base address. It holds one user to begin with:

USERS = {42: {"id": 42, "name": "Alice",
              "email": "[email protected]"}}

Its handler has one method per HTTP verb (do_GET, do_POST, do_PUT, do_PATCH, do_DELETE). You don't need to read it to follow along; later you'll build servers like this with FastAPI.

Your first request: GET

import json
import urllib.request
from shop_api import start

BASE = start()

url = BASE + "/api/users/42"
with urllib.request.urlopen(url) as resp:
    print(resp.status)
    print(resp.headers["Content-Type"])
    user = json.loads(resp.read())

print(user)
print(user["name"])
200
application/json
{'id': 42, 'name': 'Alice', 'email': '[email protected]'}
Alice

urlopen sends a GET to /api/users/42. The server finds user 42 and replies with status 200, OK. The header says the body is JSON, and json.loads turns that text into a dictionary. Every time you type an address in a browser and press Enter, this is what happens. GET only reads, so nothing changes on the server.

Query parameters

with urllib.request.urlopen(BASE + "/api/users") as resp:
    users = json.loads(resp.read())
print(resp.status, len(users), "user")

url = BASE + "/api/users?role=admin"
with urllib.request.urlopen(url) as resp:
    print(resp.status, resp.url.split("?")[1])
200 1 user
200 role=admin

/api/users gives the whole list, one user so far. ?role=admin is a query parameter, a way to narrow down what you're asking for. This tiny server only reads the path, so it doesn't filter anything; the address just carries role=admin along. A real API would use it.

Requests are stateless

REST has one important rule: requests are stateless. Think of a waiter who forgets you the moment he walks away, so every order has to say everything.

def get(path):
    req = urllib.request.Request(BASE + path)
    with urllib.request.urlopen(req) as resp:
        return resp.status


print(get("/api/users/42"))
print(get("/api/users/42"))
print(get("/api/users"))
200
200
200

The second request is identical to the first, and the server has no idea it has seen you before. Careful, though: the user list is still stored on the server. What it doesn't keep is any memory of you between requests. So each request carries everything it needs, including who you are.

POST creates

body = json.dumps({"name": "Bob"}).encode()
req = urllib.request.Request(
    BASE + "/api/users",
    data=body,
    method="POST",
    headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req) as resp:
    print(resp.status)
    print(json.loads(resp.read()))
201
{'id': 43, 'name': 'Bob'}

The name Bob becomes JSON, then bytes: that's the request body. There's no id in the address, because the server picks it. 201 means created, and the body gives you the new record with its id. POST isn't safe to repeat: send it twice and you get two Bobs.

PUT and PATCH

People mix these two up.

def send(method, data):
    req = urllib.request.Request(
        BASE + "/api/users/42",
        data=json.dumps(data).encode(),
        method=method,
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req) as resp:
        return resp.status, json.loads(resp.read())


print(send("PATCH", {"email": "[email protected]"}))
print(send("PUT", {"name": "Alicia"}))
(200, {'id': 42, 'name': 'Alice', 'email': '[email protected]'})
(200, {'id': 42, 'name': 'Alicia'})

PATCH sent only an email, so only the email changed and the name stayed. PUT sent only a name, and PUT replaces the whole record, so the email is gone. With PUT, send the full record.

DELETE removes

import urllib.error
import urllib.request
from shop_api import start

BASE = start()
url = BASE + "/api/users/42"

req = urllib.request.Request(url, method="DELETE")
with urllib.request.urlopen(req) as resp:
    print(resp.status, resp.read())

try:
    urllib.request.urlopen(url)
except urllib.error.HTTPError as err:
    print(err.code)
204 b''
404

204 means done, with nothing to send back, which is why the body is empty. Ask for the same user again and urlopen raises an HTTPError with code 404: that user doesn't exist any more.

Status codes

The first digit tells you the family. 2xx means it worked: you've seen 200, 201 and 204. 4xx means the problem is in the request:

try:
    urllib.request.urlopen(BASE + "/api/nothing")
except urllib.error.HTTPError as err:
    print(err.code, err.reason)
    print(err.read())
404 Not Found
b'{"error": "not found"}'
req = urllib.request.Request(
    BASE + "/api/users",
    data=json.dumps({"email": "[email protected]"}).encode(),
    method="POST",
)
try:
    urllib.request.urlopen(req)
except urllib.error.HTTPError as err:
    print(err.code)
    print(json.loads(err.read()))
400
{'error': 'name is required'}

You'll also meet 401, unauthorized, when the server doesn't know who you are. 5xx means the server itself has a problem, like 500 internal server error or 503 service unavailable. Your request may be fine, and the fix is on the server side. So read the code first, every time. That one number tells you where to look.

Recap

  • An API lets programs talk. REST gives each resource an address and uses the method for the action.
  • GET reads, POST creates, PUT replaces, PATCH changes a part, DELETE removes.
  • Every request stands alone and carries what it needs.
  • The status code family tells you how it went: 2xx worked, 4xx your request, 5xx the server.

Try it yourself: in not_found.py, request a path that doesn't exist and read the status code. Or ask an AI tool to write the request, then read every line it gives you. When you're ready to build the server side, start with FastAPI hello world.

Keep going in FastAPI · 2 of 26

Previous
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
Next post
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

FastAPI Hello World: Routes, uvicorn and the Free Swagger Page

The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

One Request, Two Answers: the Same Post as an HTML Page and as JSON

Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.

On this page

  • What REST adds
  • A tiny server to talk to
  • Your first request: GET
  • Query parameters
  • Requests are stateless
  • POST creates
  • PUT and PATCH
  • DELETE removes
  • Status codes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.