Debugging¶
You can connect the debugger in your editor, for example with Visual Studio Code or PyCharm.
Calluvicorn¶
In your FastAPI application, import and runuvicorn directly:
importuvicornfromfastapiimportFastAPIapp=FastAPI()@app.get("/")defroot():a="a"b="b"+areturn{"hello world":b}if__name__=="__main__":uvicorn.run(app,host="0.0.0.0",port=8000)About__name__ == "__main__"¶
The main purpose of the__name__ == "__main__" is to have some code that is executed when your file is called with:
$pythonmyapp.pybut is not called when another file imports it, like in:
frommyappimportappMore details¶
Let's say your file is namedmyapp.py.
If you run it with:
$pythonmyapp.pythen the internal variable__name__ in your file, created automatically by Python, will have as value the string"__main__".
So, the section:
uvicorn.run(app,host="0.0.0.0",port=8000)will run.
This won't happen if you import that module (file).
So, if you have another fileimporter.py with:
frommyappimportapp# Some more codein that case, the automatically created variable__name__ inside ofmyapp.py will not have the value"__main__".
So, the line:
uvicorn.run(app,host="0.0.0.0",port=8000)will not be executed.
Info
For more information, checkthe official Python docs.
Run your code with your debugger¶
Because you are running the Uvicorn server directly from your code, you can call your Python program (your FastAPI application) directly from the debugger.
For example, in Visual Studio Code, you can:
- Go to the "Debug" panel.
- "Add configuration...".
- Select "Python"
- Run the debugger with the option "
Python: Current File (Integrated Terminal)".
It will then start the server with yourFastAPI code, stop at your breakpoints, etc.
Here's how it might look:

If you use Pycharm, you can:
- Open the "Run" menu.
- Select the option "Debug...".
- Then a context menu shows up.
- Select the file to debug (in this case,
main.py).
It will then start the server with yourFastAPI code, stop at your breakpoints, etc.
Here's how it might look:








