Uvicorn runs your FastAPI app so people can use it through the internet. It listens for requests and sends back responses.
0
0
Uvicorn server basics in FastAPI
Introduction
You want to test your FastAPI app locally on your computer.
You need to run your FastAPI app on a server for others to access.
You want to see your API working in a browser or with tools like Postman.
You are developing and want to reload the server automatically when code changes.
Syntax
FastAPI
uvicorn module_name:app --host 0.0.0.0 --port 8000 --reload
module_name:app means the Python file and the FastAPI app object inside it.
--reload restarts the server when you change code, useful for development.
Examples
Runs the app in
main.py on default host 127.0.0.1 and port 8000.FastAPI
uvicorn main:app
Makes the app available on all network interfaces at port 5000.
FastAPI
uvicorn main:app --host 0.0.0.0 --port 5000
Runs with auto-reload so changes in code restart the server automatically.
FastAPI
uvicorn main:app --reload
Sample Program
This simple FastAPI app returns a greeting message at the root URL. Run it with Uvicorn to see it in action.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get('/') async def read_root(): return {"message": "Hello from FastAPI!"} # To run this app, save as main.py and run: # uvicorn main:app --reload
OutputSuccess
Important Notes
Use --reload only in development, not in production.
Uvicorn is fast and supports async code, making your API responsive.
Check the terminal for server logs and errors when running Uvicorn.
Summary
Uvicorn runs your FastAPI app so it can handle web requests.
You specify the app location and options like host, port, and reload.
Use uvicorn module_name:app --reload to develop easily.