FastAPI Tutorial in Visual Studio Code

FastAPI is a modern high-performant web framework for building APIs with Python. It is designed to make it easy to build APIs quickly and efficiently while providing features like automatic validation, serialization, and documentation of your API, making it a popular choice for building web services and microservices.

In this FastAPI tutorial, we will create a grocery list app using FastAPI. By the end of the tutorial, you will understand how to work with FastAPI in the Visual Studio Code terminal, editor, and debugger. This tutorial is not a FastAPI deep dive. For that, you can refer to the official FastAPI documentation.

If this is your first time using Python, we recommend you to start with our Python tutorial to get familiar with the language and VS Code's Python support. This tutorial is more suited for those who are already familiar with Python and want to learn how to work with FastAPI in VS Code.

The completed code project from this FastAPI tutorial can be found on GitHub: python-sample-vscode-fastapi-tutorial.

If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.

Set up the project

There are different ways you can set up your project for this tutorial. We will cover how you can set it up in GitHub Codespaces and in VS Code on your local machine.

GitHub Codespaces

You can set up this project to develop in GitHub Codespaces, where you can code, debug, and run your app remotely in a codespace. A codespace provides a fully configured development environment hosted in the cloud, eliminating the need for local setup. This environment includes your project's dependencies, tools, and extensions, ensuring a consistent and reproducible development experience. It streamlines collaboration by providing real-time editing, integrated version control, and easy access to debugging and testing tools, all while maintaining the security and reliability of your project.

Note: All GitHub.com accounts have a monthly quota of free use of GitHub Codespaces included in the Free or Pro plan. For more information, go to About billing for GitHub Codespaces.

To set up a codespace for this tutorial, navigate to this project's GitHub repository. This codespace contains all the necessary configurations and dependencies to quickly get started with FastAPI development.

For this tutorial, select the dictionarybased branch:

dictionarybased branch selected in the python-sample-vscode-fastapi-tutorial GitHub repo

Then, select Code > Codespaces > Create Codespace on <dictionarybased> branch to create and open a codespace for your project.

Once you're done, you can continue with the Replace the database section below.

Locally in VS Code

To successfully complete this tutorial in VS Code, you first need to set up your Python development environment. Specifically, this tutorial requires:

In this section, we will create a folder to open as a workspace in VS Code, set up a Python virtual environment, and install the project's dependencies.

  1. In your file system, create a project folder for this tutorial, such as groceries-plugin.

  2. Open this new folder in VS Code (File > Open Folder…).

  3. When the Workspace Trust prompt shows up, select Yes, I trust the authors to allow the workspace to access necessary resources and extensions. You can learn more about Workspace Trust in the documentation.

Now, let's create a requirements.txt file that lists the dependencies we wish to install for the application. The requirements.txt file is a common practice in Python development, used to specify the libraries that your project relies on and their versions. This file helps ensure that anyone working on the project can recreate a similar development environment, making it a convenient component for maintaining consistency.

We will install FastAPI for creating the app, uvicorn to work as the server, and Redis and type-redis for handling data storage and interacting with a Redis database.

  1. Create a new file in VS Code (File > New Text File or ⌘N (Windows, Linux Ctrl+N)).

  2. Add the following content to it:

    fastapi
    redis
    types-redis
    uvicorn
    
  3. Save the file (⌘S (Windows, Linux Ctrl+S)) and name it requirements.txt.

  4. Create a virtual environment by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and running the Python: Create Environment command.

    Note: This step may take a couple of minutes to complete.

  5. When asked for the environment type, select Venv:

    Dropdown with "Venv" or "Conda" as options for environments that can be created with the Python: Create Environment command

  6. Then select the latest version of Python available on your machine:

    List of available global environments that can be used to create a virtual environment

  7. Select the requirements.txt file from the dropdown list, so the dependencies are automatically installed, and then select OK:

    Check box selected to install dependencies from requirements.txt file

The virtual environment will be created, the dependencies automatically installed, and the environment selected for your workspace to be used by the Python extension. You can confirm it's been selected by checking the bottom right corner of VS Code:

Environment in the Status bar

Note: If you don't find the newly created environment information on the Status bar, you can click on the Python interpreter indicator (or run the Python: Select Interpreter command from the Command Palette) and manually select the virtual environment.

Start Coding

Let's create the application!

  1. Create a new Python file by using File > New File… and then select Python File.

  2. Save it as main.py (⇧⌘S (Windows, Linux Ctrl+Shift+S)) in the groceries-plugin folder.

  3. Add the following code to main.py and save the file:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def root():
        return {"message": "Hello World"}
    
  4. Run the code by starting up the debugger (F5).

  5. From the dropdown menu, select the FastAPI configuration option from the list:

    Dropdown with debugger configuration options, with FastAPI being highlighted

    This automatically creates a debug configuration that invokes uvicorn to start the application server through the debugger and allows you to step through the source code to inspect its behavior. You should see something like the following in the terminal:

    Uvicorn server running message displayed in the terminal, with an URL to access the app

    Tip: In the case where your default port is already in use, stop the debugger and open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)), search for Debug: Add Configuration, select Python Debugger, and then FastAPI. This will create a custom config file in