FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to make it easy to build APIs quickly and efficiently. This tutorial will walk you through creating your first FastAPI project step by step.
Prerequisites
Before diving into FastAPI, ensure that you have the following prerequisites:
- Python 3.7 or higher installed on your machine.
- Basic knowledge of Python programming and REST API concepts.
- An IDE or text editor (e.g., Visual Studio Code, PyCharm, etc.).
- Familiarity with terminal/command prompt navigation.
Step 1: Set Up Your Development Environment
First, set up a virtual environment for your FastAPI project. This step is crucial to avoid package conflicts.
-
Create a project directory:
mkdir fastapi_project cd fastapi_project -
Set up a virtual environment:
Usevenvto create a virtual environment:python -m venv venv -
Activate the virtual environment:
- On Windows:
venvScriptsactivate - On macOS/Linux:
source venv/bin/activate
- On Windows:
Step 2: Install FastAPI and Uvicorn
FastAPI is a framework, and Uvicorn is the ASGI server that will run your application.
- Install FastAPI and Uvicorn:
Run the following command in your terminal:pip install fastapi uvicorn
Step 3: Create Your First FastAPI Application
Now, it’s time to create your first FastAPI application.
-
Create a new Python file:
Within your project directory, create a new file namedmain.py:touch main.py -
Write a simple FastAPI application:
Openmain.pyand add the following code:from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}
Step 4: Run Your FastAPI Application
To run your FastAPI application, use Uvicorn.
-
Run the application:
Execute the following command in your terminal:uvicorn main:app --reload -
Access your application:
Open your web browser and go tohttp://127.0.0.1:8000. You should see:{"Hello": "World"} -
Access the auto-generated documentation:
FastAPI automatically generates documentation for your API based on your code. Visithttp://127.0.0.1:8000/docsto view the Swagger UI, where you can test your API.
Step 5: Handle Query Parameters and Path Parameters
Your FastAPI application can handle both query parameters and path parameters seamlessly. Let’s add more complexity to our application by using these parameters.
-
Modify the
main.pyfile:
Update theread_itemfunction to handle a query parameterq. This is already done in the previous step, but for clarity, here’s the relevant code again:@app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} -
Test the query parameters:
Visit:http://127.0.0.1:8000/items/5?q=somequeryYou should receive a response like:
{"item_id": 5, "q": "somequery"}
Step 6: Create a POST Endpoint
FastAPI allows you to create endpoints that can accept data via HTTP POST requests. Let’s create a simple endpoint to accept data.
-
Add a POST endpoint:
Updatemain.pyto include a POST endpoint:from pydantic import BaseModel class Item(BaseModel): name: str price: float is_offer: bool = None @app.post("/items/") async def create_item(item: Item): return {"item_name": item.name, "item_price": item.price, "is_offer": item.is_offer} -
Test the POST endpoint:
Use a tool like Postman or curl to send a POST request with JSON data.
Examplecurlcommand:curl -X 'POST' 'http://127.0.0.1:8000/items/' -H 'accept: application/json' -H 'Content-Type: application/json' -d '{ "name": "Sample Item", "price": 25.5, "is_offer": true }'You should receive a response like:
{"item_name": "Sample Item", "item_price": 25.5, "is_offer": true}
Step 7: Adding Validation with Pydantic
FastAPI uses Pydantic for data validation. This ensures that the incoming data is valid before it is processed.
-
Define a Pydantic model:
TheItemclass used previously serves as a Pydantic model. The type hints indicate the expected data types of the input. -
Error handling:
If you test your POST endpoint with incorrect data (e.g., sending a string where a float is expected), FastAPI will automatically return a 422 Unprocessable Entity response with detailed error messages.
Step 8: Adding Middleware
You may want to add middleware for various purposes, such as logging or handling CORS.
-
Adding CORSMiddleware:
Modify yourmain.pyfile to include CORS support:from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Allows all origins allow_credentials=True, allow_methods=["*"], # Allows all methods allow_headers=["*"], # Allows all headers ) -
Test for CORS:
You can now test your API from a different origin without triggering CORS errors.
Step 9: Creating Additional Routes
As your application grows, you will likely need to create more routes. Consider organizing your routes in a structured manner.
-
Creating routers:
Create a new directory calledrouters, and then create a fileitems.pywithin it:mkdir routers touch routers/items.py -
Define your routes in
items.py:from fastapi import APIRouter from pydantic import BaseModel router = APIRouter() class Item(BaseModel): name: str price: float is_offer: bool = None @router.post("/items/") async def create_item(item: Item): return {"item_name": item.name, "item_price": item.price, "is_offer": item.is_offer} -
Include the router in your main app:
Inmain.py, import and include the router:from routers.items import router as items_router app.include_router(items_router)
Step 10: Testing Your FastAPI Application
FastAPI provides a robust testing framework as part of its package.
-
Create a
testsfolder:mkdir tests touch tests/test_main.py -
Write tests:
Use thehttpxlibrary for making requests in your tests. Installhttpx:pip install httpx -
Example test code:
Here’s an example test filetest_main.py:from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_read_root(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"Hello": "World"} def test_create_item(): response = client.post("/items/", json={"name": "Test", "price": 10.0}) assert response.status_code == 200 assert response.json() == {"item_name": "Test", "item_price": 10.0, "is_offer": None} -
Run the tests:
Execute the tests using:pytest tests
Step 11: Deploying Your FastAPI Application
Once your application is tested and ready, you can deploy it using various cloud platforms like AWS, Google Cloud, or Heroku. Here are some general steps for deploying:
-
Containerization:
Use Docker to containerize your FastAPI application. -
Deployment:
Choose an appropriate service to deploy your container:- Docker: For local tests and private servers.
- Heroku: For easy deployments without managing servers.
-
Dockerfile Example:
Here’s a simple example of a Dockerfile:FROM python:3.9 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] -
Build and run:
Build your image:docker build -t fastapi_app .Run the container:
docker run -d -p 80:80 fastapi_app
Final Note
Creating a FastAPI application is a straightforward process that leverages modern Python features. By following the steps outlined in this tutorial, you should now have a basic FastAPI application capable of handling GET and POST requests, as well as a foundation for further development and deployment. Happy coding!