0
0
FastAPIframework~10 mins

Uvicorn server basics in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Uvicorn server basics
Write FastAPI app code
Run Uvicorn server command
Uvicorn loads app
Server listens on host:port
Client sends HTTP request
Uvicorn routes request to FastAPI app
App processes request and returns response
Uvicorn sends response back to client
Repeat for next requests or stop server
This flow shows how you write a FastAPI app, run it with Uvicorn, and how Uvicorn handles requests and responses.
Execution Sample
FastAPI
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello World"}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)
This code creates a simple FastAPI app and runs it with Uvicorn on localhost port 8000.
Execution Table
StepActionEvaluationResult
1Import FastAPI and UvicornModules loadedReady to create app
2Create FastAPI app instanceapp = FastAPI()App object created
3Define GET endpoint '/'Function read_root registeredEndpoint ready
4Check if __name__ == '__main__'True when run directlyProceed to run server
5Call uvicorn.run(app, host, port)Uvicorn starts serverServer listens on 127.0.0.1:8000
6Client sends GET request to '/'Uvicorn receives requestRoutes to read_root function
7read_root executesReturns {'message': 'Hello World'}Response prepared
8Uvicorn sends response to clientClient receives JSON messageRequest complete
9Wait for next request or stopServer runningLoop continues or server stops
💡 Server stops when process is terminated or interrupted
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5After Step 7Final
appundefinedFastAPI instanceFastAPI with endpointRunning server referenceN/AN/A
read_rootundefinedundefinedFunction registeredN/AFunction executedN/A
Key Moments - 3 Insights
Why do we check if __name__ == '__main__' before running uvicorn?
This check ensures the server runs only when the script is executed directly, not when imported. See execution_table step 4.
What happens if the client sends a request to a path not defined in the app?
Uvicorn returns a 404 Not Found response because no matching endpoint exists. This is part of Uvicorn routing after step 6.
Why is the read_root function defined as async?
FastAPI supports async functions for better performance with I/O. Uvicorn can handle async endpoints efficiently, as shown in step 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after step 5?
AApp object created
BServer listens on 127.0.0.1:8000
CFunction read_root registered
DClient receives JSON message
💡 Hint
Check the 'Result' column for step 5 in execution_table
At which step does the server send the response back to the client?
AStep 8
BStep 7
CStep 6
DStep 9
💡 Hint
Look for 'Uvicorn sends response to client' in execution_table
If we remove the if __name__ == '__main__' check, what changes in the execution?
AApp object is not created
BEndpoints are not registered
CServer runs even when imported as a module
DClient requests fail
💡 Hint
Refer to key_moments about the purpose of the __name__ check
Concept Snapshot
Uvicorn runs FastAPI apps by loading the app instance and listening on a host and port.
Use uvicorn.run(app, host, port) inside if __name__ == '__main__' to start the server.
Uvicorn routes HTTP requests to FastAPI endpoints and sends back responses.
Async functions in FastAPI improve performance with Uvicorn.
Stop the server by interrupting the process (Ctrl+C).
Full Transcript
This visual execution shows how a FastAPI app is created and run using Uvicorn. First, the FastAPI app instance is created and endpoints are defined. Then, the script checks if it is run directly and starts the Uvicorn server on localhost port 8000. When a client sends a request, Uvicorn receives it and routes it to the matching FastAPI endpoint function. The function executes asynchronously and returns a JSON response. Uvicorn sends this response back to the client. The server keeps running until stopped. Key points include the importance of the __name__ check to avoid running the server on import, and how Uvicorn handles async endpoints efficiently.