Top 10 Python FastAPI Tips and Tricks for Efficient Web Development

Jennie Lee
6 min readApr 7, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Top 10 Python FastAPI Tips and Tricks for Efficient Web Development

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 be easy to use and efficient, providing automated validation, serialization, and documentation with minimal code duplication. FastAPI uses the Starlette framework as its base, which ensures high performance and scalability.

In this article, we will provide a step-by-step guide on developing a simple Python FastAPI ToDo app. We will cover the setup process, installation of FastAPI and necessary dependencies, as well as configuring the application to run on an ASGI server. By the end of this tutorial, you will have a fully functional ToDo app that you can build upon and customize to suit your specific needs.

Before we proceed, let’s take a look at some of the benefits of using FastAPI for web development:

  • Performance: FastAPI is built with performance in mind, leveraging modern, asynchronous programming techniques. It is capable of handling high loads and performing efficiently even under heavy traffic.
  • Easy to Use: FastAPI is designed to be easy to use, with a straightforward API and intuitive features. It provides automatic request and response validation, serialization, and documentation generation, reducing code duplication and making development faster.
  • Type Safety: FastAPI leverages Python type hints to provide type checking and validation. This makes it easier to catch errors earlier in the development process and improves the overall reliability of the application.
  • Swagger UI: FastAPI automatically generates a web-based user interface (Swagger UI) that allows developers to explore and test the API endpoints. This eliminates the need for manual documentation and makes API testing and debugging more convenient.
  • Wide Range of Ecosystem: FastAPI benefits from the Python ecosystem, with a vast selection of libraries, tools, and frameworks that can be easily integrated and used in conjunction with FastAPI.

Now that we have covered the basics of FastAPI and its benefits, let’s dive into the step-by-step guide on developing a simple Python FastAPI ToDo app.

1. Setting Up the Project

To get started, create a directory for your project and navigate into it. This will help keep your code organized and make it easier to manage your project files.

mkdir fastapi-todo-app
cd fastapi-todo-app

2. Creating a Python Virtual Environment

It is recommended to use a Python virtual environment to isolate your project’s dependencies. This ensures that your project uses the intended versions of the libraries and avoids conflicts with other Python projects or system-wide installations.

To create a virtual environment, run the following command:

python3 -m venv venv

Activate the virtual environment by running the appropriate command for your operating system:

  • Windows:
venv\Scripts\activate.bat
  • Unix or Linux:
source venv/bin/activate

3. Installing FastAPI

With the virtual environment activated, you can now install FastAPI using pip, the Python package manager. Run the following command:

pip install fastapi

4. Installing an ASGI Server

FastAPI requires an ASGI server to run your application. ASGI (Asynchronous Server Gateway Interface) is a standard interface between web servers and Python web applications or frameworks. It allows the development of web applications that can handle multiple simultaneous connections efficiently.

Two popular ASGI servers for FastAPI are uvicorn and hypercorn. Uvicorn is a lightning-fast ASGI server, while Hypercorn is built on top of the trio asynchronous I/O library and provides great performance with HTTP/2 support.

To install uvicorn, run the following command:

pip install uvicorn

To install hypercorn, run the following command:

pip install hypercorn

5. Installing Packages for the Template

To create user interfaces in FastAPI, we often use template engines such as Jinja2 or Tera. These template engines allow for dynamic HTML generation, making it easier to build interactive web applications.

To install the necessary packages for a template, let’s use Jinja2 as an example. Run the following command:

pip install Jinja2

6. Installing a Package for Database Support

For our ToDo app, we will use a lightweight SQLite database. To interact with the database, we will use the databases package, which provides support for multiple databases and integrates seamlessly with FastAPI.

Run the following command to install the databases package:

pip install databases

7. Opening the Project with VSCode and Creating Files

For efficient web development in FastAPI, it is recommended to use an editor that provides features like code navigation, autocompletion, and debugging support. Visual Studio Code (VSCode) is a popular choice among developers, as it offers excellent support for Python and FastAPI.

Open your project directory in VSCode, either by navigating to the directory and running code . in the terminal or by launching VSCode and selecting "Open Folder" to choose your project directory.

Create three files within your project directory: app.py, database.py, and models.py. These files will contain the code for your FastAPI application, database setup, and data models, respectively.

app.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"Hello": "World"}

models.py

from pydantic import BaseModel

class Todo(BaseModel):
id: int
title: str
completed: bool

database.py

import databases

DATABASE_URL = "sqlite:///./todo.db"

database = databases.Database(DATABASE_URL)

8. Running the App with Uvicorn

With the code in place, you can now run your FastAPI ToDo app using Uvicorn. Open a new terminal window and navigate to your project’s directory. Ensure that your virtual environment is activated.

Run the following command to start your FastAPI app:

uvicorn app:app --reload

You should see output similar to the following:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [12345] using statreload
INFO: Started server process [12346]
INFO: Waiting for application startup.
INFO: Application startup complete.

Your FastAPI ToDo app is now running and can be accessed at http://127.0.0.1:8000/. You can also access the API documentation at http://127.0.0.1:8000/docs, where you can explore and test the available endpoints.

9. Commit and Push to GitHub

To ensure that your code is safe and can be easily shared with others, it is recommended to use version control. One popular version control system is Git, and a popular hosting platform for Git repositories is GitHub.

Initialize a Git repository in your project directory by running the following command:

git init

Create a .gitignore file in your project directory if it does not already exist. Open the file and add the following lines to exclude the virtual environment and database file from being tracked by Git:

venv/
todo.db

Add all the files in your project directory to the Git repository by running the following command:

git add .

Commit the changes to the repository with a descriptive message:

git commit -m "Initial commit"

Create a new repository on GitHub and follow the instructions to push your local repository to the remote repository. Once completed, your code will be safely stored on GitHub.

10. Deactivating the Virtual Environment

Once you have finished working on your project, it is a good practice to deactivate the virtual environment. This ensures that any subsequent Python commands are run using the global Python installation.

To deactivate the virtual environment, run the following command:

deactivate

Congratulations! You have successfully created a simple Python FastAPI ToDo app. You can now further enhance and customize the application according to your needs.

In this article, we covered the basics of FastAPI and its benefits, as well as provided a step-by-step guide on developing a simple ToDo app using Python and FastAPI. We discussed setting up the project, creating a virtual environment, installing FastAPI and necessary dependencies, configuring an ASGI server, and creating the required files. Additionally, we showed you how to run the app and access the API documentation, commit and push your code to GitHub, and deactivate the virtual environment.

FastAPI is a powerful web framework that allows you to build efficient, scalable, and easy-to-maintain web applications. With its high performance, support for modern Python features, and seamless integration with the Python ecosystem, FastAPI is becoming increasingly popular among developers.

So go ahead, explore the possibilities that FastAPI offers, and start building your next web application with ease!

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--

Jennie Lee
Jennie Lee

Written by Jennie Lee

Software Testing Blogger, #API Testing

No responses yet