FastAPI Interactive Docs

First Steps

FastAPI is a beautiful development experience. The "Fast" in FastAPI leads to a bit misleading thought process.
The development experience is fast, scaffolding is fast, documentation is fast. Its not just fast from performance POV.

I would like you to first solve this lab. If you can solve it, no need to read below.

LAB 1:

In case you want to continue reading, below is the guide.

I hope you already have Python installed, next install the requirements.

requirements.txt
pip install fastapipip install "uvicorn[standard]"

Wait, what is uvicorn? FastAPI is just the framework, It does not know how to talk to the network. Uvicorn is an ASGI server that actually runs our application and handles the requests. Think of FastAPI as the chef and uvicorn as the waiter who brings orders to the kitchen.

Create a file named main.py:

main.py
from fastapi import FastAPIapp = FastAPI()@app.get("/")def home():    return {"message": "Hello, FastAPI!"}

Let's review what is happening here:

  1. We import the FastAPI class and create an instance named app. This app object is the heart of our application.

  2. @app.get("/") is a decorator. It tells FastAPI that the function below is responsible for handling GET requests on the path /.

  3. We return a dictionary and FastAPI automatically converts it to JSON. No manual serialization needed.

Running the app:

Go to your terminal and type:

uvicorn main:app --reload

Here main is the file name and app is the FastAPI instance we created. The --reload flag restarts the server whenever we change the code. Use it only in development, not in production.

You should see something like:

INFO:     Uvicorn running on http://127.0.0.1:8000INFO:     Application startup complete.

Open http://127.0.0.1:8000 in your browser and you will see our JSON response. šŸŽ‰

Automatic Docs:

Now visit http://127.0.0.1:8000/docs
Surprise! FastAPI has generated interactive Swagger documentation for our API. We did not write a single line for this.

āš ļø Do not name your file fastapi.py. Python will try to import your own file instead of the actual library and you will be stuck debugging a very confusing error. Trust me, been there. 😁