Welcome to our beginner-friendly guide to FastAPI, a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It's incredibly easy to learn and use, with a rich set of features that will help you build robust and scalable APIs.
Why FastAPI?
In the rapidly evolving landscape of web development, efficiency and developer experience are paramount. FastAPI stands out by:
- High Performance: It's one of the fastest Python web frameworks available, comparable to NodeJS and Go, thanks to Starlette for the web parts and Pydantic for the data parts.
- Fast to code: Increase development speed by about 200% to 300%.
- Fewer bugs: Significantly reduce human-induced errors by about 40% thanks to Python type hints.
- Intuitive: Great editor support. Autocompletion everywhere. Less time debugging.
- Easy: Designed to be easy to use and learn.
- Short: Minimize code duplication.
- Robust: Get production-ready code.
- Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (formerly Swagger) and JSON Schema.
Installation
Getting started with FastAPI is as simple as installing a couple of packages. You'll need Python 3.7+ and pip.
pip install fastapi uvicorn[standard]
fastapi is the core framework, and uvicorn is an ASGI server that will run your application. The [standard] extra installs recommended dependencies for uvicorn for optimal performance.
Your First FastAPI Application
Let's create a minimal "Hello World" API. Create a file named main.py with the following content:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
Now, run the application using uvicorn:
uvicorn main:app --reload
This command starts a local development server. The main refers to the file main.py. The app refers to the object created inside main.py (app = FastAPI()). The --reload flag means the server will automatically reload when code changes are detected, which is very handy during development.
Open your browser and navigate to http://127.0.0.1:8000. You should see:
{"Hello":"World"}
Automatic API Documentation
One of FastAPI's most powerful features is its automatic generation of interactive API documentation. By default, it provides two interfaces:
- Swagger UI: Available at
/docs - ReDoc: Available at
/redoc
Visit http://127.0.0.1:8000/docs in your browser. You'll see an interactive UI where you can test your API endpoints directly!
Defining Path Operations with Parameters
Let's add an endpoint that takes a path parameter. Create a new endpoint in main.py:
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
Here, item_id is a path parameter. By annotating it with int, FastAPI automatically validates that the incoming item_id is an integer and returns an error if it's not.
Try accessing http://127.0.0.1:8000/items/5. You should get:
{"item_id":5}
If you try http://127.0.0.1:8000/items/foo, FastAPI will return a validation error.
Query Parameters
Parameters that are not part of the path are treated as query parameters. Let's add an optional query parameter:
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
Now, you can access it like this:
http://127.0.0.1:8000/items/5?q=somequeryhttp://127.0.0.1:8000/items/5
Notice how q: str | None = None makes q an optional parameter. If it's not provided, its value will be None.
Tip: FastAPI uses Pydantic models for data validation and serialization, which allows for powerful features like type checking, default values, and custom validation rules.
Conclusion
This guide covered the absolute basics of getting started with FastAPI, from installation to your first API endpoints and understanding automatic documentation. FastAPI's design principles make it a joy to work with, enabling developers to build robust and performant APIs with minimal effort. Dive deeper into the official documentation to explore features like request bodies, dependency injection, authentication, and much more!
Happy coding!