Lab: Your First JSON Endpoint
Serve a small JSON API locally with FastAPI, then verify its status codes, headers and bodies with curl, as any client would see them.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Serve a health route
- Step 2: Create notes with POST
- Step 3: Read a note, or answer 404
- Step 4: Watch validation reject bad input
- Step 5: Check method handling and the generated docs
- The same endpoint in Node or Next.js
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of HTTP & APIs
- What Travels Over the Wire: Requests, Responses and HTTPS Concept · 20 min
- Methods, Status Codes and Idempotency Concept · 20 min
- Lab: Inspecting Traffic with curl and DevTools Lab · 20 min
- Calling a Public JSON API from Python or TypeScript Worked example · 25 min
- Lab: Your First JSON Endpoint Lab · 20 min
- Check: Read the Exchange, Predict the Outcome Knowledge check · 10 questions
What you will learn
- Serve a minimal JSON endpoint locally (a FastAPI route in the reference stack, or a Node or Next.js route handler) and verify its status, headers and body with curl.
Prerequisites: Python Foundations
01. Goal and setup
So far you have called other people's APIs. Now you serve one. You will build a small notes API with FastAPI, run it locally with uvicorn and check every response with curl -i, exactly as a client sees it. By the end it will have three routes:
GET /health, which answers200with a tiny JSON body;POST /notes, which validates a JSON body with a Pydantic model and answers201 Createdwith aLocationheader;GET /notes/{note_id}, which answers200with the note, or404when it does not exist.
You need Python 3.11 or later (current FastAPI releases no longer install on 3.10), curl, and two terminals: one runs the server, the other sends requests. The lab was tested with Python 3.13, FastAPI 0.163.1, Pydantic 2.14.3 and uvicorn 0.54.0, and the install below pins those versions so your output matches. A newer FastAPI release built on Pydantic 2 behaves the same way for these routes, though error messages may be worded slightly differently.
mkdir notes-api && cd notes-api
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install fastapi==0.163.1 pydantic==2.14.3 'uvicorn[standard]==0.54.0'
python -c "import fastapi, pydantic; print(fastapi.__version__, pydantic.VERSION)"0.163.1 2.14.3FastAPI's own tutorial installs fastapi[standard], which adds a fastapi dev command and several optional extras. Plain fastapi plus uvicorn is all this lab needs.
02. Step 1: Serve a health route
Create main.py in the notes-api folder:
from fastapi import FastAPI
app = FastAPI(title='Notes API')
@app.get('/health')
def health() -> dict[str, str]:
return {'status': 'ok'}Start the server in terminal 1. main:app means: import the module main and serve the object called app inside it. --reload restarts the server whenever you save a file, which is handy during development and should not be used in production.
uvicorn main:app --reloadINFO: Will watch for changes in these directories: ['/home/you/notes-api']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [41210] using WatchFiles
INFO: Started server process [41212]
INFO: Waiting for application startup.
INFO: Application startup complete.By default uvicorn listens on 127.0.0.1, the loopback address, on port 8000, so only your own machine can reach it. Leave it running and, in terminal 2, ask for the health route:
curl -i http://127.0.0.1:8000/healthHTTP/1.1 200 OK
date: Sat, 17 Oct 2026 13:37:17 GMT
server: uvicorn
content-length: 15
content-type: application/json
{"status":"ok"}Your function returned a Python dictionary; FastAPI serialised it to JSON and set content-type: application/json for you. FastAPI does not end the body with a newline, so your shell prompt may appear straight after }. uvicorn speaks plain HTTP/1.1 without TLS, which is normal for local development; in production, a proxy or hosting platform in front of the app usually handles HTTPS.
03. Step 2: Create notes with POST
Replace main.py with this version, which adds two Pydantic models, an in-memory store and a POST route:
from fastapi import FastAPI, Response
from pydantic import BaseModel, Field
app = FastAPI(title='Notes API')
class NoteIn(BaseModel):
title: str = Field(min_length=1, max_length=100)
body: str = ''
class Note(NoteIn):
id: int
notes: dict[int, Note] = {} # in memory: emptied on every restart
@app.get('/health')
def health() -> dict[str, str]:
return {'status': 'ok'}
@app.post('/notes', status_code=201)
def create_note(note: NoteIn, response: Response) -> Note:
new_note = Note(id=len(notes) + 1, **note.model_dump())
notes[new_note.id] = new_note
response.headers['Location'] = f'/notes/{new_note.id}'
return new_note- Because the
noteparameter is a Pydantic model, FastAPI reads the request body as JSON and validates it againstNoteInbefore your function runs:titlemust be a string of 1 to 100 characters, andbodyis optional. status_code=201changes the success status of this route from the default 200 to 201 Created.- The
responseparameter lets you add headers; here, aLocationheader that points at the new note. - The return annotation
-> Notetells FastAPI how to validate, serialise and document the response.
Generating ids with len(notes) + 1 is a lab simplification; a real service lets its database assign them. Save the file (uvicorn reloads), then create a note from terminal 2. With curl 7.82 or later, --json can replace the -H and -d pair.
curl -i -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' \
-d '{"title": "Buy milk", "body": "Semi-skimmed"}'HTTP/1.1 201 Created
date: Sat, 17 Oct 2026 13:37:17 GMT
server: uvicorn
content-length: 49
content-type: application/json
location: /notes/1
{"title":"Buy milk","body":"Semi-skimmed","id":1}04. Step 3: Read a note, or answer 404
Add a route with a path parameter. Change the first import line and add the new function at the end of main.py:
from fastapi import FastAPI, HTTPException, Response
# ... models, notes, health and create_note stay as they are ...
@app.get('/notes/{note_id}')
def get_note(note_id: int) -> Note:
if note_id not in notes:
raise HTTPException(status_code=404, detail='Note not found')
return notes[note_id]{note_id} in the path becomes the note_id argument, converted to an int. Raising HTTPException stops the handler and sends the status you chose with a JSON body of the form {"detail": ...}.
Saving the file restarted the server and emptied the in-memory store, so create a note again, then read it back and ask for one that does not exist. -w '\n' prints a newline after each body to keep the output tidy.
curl -s -w '\n' -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' -d '{"title": "Buy milk"}'
curl -i -w '\n' http://127.0.0.1:8000/notes/1
curl -i -w '\n' http://127.0.0.1:8000/notes/99{"title":"Buy milk","body":"","id":1}
HTTP/1.1 200 OK
date: Sat, 17 Oct 2026 13:49:23 GMT
server: uvicorn
content-length: 37
content-type: application/json
{"title":"Buy milk","body":"","id":1}
HTTP/1.1 404 Not Found
date: Sat, 17 Oct 2026 13:49:23 GMT
server: uvicorn
content-length: 27
content-type: application/json
{"detail":"Note not found"}05. Step 4: Watch validation reject bad input
Send a note without the required title. python -m json.tool pretty-prints the JSON error so you can read it:
curl -s -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' -d '{"body": "no title"}' \
| python -m json.tool{
"detail": [
{
"type": "missing",
"loc": [
"body",
"title"
],
"msg": "Field required",
"input": {
"body": "no title"
}
}
]
}FastAPI checked the body against NoteIn before create_note ran, and answered with status 422 and a list of problems: type says what went wrong, loc where (the title field of the body) and msg gives a readable explanation. Now send an empty title and a note id that is not a number, printing only the status codes:
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8000/notes \
-H 'Content-Type: application/json' -d '{"title": ""}'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/notes/abc422
422
INFO: 127.0.0.1:59168 - "POST /notes HTTP/1.1" 422 Unprocessable Content
INFO: 127.0.0.1:59174 - "POST /notes HTTP/1.1" 422 Unprocessable Content
INFO: 127.0.0.1:59184 - "GET /notes/abc HTTP/1.1" 422 Unprocessable ContentRun the two commands again without -o /dev/null -w ... to read the bodies: their type values are string_too_short and int_parsing, and loc shows that one problem was in the body and the other in the path. The server log in terminal 1 is a quick way to confirm the status of every request. uvicorn takes the reason phrase from Python's http module: on Python 3.13 and later it prints "Unprocessable Content", as above, the name RFC 9110 uses; on Python 3.12 and earlier it prints the older "Unprocessable Entity". Only the number matters.
06. Step 5: Check method handling and the generated docs
Try a method that no route supports for this path:
curl -i -X DELETE http://127.0.0.1:8000/notes/1HTTP/1.1 405 Method Not Allowed
date: Sat, 17 Oct 2026 13:37:17 GMT
server: uvicorn
allow: GET
content-length: 31
content-type: application/json
{"detail":"Method Not Allowed"}FastAPI answers 405 with an Allow header listing the methods that exist for the path, without any code from you. Finally, open http://127.0.0.1:8000/docs in your browser. FastAPI generates interactive documentation from your routes and models, and the machine-readable OpenAPI description behind it is at /openapi.json. Use Try it out on POST /notes, then compare the request it sends with your curl command.
07. The same endpoint in Node or Next.js
Nothing in this lab is specific to Python. A route handler in any framework does the same four things: match the method and path, parse and validate the body, choose a status code, and return a body with the right headers. In a Next.js App Router project, a file at app/api/notes/route.ts that exports a POST function handles POST /api/notes:
type Note = { id: number; title: string; body: string };
const notes = new Map<number, Note>(); // in memory: fine for a demo, lost on restart
export async function POST(request: Request) {
const input = (await request.json().catch(() => null)) as Partial<Note> | null;
if (typeof input?.title !== 'string' || input.title.length === 0) {
return Response.json({ detail: 'title is required' }, { status: 422 });
}
const note: Note = { id: notes.size + 1, title: input.title, body: input.body ?? '' };
notes.set(note.id, note);
return Response.json(note, {
status: 201,
headers: { Location: `/api/notes/${note.id}` },
});
}Response.json serialises the object and sets content-type: application/json, and its second argument carries the status and headers. Next.js does not validate bodies for you, so the check is written by hand here; in a real project a schema library such as Zod plays the role Pydantic plays in FastAPI. Express, Fastify and the built-in node:http module follow the same pattern. Start the Next.js dev server and test the route with the same curl commands, on port 3000 and the /api/notes path.
08. Troubleshooting
09. Check your understanding
10. Apply it: stretch task
Finish this skill's practice project. Add a GET /repos route that returns the fields your script from the previous lesson saved in results.json, including the HTTP version it recorded. Either read the file in the handler, or call your httpx function directly and turn its failures into 502 or 504 responses with a clear detail. Verify the route with curl -i: check the status line, content-type: application/json and the body.
Then add PUT /notes/{note_id}, which replaces a note and answers 404 when it does not exist. Send the same PUT twice and confirm with GET that the note is identical after each, because PUT must be idempotent. If you work in JavaScript, build both routes as Next.js or Node route handlers instead.
11. Review prompt
Without looking back, write a FastAPI route POST /tags that takes a JSON body with a required name, answers 201 with the new tag and a Location header, and a GET /tags/{tag_id} route that answers 404 when the tag is missing. Then write the curl commands that would prove each status code, header and body, and say what status a client gets when name is missing.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.