In short, use fastapi run to serve your FastAPI application:
fast →fastapi run main.py FastAPI Starting production server 🚀
Searching for package file structure from directories with __init__.py files Importing from /home/user/code/awesomeapp
module 🐍 main.py
code Importing the FastAPI app object from the module with the following code:
from main import app
app Using import string: main:app
server Server started at http://0.0.0.0:8000 server Documentation at http://0.0.0.0:8000/docs
Logs:
INFO Started server process [2306215] INFO Waiting for application startup. INFO Application startup complete. INFO Uvicorn running on http://0.0.0.0:8000(Press CTRL+C to quit)
FastAPI uses a standard for building Python web frameworks and servers called ASGI. FastAPI is an ASGI web framework.
The main thing you need to run a FastAPI application (or any other ASGI application) in a remote server machine is an ASGI server program like Uvicorn, this is the one that comes by default in the fastapi command.
There's a small detail about names to keep in mind. 💡
The word "server" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn).
Just keep in mind that when you read "server" in general, it could refer to one of those two things.
When referring to the remote machine, it's common to call it server, but also machine, VM (virtual machine), node. Those all refer to some type of remote machine, normally running Linux, where you run programs.
If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:
fast →uvicorn main:app --host 0.0.0.0 --port 80 INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
These examples run the server program (e.g Uvicorn), starting a single process, listening on all the IPs (0.0.0.0) on a predefined port (e.g. 80).
This is the basic idea. But you will probably want to take care of some additional things, like:
Security - HTTPS
Running on startup
Restarts
Replication (the number of processes running)
Memory
Previous steps before starting
I'll tell you more about each of these concepts, how to think about them, and some concrete examples with strategies to handle them in the next chapters. 🚀