How to Install FastAPI: Step-by-Step Guide
To install
fastapi, run pip install fastapi in your terminal. For running your FastAPI app, also install an ASGI server like uvicorn with pip install uvicorn.Syntax
Use the pip install command to add FastAPI and its server to your Python environment.
pip install fastapi: Installs the FastAPI framework.pip install uvicorn: Installs Uvicorn, a server to run FastAPI apps.
bash
pip install fastapi pip install uvicorn
Example
This example shows how to install FastAPI and Uvicorn, then create a simple app and run it.
bash and python
pip install fastapi uvicorn # Create a file named main.py with this content: from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI!"} # Run the app with: # uvicorn main:app --reload
Output
INFO: Started server process [12345]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Common Pitfalls
Common mistakes when installing FastAPI include:
- Not installing
uvicorn, so the app cannot run. - Using Python versions older than 3.7, which FastAPI requires.
- Running
pip install fastapiinside the wrong environment or without activating a virtual environment.
Always check your Python version with python --version and use a virtual environment.
bash
## Wrong way (missing uvicorn): pip install fastapi ## Right way: pip install fastapi uvicorn
Quick Reference
Summary tips for installing FastAPI:
- Use Python 3.7 or newer.
- Install both
fastapianduvicorn. - Use a virtual environment to avoid conflicts.
- Run your app with
uvicorn main:app --reloadfor auto-reload during development.
Key Takeaways
Install FastAPI using 'pip install fastapi' and Uvicorn with 'pip install uvicorn'.
Use Python 3.7 or higher to ensure compatibility with FastAPI.
Always run your FastAPI app with Uvicorn to serve it properly.
Use a virtual environment to keep your Python packages organized.
Run 'uvicorn main:app --reload' during development for automatic code reload.