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.
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:
| Method | Does | Example |
|---|---|---|
| GET | Reads | Open a profile |
| POST | Creates | Sign up, add a comment |
| PUT | Replaces the whole thing | Send the full record |
| PATCH | Changes a part | Edit your bio |
| DELETE | Removes | Delete 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.
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.
StudyEasy AI Community
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
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.
