FastAPI Python: Build A Sample Project
Hey guys! Today, we're diving headfirst into the exciting world of FastAPI with Python. We're going to build a sample project from scratch, so whether you're a seasoned Python pro or just starting out, you'll walk away with a solid understanding of how to use FastAPI to create blazing-fast, modern APIs. Get ready to level up your backend development skills!
What is FastAPI?
FastAPI is a modern, high-performance web framework for building APIs with Python 3.6+ based on standard Python type hints. It's like the cool kid on the block when it comes to building APIs, and for good reason. Here's why you should be paying attention:
- Speed: FastAPI is built on top of Starlette and Pydantic, which means it's incredibly fast. We're talking about performance that rivals Node.js and Go. This is crucial for applications where response time is critical.
- Easy to Use: FastAPI is designed to be intuitive and easy to learn. The framework leverages Python type hints, which not only help you write cleaner code but also provide automatic data validation and serialization.
- Automatic Data Validation: Say goodbye to tedious manual data validation. FastAPI automatically validates request data, ensuring that your API only receives valid input.
- Interactive API Documentation: FastAPI automatically generates interactive API documentation using OpenAPI and Swagger UI. This makes it incredibly easy for developers to explore and test your API.
- Dependency Injection: FastAPI has a powerful dependency injection system that makes it easy to manage dependencies and write testable code.
In essence, FastAPI simplifies and accelerates API development while ensuring robustness and maintainability. It's a win-win!
Setting Up Your Environment
Before we start coding, let's get our environment set up. This involves installing Python (if you haven't already), creating a virtual environment, and installing FastAPI along with its dependencies.
-
Install Python: If you don't have Python installed, download the latest version from the official Python website (https://www.python.org/downloads/). Make sure to add Python to your system's PATH during installation.
-
Create a Virtual Environment: It's always a good idea to create a virtual environment for your projects. This helps isolate your project's dependencies from other projects on your system. Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command:
python3 -m venv venvThis will create a virtual environment named "venv" in your project directory.
-
Activate the Virtual Environment: Before you can use the virtual environment, you need to activate it. On macOS and Linux, run the following command:
source venv/bin/activateOn Windows, run the following command:
venv\Scripts\activateOnce the virtual environment is activated, you'll see the name of the environment in parentheses at the beginning of your terminal prompt.
-
Install FastAPI: Now that your virtual environment is activated, you can install FastAPI and its dependencies. Run the following command:
pip install fastapi uvicornThis will install FastAPI and Uvicorn, an ASGI server that you'll use to run your FastAPI application. We'll also use Pydantic, but FastAPI installs this automatically.
With your environment prepped, you're set to move onto creating the core of our app. We'll start small, then build up to more exciting features.
Creating Your First FastAPI Application
Alright, let's get our hands dirty and create a basic FastAPI application. We'll start with a simple "Hello, World!" example to get a feel for how things work.
-
Create a
main.pyfile: In your project directory, create a file namedmain.py. This will be the main file for your application. -
Import FastAPI: Open
main.pyin your favorite text editor or IDE and import theFastAPIclass:from fastapi import FastAPI -
Create an Instance of FastAPI: Create an instance of the
FastAPIclass:app = FastAPI() -
Define a Route: Define a route using the
@app.get()decorator. This decorator tells FastAPI to handle GET requests to the specified path. In this case, we'll create a route for the root path ("/"):@app.get("/") async def read_root(): return {"Hello": "World"}This function will return a JSON response with the message
{"Hello": "World"}when a user visits the root path of your API. -
Run the Application: To run the application, you'll need to use an ASGI server like Uvicorn. Open your terminal and run the following command:
uvicorn main:app --reloadThis will start the Uvicorn server and run your FastAPI application. The
--reloadflag tells Uvicorn to automatically reload the server whenever you make changes to your code. -
Test the Application: Open your web browser and navigate to
http://127.0.0.1:8000. You should see the JSON response{"Hello": "World"}displayed in your browser. Congratulations! You've just created your first FastAPI application.This is just the starting point, but now you've got the foundation on which to build something great.
Adding Path Parameters
Path parameters are a way to capture values from the URL and use them in your API. Let's add a path parameter to our application to greet users by name.
-
Define a Route with a Path Parameter: Modify your
main.pyfile to include a route with a path parameter:@app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}In this example,
item_idis a path parameter that will capture the value from the URL. The: intannotation tells FastAPI to expect an integer value for this parameter. We've also added an optional query parameterqwith a default value ofNone. -
Test the Route: Restart your Uvicorn server (if it's not already running with the
--reloadflag) and open your web browser. Navigate tohttp://127.0.0.1:8000/items/5?q=somequery. You should see a JSON response like this:{ "item_id": 5, "q": "somequery" }Notice how the
item_idandqvalues are extracted from the URL and passed to theread_itemfunction.Now you're empowered to create more dynamic endpoints.
Using Request Body
FastAPI also allows you to receive data in the request body, which is useful for creating resources or updating existing ones. Let's create a route that accepts a JSON payload in the request body.
-
Define a Request Body Model: Create a Pydantic model to define the structure of the request body. This model will automatically validate the incoming data.
from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float tax: float = NoneThis model defines an
Itemwith four fields:name,description,price, andtax. Thedescriptionandtaxfields are optional (i.e., they can beNone). -
Define a Route that Accepts a Request Body: Modify your
main.pyfile to include a route that accepts anItemobject in the request body:@app.post("/items/") async def create_item(item: Item): return itemThis route will receive an
Itemobject in the request body and return it as a JSON response. -
Test the Route: You can test this route using a tool like
curlor Postman. Here's an example of how to usecurlto send a POST request with a JSON payload:curl -X POST -H "Content-Type: application/json" -d '{ "name": "Foo", "description": "A very nice Item", "price": 50.2, "tax": 3.2 }' http://127.0.0.1:8000/items/This will send a POST request to
/items/with the specified JSON payload. The server will return the same JSON payload as a response.With request bodies, your API can now handle complex data submissions.
Dependency Injection
Dependency injection is a powerful technique for managing dependencies in your application. FastAPI has a built-in dependency injection system that makes it easy to manage dependencies and write testable code.
-
Define a Dependency: Create a function that defines a dependency. This function will be responsible for creating and returning the dependency.
async def get_db(): db = SessionLocal() try: yield db finally: db.close()In this example, the
get_dbfunction creates a database session and returns it. Theyieldkeyword is used to create a generator, which allows FastAPI to automatically close the database session after the route has finished executing. -
Inject the Dependency into a Route: Inject the dependency into a route by adding it as a parameter to the route function.
from fastapi import Depends @app.get("/items/") async def read_items(db: Session = Depends(get_db)): items = db.query(Item).all() return itemsIn this example, the
dbparameter is injected into theread_itemsfunction using theDependsfunction. FastAPI will automatically call theget_dbfunction to create a database session and pass it to theread_itemsfunction.This is where things get really interesting. Dependency Injection makes your app scalable and testable.
Conclusion
Alright, you've successfully built a sample FastAPI project! We covered a lot of ground, including setting up your environment, creating basic routes, adding path parameters, using request bodies, and dependency injection. FastAPI is a powerful framework that makes it easy to build modern, high-performance APIs with Python. Keep experimenting, and you'll be building amazing things in no time!