In this tutorial we will setup Visual Studio Code IDE to help debug FastAPI repository. Analyse the state of variables and see how to debug FastAPI in VS Code. To do this we will add a debug configuration and create a breakpoint in a sample FastAPI repository and hit that breakpoint.
Debugging is an essential part of Software Engineering development. Debugging a piece of software will help you understand the behavior, its workflow, allows you to watch the state of the application variables and troubleshoot problematic scenarios. Debugging software in case of fixing defects 🐛 will provide you the exact point of root cause where the defect originates from. Debugging might also help identify cases that are un-handled and go out of the radar of the tests and test coverage of the particular Application under test is being troubleshooted.
Table of Contents
- Prerequisites
- Initial Setup of Workspace to Debug FastAPI in VS Code
- Setup launch.json configuration to Debug FastAPI in VS Code
- Define configuration in launch.json to debug FastAPI in VS Code IDE
- Debug FastAPI in VS Code
Prerequisites
- VS Code IDE
- Python
- Setup VS Code IDE for Python Development
- Python extension for VS Code
ms-python.python
- Pylance extension for VS Code `ms-python.vscode-pylance
- Python extension for VS Code
- Git
We will set up the Visual Studio Code IDE to help debug the FastAPI application. This will be a short and sweet notes about setting up a Debugger for FastAPI using VS Code
Initial Setup of Workspace to Debug FastAPI in VS Code
In this section we will setup our demo FastAPI repository and make the workspace ready to debug the FastAPI application. The following steps are more or less similar to your custom FastAPI repositories and detailed explanation is provided wherever necessary to reflect the settings according to your need.
Clone FastAPI Repository
Clone any FastAPI repository or run the command mentioned below in a Command Line Terminal to clone repository that has Async REST APIs in FastAPI with PostgreSQL CRUD
git clone -b fastapi-postgresql-azure-deploy https://github.com/windson/fastapi.git
This repo already has a launchconfig.json
and you can directly start debugging the FastAPI. But if you are doing it for your own FastAPI repository, follow the further steps.
Open the FastAPI repository in VS Code
Once you successfully clone the repository, open the solution in VS Code IDE by running the command following command in the terminal.
cd fastapi code .
Activate Pylance Extension on VS Code IDE
By default, when you launch any repository in VS Code, not all the extensions are activated. To activate Python related extensions such as Python ms-python.python
and Pylance ms-python.vscode-pylance
, open any python file that has extension .py
. In our case open main.py
to activate Python extensions for VS Code IDE.
Create & Activate Python Virtual Environment to debug FastAPI repository
If your repository needs a Python Virtual Environment just like the one you cloned, install the Virtual Environment and Activate it to help us debug FastAPI in VS Code IDE.
Open the Command Terminal with in VS Code by navigating to VS Code menu option Terminal
and click on New Terminal
. In the terminal, run the following commands to quickly install and activate Python 3.* virtual environment. And also to install required python modules required by our FastAPI Application.
Windows Users
python -m venv env env\Scripts\activate python -m pip install --upgrade pip pip install -r requirements.txt
Linux users
python3 -m venv env source ./env/bin/activate python -m pip install --upgrade pip pip install -r requirements.txt
Select Python Interpreter
Once you install and activate Python Virtual Environment, you will see a warning and a prompt thrown by Python extension for VS Code IDE to Select Python Interpreter
. Click on it and choose the python interpreter located in your virtual environment. This will create a settings.json
in a .vscode
root directory with the following json settings.
{ "python.pythonPath": "env\\Scripts\\python.exe" }
If you are on a Linux PC, you should see some different value for the python.pythonPath
that points to location of Python binaries.
Setup launch.json configuration to Debug FastAPI in VS Code
VS Code facilitates setting up of debug configuration with all the required prerequisites to be defined in a single file launch.json
located under the .vscode
directory created at the root of the repository. It is recommended to check-in the files launch.json
and settings.json
of .vscode
directory to help create a similar development experience across all the members contributing to the specific repository. Follow the steps to create launch.json
- Hit
Ctrl + Shift + D
to launchRun and Debug
side panel of the VS Code IDE. - Locate and click on an hyper link that says
create a launch.json file.
- You will be prompted to
Select Environment
to have debug configuration to be created. ChoosePython
from the list. - The next prompt will suggest you to
Select a debug configuration
. From the list chooseFlask Launch and debug a Flask web application
.- Wondered why I choose Flask? I will modify this template to work for FastAPI. Lets see how to modify
launch.json
to help debug FastAPI in VS Code IDE.
- Wondered why I choose Flask? I will modify this template to work for FastAPI. Lets see how to modify
- Finally you will be prompted to
Enter the path to the application
. As our FastAPI instance variable is available in main.py, typemain.py
and hit enter.
This will land you on a new file launch.json
created under the .vscode
directory.
Define configuration in launch.json to debug FastAPI in VS Code IDE
Perform the following modifications to get your development workspace ready to debug FastAPI in VS Code.
Update Debug Configuration Name to FastAPI
Replace line that says Flask
"name": "Python: Flask",
with the following
"name": "Python: FastAPI",
Update module to uvicorn
On a development PC, we generally tend to work with uvicorn
to run FastAPI. So provide the “module” with the value uvicorn
. So find and replace the following line
"module": "flask",
and update it to point to uvicorn
as follows
"module": "uvicorn",
Add Environment variables
The demo repository is dependent on some environment variables. Add or customize the environment variables according to your needs as below.
Change the env
section of the launch.json
from what it looks like
"env": { "FLASK_APP": "main.py", "FLASK_ENV": "development", "FLASK_DEBUG": "0" },
and update it according to your needs as below
"env": { "db_username": "postgres", "db_password": "secret", "host_server": "localhost", "database_name": "fastapi", "ssl_mode": "prefer", "db_server_port": "5432" },
Update args of launch.json to debug FastAPI in VS Code
Finally update the args
section of the launch.json
configuration file to resemble the general command that runs FastAPI on local development environment. That means, we generally issue the following command to run FastAPI on local PC.
uvicorn main:app --reload --port 8000
So, we are issuing the uvicorn
module with the set of arguments like where the FastAPI entry point is located in the form of module:fastapi-instance and enabling to reload the uvicorn runner for every change in the code using --reload
and also mentioning which port to run the FastAPI app on by --port
with value 8000
. Provide these arguments in the form of json in the args
section of the launch.json
file as follows.
"args": [ "main:app", "--reload", "--port", "8000" ]
Remove the key value pair that sets jinja
to true
if you are not using in your repository. Save the file and close it.
The full and final configuration in launch.json
that will help you enable debugging of FastAPI in VS Code IDE will look like below.
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: FastAPI", "type": "python", "request": "launch", "module": "uvicorn", "env": { "db_username": "postgres", "db_password": "secret", "host_server": "localhost", "database_name": "fastapi", "ssl_mode": "prefer", "db_server_port": "5432" }, "args": [ "main:app", "--reload", "--port", "8000" ] } ] }
Debug FastAPI in VS Code
Now we will debug the cloned FastAPI repository by following the steps mentioned below.
Add breakpoints
Place the cursor on any desired line to hit the execution to and hit the function key F9
. That will add a red dot to the left of the window. Lets suppose we add a breakpoint to the get notes collection end point that has the line
query = notes.select().offset(skip).limit(limit)
Debug
Hit Ctrl + Shift + D
to open the Run and Debug
window. Find the dropdown and choose the value that has value Python: FastAPI
we provided for the key name
in our debug configuration in launch.json file. Select Python: FastAPI
and click on the green button.
Based on the args
provided in the debug configuration of launch.json
, FastAPI will be running on port 8000. In the browser, navigate to http://127.0.0.1:8000/notes/?skip=1&limit=3
and you will hit the breakpoint that we have set in get notes collection endpoint of main.py
Hover over the variables skip
and limit
to watch the values held by them. You should see the values sent in the request as 1 and 3 for skip and limit respectively.
You can also watch for variables and notice the call stack to understand the origin and flow of the control execution and have a glance of various Variables in global scope and their beholding values in the Run and Debug
pane.
Congratulations 🎉, You have mastered how to debug FastAPI in VS Code IDE. You are able to setup the debug configuration for various folder structures of FastAPI and watch the variable state during debug, manage debug points.
Bookmark 🔖 (Ctrl + D) this article for future reference to understand how to debug FastAPI in VS Code IDE.
Pingback: Implementing Async REST APIs in FastAPI with PostgreSQL CRUD – TutLinks