Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

FastAPI - Hello World

  • FastAPI

  • get

  • virtualenv

  • The requirements include both FastAPI and pytest so we can write and run tests for our web application.

fastapi[all]
pytest
  • It is recommended to set up a virtual environment or use some other way to separate environments.
virtualenv -p python3 venv
source venv/bin/activate
pip install -r requirements.txt
  • We need a single file in which we import the FastAPI class.
  • We then create an instance of it. We can call it any name, but most of the examples are using app so we'll use that as well.
  • For each URL path we need to create a mapping to indicate which function needs to be executed when someone access that path.
  • The functions are defined as async so FastAPI can handle several requests at the same time. The name of the function does not matter.
  • The decorator @app.get("/") is doing the mapping.
  • The function needs to return some Python data structure that will be converted to JSON when it is sent back to the client.
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

  • In order to see this working launch the development web server that comes with the installation of FastAPI.
fastapi dev main.py

Then visit http://localhost:8000/

You can also visit some other pages on this site:

  • http://localhost:8000/docs to see the documentation generated by Swagger UI

  • http://localhost:8000/redoc to see the documentation generated by Redoc

  • http://localhost:8000/openapi.json

  • path - endpoint - route