Up and Running with FastAPI

Before working on any Python project, it’s important to create a virtual environment in your project folder. Virtual environments allow Python code to run inside their own isolated space.

Every Python-based project you build or work on may have its own requirements for Python, its dependencies, their version numbers, and so on. Project A might need version 1.0 of a particular module while project B might need version 2.0.

A virtual environment places a project into its own silo where any packages and modules that are installed for that project will only be accessible within that specific virtual environment. This creates a more clean and professional way to maintain compatibility and reduce code conflict among packages, modules, and projects.

Always create virtual environments if you can.

In this post, we set up a Python virtual environment, install FastAPI and Uvicorn, and create a basic project to make sure everything is working correctly.

Create a Virtual Environment

If you haven’t already, download and install Visual Studio Code. A basic installation guide for VS Code is included in the post titled Install Python.

Create a project folder called ice-cream-inventory and open it in VS Code. In the VS Code menu, click Terminal > New Terminal. A terminal window is opened within VS Code.

Alternatively, you could also run these commands in the Terminal app on macOS. If you’re on Windows, PowerShell should work as an equivalent.

Virtual environments can be created using the Python venv module, which comes as part of the Python standard library. Execute the following command in the Terminal window.

python3 -m venv venv

The command can be broken down into:

term description
python3 The Python term to run a script
-m The Python flag to run a module
venv Python’s venv module
venv The name of our virtual environment

The venv command creates a new folder and virtual environment called venv in your current fastapi directory. The venv directory contains files and folders that Python uses to construct the virtual environment.

You can call your virtual environment anything you choose. One naming convention developers use is env, venv, or .venv. The dot-notation would keep the directory hidden in Finder and in your shell. In any case, use a name that helps identify why the directory exists.

Next, you must activate the virtual environment to use it. Execute the following command to activate your environment.

. venv/bin/activate

With your virtual environment activated, “(venv)” will be displayed in front of your computer’s user and hostname in the Terminal app. If you exit VS Code and come back another day to work on your project, make sure the activate command is run and that “(venv)” is showing.

(venv) username@Kitchen-computer ice-cream-inventory

If you need to deactivate the environment, use the following command.

deactivate

Install FastAPI

Python includes a package manager named Pip for managing Python packages and modules. It’s included with the default Python binary installers so you don’t have to install it separately.

With your virtual environment activated, use the following command to install FastAPI.

pip3 install fastapi

You also need to install the Uvicorn web server to run FastAPI applications in your local web browser. Execute the following command to install Uvicorn.

pip3 install uvicorn

Now run the following command to see a list of the currently installed Python packages in the virtual environment.

pip3 list

A list of packages and their version numbers are returned. Review the results. Both FastAPI, Uvicorn and their dependencies are shown.

Package           Version
----------------- -------
anyio             3.6.2
click             8.1.3
fastapi           0.85.1
h11               0.14.0
idna              3.4
pip               22.2.2
pydantic          1.10.2
setuptools        63.2.0
sniffio           1.3.0
starlette         0.20.4
typing_extensions 4.4.0
uvicorn           0.19.0

Start Your Project

Let’s create a basic project to see if everything works.

In your project folder, create a new file named main.py with the following code.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
	return {"message": "Hello, World!"}

The first line of code imports the FastAPI framework.

A variable called app is assigned an instance of the FastAPI class.

The @app.get("/") is a path operation decorator for the root() function. The decorator is used to create the route with the specified HTTP method, get(). The root() function is called whenever someone tries to access that endpoint with a GET request.

The function returns a JSON message containing the message “Hello, World!”. It’s also possible to return HTML, errors, and whatever else we would like.

Save your work and then execute the following command in the terminal window.

uvicorn main:app --reload

The uvicorn command will start a web server on your computer using the main.py file and load the variable app that was initialized with FastAPI to handle the routes. If you need to quit the server, click into the Terminal window and press the key-command CTRL+C.

The --reload parameter is optional. This flag will make uvicorn watch our project directory for any changes made to the code and will reload the web server as updates are made. This works well for development purposes but should not be used in production.

In a web browser, navigate to http://localhost:8000 and you will see the following output.

Hello World example in FastAPI

Summary

In this post we successfully set up a virtual environment to keep our Python packages within the scope of a single project. We also learned how to install FastAPI and create a basic example of its usage.

There wasn’t much code introduced but you can find a copy of it in the GitHub repository for this project.

In the next lesson, Path and Query Paramters, we explore how variables can be passed into URL requests.