Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 20 min · revision 3

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

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 answers 200 with a tiny JSON body;
  • POST /notes, which validates a JSON body with a Pydantic model and answers 201 Created with a Location header;
  • GET /notes/{note_id}, which answers 200 with the note, or 404 when 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.

Terminal 1
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)"
Expected output
0.163.1 2.14.3

FastAPI'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:

main.py
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.

Terminal 1
uvicorn main:app --reload
Expected output (paths and process ids differ)
INFO:     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:

Terminal 2
curl -i http://127.0.0.1:8000/health
Expected output (your date line will differ)
HTTP/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:

main.py
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 note parameter is a Pydantic model, FastAPI reads the request body as JSON and validates it against NoteIn before your function runs: title must be a string of 1 to 100 characters, and body is optional.
  • status_code=201 changes the success status of this route from the default 200 to 201 Created.
  • The response parameter lets you add headers; here, a Location header that points at the new note.
  • The return annotation -> Note tells 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.

Terminal 2
curl -i -X POST http://127.0.0.1:8000/notes \
  -H 'Content-Type: application/json' \
  -d '{"title": "Buy milk", "body": "Semi-skimmed"}'
Expected output (your date line will differ)
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:

main.py (changes only)
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.

Terminal 2
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
Expected output (your date line will differ)
{"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:

Terminal 2
curl -s -X POST http://127.0.0.1:8000/notes \
  -H 'Content-Type: application/json' -d '{"body": "no title"}' \
  | python -m json.tool
Expected output
{
    "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:

Terminal 2
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/abc
Expected output in terminal 2, then the log lines in terminal 1 (client ports differ)
422
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 Content

Run 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:

Terminal 2
curl -i -X DELETE http://127.0.0.1:8000/notes/1
Expected output (your date line will differ)
HTTP/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:

app/api/notes/route.ts (Next.js)
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

Practice check · 3 questions

Check your endpoint knowledge

Questions about the server you have just built.

Q1. What does main:app mean in the command uvicorn main:app --reload?
Q2. GET /notes/7 asks for a note that does not exist. What should the handler do?
Q3. curl -d '{"title": "x"}' http://127.0.0.1:8000/notes gets a 422, even though the JSON is valid. Why?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check