Install FastAPI and Uvicorn
Install FastAPI and Uvicorn with pip — FastAPI Backend Development.
Focus: install fastapi and uvicorn with pip
Every FastAPI tutorial assumes you already have a working environment, but getting there is exactly where many developers lose momentum. You open your terminal, type pip install fastapi, and then hit a wall of permission errors, outdated packages, or a mysterious ModuleNotFoundError when you try to run your first app. This lesson clears that roadblock for good. You'll learn how to install FastAPI and Uvicorn with pip, verify your setup, and avoid the common pitfalls that trip up beginners and seasoned developers alike.
The problem this lesson solves
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+. But before you can write your first route or serve your first JSON response, you need a clean, working installation. The pain points are real:
- Conflicting dependencies — FastAPI relies on Pydantic and Starlette; a misconfigured environment can break both.
- Permission errors — Installing globally can get blocked by your operating system's security policies.
- The wrong server — FastAPI alone doesn't run a web server; you need an ASGI server like Uvicorn.
- Version mismatches — Using an old Python or pip can cause subtle bugs in type validation and async behavior.
If you skip this step or do it carelessly, you'll waste hours debugging errors that have nothing to do with your code. This lesson gives you a repeatable, safe way to set up FastAPI and Uvicorn with pip, so you can focus on building your API instead of fighting your environment.
Core concept / mental model
Think of your Python environment as a workshop and pip as your tool fetcher. FastAPI and Uvicorn are two distinct tools: FastAPI is the framework — the blueprint for defining endpoints, data models, and validation; Uvicorn is the running engine — an ASGI (Asynchronous Server Gateway Interface) server that actually listens for HTTP requests and hands them to your FastAPI application.
A common analogy: FastAPI is the kitchen where you prepare dishes (your API endpoints), and Uvicorn is the waiter who takes orders from customers (incoming HTTP requests) to that kitchen and delivers the results. Neither works alone — you need both installed, and they must be compatible with your Python version.
In practical terms, the installation flow is:
- Create an isolated environment (recommended) →
python -m venv venv - Activate it (so pip installs locally, not system-wide)
- Install FastAPI and Uvicorn with pip →
pip install fastapi uvicorn - Verify the installation →
python -c "import fastapi; print(fastapi.__version__)"
This mental model — two components, one isolated environment, one command — will guide you through every step that follows.
How it works step by step
Let's break the installation process into clear, logical steps. Each step builds on the previous one, so follow them in order.
Step 1: Check your Python version
FastAPI requires Python 3.7 or later. Most modern systems have 3.8 or higher, but it's worth confirming. Open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and run:
python --version
If you see Python 3.7+, you're good. If not, install a newer Python from python.org or via your package manager.
Step 2: Create and activate a virtual environment
This is the single most important best practice. A virtual environment keeps your project's dependencies isolated from the rest of your system, preventing version conflicts. Here's why: if you install FastAPI globally, some other project might already use a different Pydantic version, and you'll get strange validation errors later.
Run these commands in your project folder:
# Create a virtual environment named 'venv'
python -m venv venv
# Activate it
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
Your terminal prompt should now show (venv) at the beginning, indicating you're inside the isolated environment.
Step 3: Upgrade pip (recommended)
Before installing anything, make sure pip is up-to-date. An outdated pip can cause dependency resolution issues:
python -m pip install --upgrade pip
Step 4: Install FastAPI and Uvicorn with pip
Now the magic happens. You can install both together in one command:
pip install fastapi uvicorn
Pip will download FastAPI, its dependencies (Starlette, Pydantic, and others), and Uvicorn (plus its dependencies). This may take a minute. When it finishes, you'll see a success message and a list of installed packages.
To confirm the installation worked, check the versions:
python -c "import fastapi; print(fastapi.__version__)"
python -c "import uvicorn; print(uvicorn.__version__)"
If both print version numbers without errors, you're ready to write your first app.
Hands-on walkthrough
Let's make this practical. We'll create a minimal FastAPI application and run it with Uvicorn to prove both are working correctly.
Example 1: Your first "Hello World" API
Create a file named main.py with the following content:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
Run it with Uvicorn from your terminal:
uvicorn main:app --reload
You should see output like:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [12345]
INFO: Started server process [12346]
Now open your browser to http://127.0.0.1:8000 and you'll see {"message": "Hello, FastAPI!"}. You've just built a live web API!
Example 2: Verify the interactive docs
FastAPI automatically generates interactive documentation at /docs. Visit http://127.0.0.1:8000/docs — you'll see a Swagger UI where you can test your endpoint directly. This is a built-in feature that comes free with FastAPI.
Example 3: Handling a JSON body
Let's make it slightly more realistic by adding a POST endpoint:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return {"item": item.name, "price": item.price}
Restart Uvicorn (or rely on --reload), then use the docs page to send a test request. You'll see automatic validation — if you send {"name": "apple"} without price, FastAPI returns a 422 validation error with a clear message.
Pro tip: Always run Uvicorn with the
--reloadflag during development. It watches your files and restarts the server automatically, saving you manual restarts.
Compare options / when to choose what
There are a few ways to install FastAPI and Uvicorn, and the best choice depends on your context. Here's a comparison:
| Method | Pros | Cons | Best for |
|---|---|---|---|
pip install fastapi uvicorn |
Simple, one command, standard | May install latest versions with breaking changes | Most projects |
pip install fastapi[all] |
Installs extra utilities (like uvicorn[standard] and python-multipart) |
Pulls in more packages than needed | Development where you want convenience |
Pin versions (fastapi==0.110.0) |
Reproducible builds, avoids surprises | Must update manually over time | Production and team projects |
Poetry or uv |
Better dependency management, lock files | Extra learning curve, additional tooling | Large projects with strict reproducibility |
For this learning path, start with pip install fastapi uvicorn — it's the fastest way to get going. Later, when you build for production, you'll want to pin versions and use a requirements.txt file with exact versions.
If you're wondering about uvicorn[standard]: it installs optional C extensions for better performance and includes watchfiles for auto-reload. For production, this is recommended, but for learning, plain uvicorn is enough.
One more option: use pip install fastapi[all] if you want to avoid typing multiple packages. This installs Uvicorn and other common extras like python-multipart for file uploads. It's a convenience trade-off — you get more, but you may not need everything.
Troubleshooting & edge cases
Even with clear instructions, things go wrong. Here are the most common issues and how to fix them.
ModuleNotFoundError: No module named 'fastapi'
You're likely outside your virtual environment. Activate it with source venv/bin/activate (or venv\Scripts\activate on Windows) and try again. Alternatively, you might have installed in a different Python than the one you're running. Always use python and pip from the same environment.
Permission errors during installation
If you see PermissionError or Operation not permitted, your pip is trying to install globally because the virtual environment isn't active. Never use sudo pip install — it can break your system Python. Instead, activate the environment correctly and retry.
Python version too old
FastAPI uses from __future__ import annotations internally in newer versions, which requires Python 3.7+. If you're on Python 3.6 or earlier, upgrade. Run python --version to check.
Uvicorn shows Address already in use
Port 8000 is occupied. Either kill the process on that port or run Uvicorn on a different port:
uvicorn main:app --reload --port 8001
pip not found
If pip isn't available, run python -m pip instead of just pip. This uses the pip module of your current Python interpreter and avoids ambiguity.
Slow downloads or timeouts
If you're behind a firewall or have a slow connection, use a mirror:
pip install -i https://pypi.org/simple fastapi uvicorn
Or set a longer timeout: pip install --timeout 120 fastapi uvicorn.
What you learned & what's next
You've successfully installed FastAPI and Uvicorn with pip, verified your environment, and run your first live API. You now understand the distinction between the framework (FastAPI) and the server (Uvicorn), and you know how to create an isolated environment to avoid dependency hell. You can also troubleshoot common installation issues with confidence.
This foundational setup unlocks everything that comes next in the FastAPI Backend Development track. You're now ready to dive into routing — defining endpoints with @app.get and @app.post — and then explore path parameters, query strings, and request bodies with Pydantic validation. The interactive docs at /docs will be your constant companion as you build more complex APIs.
In the next lesson, you'll learn how to create a simple API with multiple routes, and then move on to handling dynamic URL parameters. Your environment is ready — go build something amazing.
Practice recap
Create a new virtual environment, install FastAPI and Uvicorn, then write a second endpoint that returns a hardcoded list of items. Run it with --reload and test both GET endpoints in the browser docs at /docs. This reinforces the install process and gets you comfortable with the basic app structure.
Common mistakes
- Forgetting to activate the virtual environment — you get
ModuleNotFoundErroror install globally without realizing it. - Using
sudo pip install— this can modify system Python files and break other projects; always use a venv. - Typing
uvicorn main:appwhenmainfile isn't in the same directory — you getModuleNotFoundError: No module named 'main'. - Installing only
fastapiand forgettinguvicorn— you'll have no way to run the server.
Variations
- Use
fastapi[all]to install Uvicorn plus optional extras likepython-multipartin one command. - Pin exact versions in a
requirements.txtfor reproducibility across environments. - Use
uvicorn[standard]for production to gain performance optimizations and better watch functionality.
Real-world use cases
- Set up a development environment on a laptop for building a personal API project with auto-reload.
- Create a reproducible service container by installing pinned FastAPI and Uvicorn versions in a Docker image.
- Bootstrap a CI pipeline that installs dependencies with pip before running tests for an API codebase.
Key takeaways
- FastAPI is the framework; Uvicorn is the ASGI server — you need both to serve an API.
- Always use a virtual environment to isolate dependencies and prevent version conflicts.
- The single command
pip install fastapi uvicorninstalls both packages at once. - Verify installation with
python -c "import fastapi"to catch environment mistakes early. - Run Uvicorn with
--reloadduring development for automatic server restarts. - Interactive docs at
/docsare built-in—use them to test your endpoints instantly.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.