Skip to content

Building Your First API

We will learn FastAPI by building a simple blog, starting with an API that lists all posts.

Building an API means writing a function that performs a server-side task and connecting it to a client's request. When the client sends a request to the registered path with the matching HTTP method, the server runs the associated function and returns its result.

A client's GET /posts request is routed to a server function, which returns a list of posts

Listing All Posts

Update main.py as follows:

main.py
from fastapi import FastAPI

app = FastAPI()

posts = [  # ①
    {"id": 1, "title": "First post", "content": "Starting my blog"},
    {"id": 2, "title": "Second post", "content": "Thanks for stopping by"},
]


@app.get("/posts")  # ②
def get_posts_handler():  # ③
    return posts  # ④

① defines posts, a Python list containing our post data. We are not using a database yet, so the server keeps its data in this list. Each dictionary represents a post: id is its identifier, title its title, and content its body.

③ defines get_posts_handler, which retrieves all posts. ④ returns the data stored in ①.

A function that handles a client's request is called a request handler. It is an ordinary Python function with a particular role in FastAPI. In this guide, we add _handler to these function names to distinguish them from other functions.

We do not call this function ourselves. We define it on the server so clients can use it by sending a request. That is why the code contains no direct call such as get_posts_handler().

We decide what should happen when a request arrives and define a function for it. FastAPI calls the function. We still need to tell FastAPI which requests should trigger it.

②, @app.get("/posts"), registers the function immediately below it to handle GET /posts. An expression beginning with @ above a function is called a decorator.

What Is a Decorator?

A decorator is Python syntax for adding behavior without editing a function's body, or registering a function for a particular purpose.

Consider two functions with different execution times. You can try this code in a separate Python file.

from time import sleep


def short_work():
    sleep(0.1)
    print("Short task complete")


def long_work():
    sleep(1)
    print("Long task complete")

short_work finishes quickly, while long_work takes longer.

To measure how long each function takes, define a timer function:

from time import perf_counter


def timer(func):
    def wrapper(*args, **kwargs):
        start = perf_counter()
        result = func(*args, **kwargs)
        end = perf_counter()
        print(f"Elapsed time: {end - start:.3f} seconds")
        return result

    return wrapper

timer accepts a function and returns a wrapper that surrounds it. The wrapper records the time before and after calling the original function, prints the difference, and returns the original result.

Passing our functions to timer returns wrappers that measure execution time. Store them in variables and call them:

short_work_with_timer = timer(short_work)
long_work_with_timer = timer(long_work)

short_work_with_timer()
long_work_with_timer()

Calling short_work_with_timer() runs short_work() inside the wrapper, then prints the elapsed time after the completion message. long_work_with_timer() works the same way.

Short task complete
Elapsed time: 0.101 seconds
Long task complete
Elapsed time: 1.001 seconds

Actual timings will vary with your environment.

Decorators let you reuse shared behavior across functions without editing their bodies. Each function can focus on its task, while extra behavior such as timing is managed in one place. This reduces duplication and makes changes easier.

Python lets you apply the same behavior more concisely by placing @timer directly above a function definition:

@timer
def short_work():
    sleep(0.1)
    print("Short task complete")


@timer
def long_work():
    sleep(1)
    print("Long task complete")


short_work()
long_work()

@timer is shorthand for wrapping the defined function with an assignment such as short_work = timer(short_work). You can now call the original name to perform the work and measure its time. The decorator also makes the added behavior visible above the function.

Routing

FastAPI uses decorators for routing: finding the appropriate handler for a request. As the diagram shows, routing determines which function runs when a client sends a particular request.

Web APIs choose a handler based on the request path and HTTP method. For example, /posts is a path for working with posts, and GET is the HTTP method for retrieving data.

@app.get("/posts") expresses both conditions: get matches the GET method, and "/posts" matches the path. When both match, FastAPI calls the function directly below the decorator.

@app.get("/posts")
def get_posts_handler():
    return posts

FastAPI calls get_posts_handler when a request matches. Even with many functions on the server, this registration directs each request to the right handler.

Testing the API

Save main.py and make sure the development server is running. If you stopped it, run fastapi dev again with the virtual environment active.

Open http://127.0.0.1:8000/posts in your browser. The browser sends GET /posts. FastAPI runs get_posts_handler and converts the returned posts list into a JSON response.

If you see the following list, the API is working. Your browser may display different indentation or line breaks.

[
  {
    "id": 1,
    "title": "First post",
    "content": "Starting my blog"
  },
  {
    "id": 2,
    "title": "Second post",
    "content": "Thanks for stopping by"
  }
]

Swagger UI

To use an API, you need to know its path, HTTP method, input, and response. API documentation explains this interface. It lets developers use an API without reading its server code and provides a shared reference for testing it.

FastAPI generates a specification in the OpenAPI standard from the registered APIs. Swagger UI turns that specification into readable, interactive documentation, available at /docs by default.

OpenAPI and Swagger UI

OpenAPI is unrelated to OpenAI, the company behind ChatGPT. OpenAPI is a specification format; Swagger UI is a tool for displaying that specification.

Different tools can display the same specification. FastAPI provides Swagger UI at /docs and an alternative, ReDoc, at /redoc by default.

Swagger UI shows request paths, HTTP methods, and inputs, and lets you send HTTP requests from your browser and inspect the responses. It is useful during development because you can test APIs without writing a separate client.

Documentation Layout

  1. The application title appears at the top.
  2. The API list identifies operations by method and path, such as GET /posts.
  3. Parameters shows request inputs when you expand an operation. Use it to enter values such as a post ID or search term.
  4. Responses describes expected status codes and response formats.
  5. Server response shows the actual status code and body after you click Execute.

Swagger UI layout: application title, API list, Parameters, expected Responses, and actual Server response

Retrieving Posts

With the development server running, open http://127.0.0.1:8000/docs. You should see the GET /posts operation.

  1. Expand GET /posts.
  2. Click Try it out.
  3. This API has no inputs, so click Execute.
  4. Check for status code 200 under Server response.
  5. Check the two posts under Response body.

When you click Execute, Swagger UI acts as a client and sends GET /posts to the server. The server runs get_posts_handler and returns its list as JSON. This calls the same API as entering /posts in the address bar, using a different interface.

We will also use Swagger UI to enter input and inspect results as we build more APIs.

Setting the Application Title

Set title when creating the FastAPI app to name it in Swagger UI. Replace app = FastAPI() in main.py with:

app = FastAPI(title="Blog API")

Save the file and refresh http://127.0.0.1:8000/docs. The default title, FastAPI, is now Blog API. This changes the documentation title without affecting the /posts path or response data.

Adding an API Summary

The routing decorator's summary argument provides a short description in the documentation. Add one to the API that lists posts:

main.py
@app.get("/posts", summary="List all posts")
def get_posts_handler():
    return posts

Save the file and refresh /docs. The generated documentation now shows List all posts next to GET /posts.

Check Your Understanding

Decide whether each statement is true or false.

  1. FastAPI calls the registered handler when a matching request arrives.
  2. A decorator requires you to edit the original function's body to add behavior.
  3. Choosing a handler based on a request is called routing.
  4. A GET routing decorator registers a handler for GET requests at its specified path.
  5. Swagger UI can send HTTP requests to the server from a browser.
Answers and Explanations
  1. True — FastAPI calls the registered handler and sends its return value as a response.
  2. False — A decorator adds behavior without editing the original body and can share behavior across functions.
  3. True — Routing matches conditions such as the request path and HTTP method to a handler.
  4. True — Both the method and path determine which handler runs.
  5. True — Clicking Execute sends a request through the browser.