Introduction
FastAPI is a modern, fast (high-performance) Python web framework for building APIs. It's designed to be easy to use, fast to code, and ready for production. In this guide, we'll walk through the process of creating your first FastAPI application.
Prerequisites
Before we begin, make sure you have:
- Python 3.6+ installed
- pip (Python package manager)
- A text editor or IDE of your choice
Step 1: Setting Up Your Environment
First, let's create a new directory for our project and set up a virtual environment:
mkdir fastapi-first-app cd fastapi-first-app python -m venv venv source venv/bin/activate # On Windows, use: venv\Scripts\activate
Step 2: Installing FastAPI
Now, let's install FastAPI and its dependencies:
pip install fastapi[all]
This command installs FastAPI along with all optional dependencies, including the Uvicorn ASGI server.
Step 3: Creating Your First FastAPI Application
Create a new file named main.py
in your project directory and add the following code:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello, FastAPI!"}
Let's break down this code:
- We import
FastAPI
from thefastapi
module. - We create an instance of the
FastAPI
class. - We define a route using the
@app.get("/")
decorator, which tells FastAPI that this function should handle GET requests to the root URL ("/"). - The
root()
function is an asynchronous function that returns a JSON response.
Step 4: Running Your Application
To run your FastAPI application, use the following command:
uvicorn main:app --reload
This command starts the Uvicorn server and tells it to:
- Use the
app
object from themain.py
file - Enable auto-reload for development
You should see output indicating that the server is running. By default, it will be available at http://127.0.0.1:8000
.
Step 5: Testing Your API
Open your web browser and navigate to http://127.0.0.1:8000
. You should see the JSON response:
{"message": "Hello, FastAPI!"}
Congratulations! You've just created and run your first FastAPI application.
Step 6: Adding More Endpoints
Let's add a few more endpoints to our application to demonstrate FastAPI's capabilities. Update your main.py
file with the following code:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool = None @app.get("/") async def root(): return {"message": "Hello, FastAPI!"} @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} @app.post("/items") async def create_item(item: Item): return item
In this updated version, we've added:
- A
GET
endpoint that accepts a path parameter (item_id
). - A
POST
endpoint that accepts a JSON payload conforming to theItem
model.
Step 7: Exploring FastAPI's Automatic Documentation
One of FastAPI's most powerful features is its automatic interactive API documentation. To see it in action:
- Start your server (if it's not already running)
- Navigate to
http://127.0.0.1:8000/docs
in your web browser
You'll see a Swagger UI interface that allows you to explore and test your API endpoints interactively.
Conclusion
You've now created your first FastAPI application, added multiple endpoints, and explored some of FastAPI's key features. This is just the beginning of what you can do with FastAPI. As you continue your journey, you'll discover how to handle more complex scenarios, integrate with databases, implement authentication, and much more.
Remember to refer to the official FastAPI documentation for in-depth information on its features and best practices. Happy coding!