How to Create GET Endpoints in FastAPI

Many guides still stop at one hello-world route. It runs, but a real API also has to return lists, single records and a proper 404.

In this tutorial, I’ll build a FastAPI GET endpoint the fuller way: decorate a function with @app.get(), return your data, and FastAPI sends it as JSON.

Everything below ran on Python 3.12.5 and FastAPI 0.162.2, using a small US job board API.

The sample job board API we’ll use

Three jobs live in a plain list, so there’s no database to set up. If FastAPI isn’t installed yet, install FastAPI and create your first API first. Here’s the complete main.py:

from fastapi import FastAPI, HTTPException

app = FastAPI()

JOBS = [
    {"id": 1, "title": "Data Analyst", "city": "Austin"},
    {"id": 2, "title": "Python Developer", "city": "Denver"},
    {"id": 3, "title": "QA Engineer", "city": "Austin"},
]


@app.get("/jobs")
def list_jobs(city: str | None = None):
    if city:
        return [job for job in JOBS if job["city"] == city]
    return JOBS


@app.get("/jobs/featured")
def featured_job():
    return JOBS[1]


@app.get("/jobs/{job_id}")
def get_job(job_id: int):
    for job in JOBS:
        if job["id"] == job_id:
            return job
    raise HTTPException(status_code=404, detail="Job not found")

Start it from the folder holding the file with fastapi dev main.py.

VS Code showing the FastAPI job board main.py with GET routes and the fastapi dev server running on port 8000
The server is up on port 8000, and it reloads when you save the file.

Method 1: Return a list from a FastAPI GET endpoint (Recommended)

Start here, because every other route builds on it. If routes are new to you, the FastAPI beginner tutorial sets the scene. The decorator names the URL, and the function’s return value becomes the response:

@app.get("/jobs")
def list_jobs(city: str | None = None):
    ...
    return JOBS

Open http://127.0.0.1:8000/jobs in a browser, and the same job board comes back as three JSON objects:

[{"id":1,"title":"Data Analyst","city":"Austin"},{"id":2,"title":"Python Developer","city":"Denver"},{"id":3,"title":"QA Engineer","city":"Austin"}]
Browser showing the JSON list of three US jobs returned by a FastAPI GET endpoint
A browser address bar always sends a GET request, so this is your quickest test.

How does this work?

@app.get("/jobs") registers the function for GET requests on that path. FastAPI converts the Python list to JSON and returns status 200.

Method 2: Get a single item with a path parameter

Use this when the URL identifies one record. Same JOBS list, but now the braces capture part of the URL, and a for loop finds the match:

@app.get("/jobs/{job_id}")
def get_job(job_id: int):

This script calls the running server, and /jobs/2 returns the Python Developer role in Denver:

import httpx

BASE = "http://127.0.0.1:8000"
PATHS = ["/jobs/2", "/jobs/99", "/jobs/abc", "/jobs?city=Austin",
         "/jobs?city=austin", "/jobs/featured"]

for path in PATHS:
    r = httpx.get(BASE + path)
    body = r.json()
    if r.status_code == 422:
        body = body["detail"][0]["msg"]
    print(r.status_code, path, body)

Output:

200 /jobs/2 {'id': 2, 'title': 'Python Developer', 'city': 'Denver'}
404 /jobs/99 {'detail': 'Job not found'}
422 /jobs/abc Input should be a valid integer, unable to parse string as an integer
200 /jobs?city=Austin [{'id': 1, 'title': 'Data Analyst', 'city': 'Austin'}, {'id': 3, 'title': 'QA Engineer', 'city': 'Austin'}]
200 /jobs?city=austin []
200 /jobs/featured {'id': 2, 'title': 'Python Developer', 'city': 'Denver'}
Command Prompt output of FastAPI GET requests returning 200, a 404 not found, a 422 validation error and query parameter results
One script, six URLs: 200 for a match, 404 for a missing job and 422 for a bad type.

How does this work?

The int type hint makes FastAPI convert "2" to 2. That’s why /jobs/abc gets a 422 before your function even runs.

Job 99 passes validation but isn’t in the list, so raise HTTPException(status_code=404, ...) sends the 404 with {'detail': 'Job not found'}.

Method 3: Filter the list with a query parameter

Any function argument that’s not in the path is read from the query string. On the same list, /jobs?city=Austin returns 2 of the 3 jobs.

How does this work?

city: str | None = None makes the filter optional, so plain /jobs still returns everything. The output above also shows ?city=austin returning [], because my comparison is case-sensitive.

The filter itself is a list comprehension, so swap in a .lower() check if you want case-insensitive matching.

Why does route order matter in FastAPI?

FastAPI checks routes in the order you declare them. Here’s what the job board does with /jobs/featured moved below /jobs/{job_id}:

import httpx

r = httpx.get("http://127.0.0.1:8000/jobs/featured")
print(r.status_code, r.json()["detail"][0]["msg"])

Output:

422 Input should be a valid integer, unable to parse string as an integer
Command Prompt output showing a FastAPI 422 error because /jobs/featured matched the job_id path parameter route
With the routes swapped, “featured” is treated as a job ID.

Important: Declare fixed paths like /jobs/featured before /jobs/{job_id}. In the correct order, it returned job 2.

This matters more once routes spread across files, which the FastAPI project structure guide covers.

Should a GET endpoint use def or async def?

Plain def is fine here. FastAPI runs it in a threadpool so it doesn’t block the server. Use async def when the function awaits an async library.

Test FastAPI GET endpoints in /docs

Open http://127.0.0.1:8000/docs for the Swagger UI page FastAPI generates from your routes:

Swagger UI at /docs listing the three FastAPI GET endpoints of the job board API
All three GET routes appear automatically.

Expand Get Job, click Try it out, enter 99 for job_id, and click Execute. You’ll get the real 404:

Swagger UI Try it out for the FastAPI get job endpoint showing a 404 Job not found response for job 99
Swagger UI sends a real request to your running server.

Edits reload automatically under fastapi dev. The Uvicorn guide covers production runs.

Which FastAPI GET method should you use?

You needUseJob board example
Every recordPlain route/jobs
One record by IDPath parameter/jobs/2
An optional filterQuery parameter/jobs?city=Austin
A fixed special pageFixed path, declared first/jobs/featured

Things to Keep in Mind

  • Put fixed paths above path parameters, or you’ll get a 422.
  • Raise HTTPException for a missing record; returning None gives a 200.
  • Give query parameters a default, or they become required.
  • Use the int type hint on IDs, so bad values fail with a clear 422.

Keep building your API with these:

Frequently asked questions

How do I create a GET endpoint in FastAPI?

Decorate a function with @app.get("/path") and return a dict or list.

What’s the default status code?

200. Raise HTTPException to send a 404 or another error.

Why am I getting a 422 error?

A value failed validation, such as text sent to an int path parameter.

Can a GET endpoint have both path and query parameters?

Yes. Names in the path braces are path parameters, and the other arguments are query parameters.

Where can I read the official reference?