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.
@app.get("/")def home(): return {"message": "Hello, FastAPI!"}Let's review what is happening here:
We import the
FastAPIclass and create an instance namedapp. Thisappobject is the heart of our application.@app.get("/")is a decorator. It tells FastAPI that the function below is responsible for handling GET requests on the path/.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 --reloadHere 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.
