Python / Uvicorn Fundamentals Interview Questions
How do you run Uvicorn programmatically using uvicorn.run() and uvicorn.Config/Server?
Beyond the CLI, Uvicorn can be configured and launched entirely from Python code. This is useful when you need to customise server startup, integrate it into a larger application, or run it from within an existing async event loop.
import uvicorn # Method 1: uvicorn.run() - simplest programmatic start if __name__ == "__main__": uvicorn.run( "main:app", # string import path host="0.0.0.0", port=8000, reload=True, # development only log_level="info", ) # You can also pass the app object directly (no reload support): # uvicorn.run(app, host="0.0.0.0", port=8000) # Method 2: uvicorn.Config + uvicorn.Server - more control import uvicorn if __name__ == "__main__": config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) server.run() # Method 3: Running inside an existing async loop import asyncio import uvicorn async def main(): config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) await server.serve() # use serve() not run() inside async context if __name__ == "__main__": asyncio.run(main())
Important distinction: when passing the app object directly (not a string) to uvicorn.run(), the reload option is not available because the reloader must re-import the module by name. Always use the 'module:attribute' string form when reload=True.
More Related questions...