Your First FastAPI App

Make a project folder with a virtual environment, install FastAPI, write GET routes that return a dictionary and a list for FastAPI to send as JSON, run the app with fastapi dev, and try every route on its docs page at /docs.

Apprentice · FastAPI · REST API · Updated

By

After this lesson you can

  • Make a FastAPI app with app = FastAPI() and GET routes that return a dictionary or a list, which FastAPI sends back as JSON
  • Run an app with fastapi dev, open its routes at http://127.0.0.1:8000, try them on the /docs page, and stop it with Ctrl+C

Key takeaways

  • Installing fastapi[standard] brings FastAPI, Uvicorn (the web server that runs your app) and the fastapi command.
  • app = FastAPI() makes the app. A decorator such as @app.get("/specials") ties the function below it to GET requests for that address.
  • A route returns a dictionary or a list, and FastAPI sends it back as JSON.
  • fastapi dev main.py runs the app at http://127.0.0.1:8000 and reloads it each time you save. Ctrl+C stops it.
  • The docs page at /docs lists every route, and Try it out sends each one a real request.

Every API you'll build starts the same way: an empty folder, FastAPI installed, and one route that answers. This lesson takes you from nothing to an API answering in your browser, with a docs page you didn't have to write.

The example is Maple Street Bakery, whose owner wants today's specials, sourdough at $6.50 and a dozen bagels at $12.00, in the bakery's phone app.

A script can't answer a phone

A first try is a Python file that prints the specials:

print("Sourdough loaf: $6.50")
print("A dozen bagels: $12.00")
Sourdough loaf: $6.50
A dozen bagels: $12.00

It prints two lines in your terminal and stops. The bakery's app is on a customer's phone across town: it can't see your terminal, and by the time it asks, the program has ended. The app needs a program that keeps running, waits for requests and answers each one, called a web server, and something that decides which of your functions answers which address. FastAPI and the server that comes with it do both.

Set up the project

In VS Code's terminal, make a folder for the project in your python-course folder, go into it, and make and turn on a virtual environment, as Virtual Environments and pip shows. On Windows (PowerShell):

cd ~/python-course
mkdir maple-street-api
cd maple-street-api
python -m venv .venv
.venv\Scripts\Activate.ps1

On a Mac (zsh):

cd ~/python-course
mkdir maple-street-api
cd maple-street-api
python3 -m venv .venv
source .venv/bin/activate

With the prompt starting (.venv), install FastAPI:

pip install "fastapi[standard]==0.163.1"

[standard] asks for FastAPI's usual extras: Uvicorn, the web server that runs your app, and the fastapi command that starts it. The quotes keep zsh from reading the square brackets as a pattern, and PowerShell is fine with them. Then open the folder in VS Code (File > Open Folder) and make a file named main.py. If the new terminal's prompt doesn't start with (.venv), turn the environment on again.

Your first route

Put this in main.py:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def welcome():
    return {"bakery": "Maple Street Bakery", "message": "Fresh bread every morning"}
  • app = FastAPI() makes the app: the object that holds your routes, and the one the server runs.
  • @app.get("/"), read "at app dot get slash", is a decorator: a line starting with @ that ties the function below it to an address. This one ties welcome to GET requests for /, the address with nothing after the slash. GET is what a browser sends when you type an address: "get me what's there".
  • welcome is the route, the function that answers. It returns a dictionary, and FastAPI turns it into JSON.

Start the app in the terminal:

fastapi dev main.py

The terminal says the server started at http://127.0.0.1:8000, with documentation at http://127.0.0.1:8000/docs, and it keeps running: it's waiting for requests. Open http://127.0.0.1:8000 in your browser. It answers 200 OK ("here it is") with:

{"bakery":"Maple Street Bakery","message":"Fresh bread every morning"}

127.0.0.1 is the address every computer uses for itself, also called localhost, so the request never leaves your computer. 8000 is the port, the numbered door the server listens at. Each request shows up as a line in the terminal, such as "GET / HTTP/1.1" 200 OK.

VS Code's terminal after fastapi dev main.py: it says the server started at http://127.0.0.1:8000 with documentation at http://127.0.0.1:8000/docs, and a log line shows GET / answered 200 OK

Add a route, and the app reloads

Add a second route below the first, and save the file:

@app.get("/specials")
def list_specials():
    return [
        {"name": "Sourdough loaf", "price": 6.50},
        {"name": "A dozen bagels", "price": 12.00},
    ]

There's nothing to restart: fastapi dev watches your files, and the terminal says WatchFiles detected changes in 'main.py'. Reloading.... Open http://127.0.0.1:8000/specials:

[{"name":"Sourdough loaf","price":6.5},{"name":"A dozen bagels","price":12.0}]

A list comes back as a JSON array, in square brackets, with each dictionary inside it. (JSON writes 6.50 as 6.5; the app adds the zero back when it shows a price.) An address no route answers, such as /hours, gets 404 Not Found, "there's nothing at that address":

{"detail":"Not Found"}

The docs page, written for you

Open http://127.0.0.1:8000/docs. FastAPI has built a page that lists every route in your app, GET / and GET /specials, and it updates each time the app reloads. Click GET /specials, then Try it out, then Execute: the page sends a real request and shows the answer, code 200 and the same JSON. You'll try every route in this course on this page, so there's nothing else to install.

FastAPI's docs page with GET /specials opened after Try it out and Execute: the response shows code 200 and a body with the two specials, Sourdough loaf at 6.5 and A dozen bagels at 12.0

When you're done, click in the terminal and press Ctrl+C. The server stops, and the address stops answering until you run fastapi dev main.py again.

Check yourself

2 questions to try on the lesson page.

So what

One import, one line that makes the app and one decorator turn a Python function into an address any app can ask, and every API in this course grows from a file like this one.

Key terms

Related