How to Install FastAPI and Create Your First API

Picture a small retail chain that wants its website and phone app to read store hours from one place. A tiny API solves that, and you can have one running in about ten minutes.

In this tutorial, we’ll install FastAPI inside a virtual environment using pip install "fastapi[standard]", then build that store-hours API. I ran every command below on Windows with Python 3.12.5 and FastAPI 0.162.2.

Here’s what we’re building: an API with its own interactive documentation page.

Swagger UI at the FastAPI docs URL listing the home and get hours endpoints of the Store Hours API
The finished Store Hours API, documented automatically at /docs.

Before You Start: What You Need to Install FastAPI

You need Python 3.10 or newer, since that’s the minimum the current FastAPI release accepts on PyPI. Check yours with python --version. If you juggle several interpreters, installing multiple Python versions explains how to pick one.

Our running sample is three stores, kept in a plain dictionary so a database doesn’t get in the way:

KeyCityOpensCloses
austinAustin, TX8:00 AM9:00 PM
denverDenver, CO9:00 AM8:00 PM
bostonBoston, MA7:30 AM6:00 PM

Step 1: Create a Virtual Environment

A virtual environment is a private folder of packages for one project, so this install can’t break anything else. If you’re still deciding what to build with Python, this setup fits most projects. Open Command Prompt and run these one at a time:

  1. Make the project folder with mkdir store-api, then cd store-api.
  2. Create the environment with python -m venv .venv.
  3. Activate it with .venv\Scripts\activate.
mkdir store-api
cd store-api
python -m venv .venv
.venv\Scripts\activate
Command Prompt creating and activating a Python virtual environment named .venv in a store-api folder
The (.venv) prefix tells you the environment is active.

Other shells use a different activation line. On macOS, use python3 if python isn’t found:

ShellActivate command
Windows Command Prompt.venv\Scripts\activate
Windows PowerShell.venv\Scripts\Activate.ps1
macOS / Linuxsource .venv/bin/activate
# macOS / Linux
mkdir store-api && cd store-api
python3 -m venv .venv
source .venv/bin/activate

Checkpoint: your prompt now starts with (.venv).

Step 2: Run pip install “fastapi[standard]”

With the environment active, install FastAPI plus its standard extras. Keep the quotes, because some shells treat square brackets as a pattern:

pip install "fastapi[standard]"
Command Prompt showing pip install fastapi standard finishing with a successfully installed package list
One command brings in FastAPI, the server and the CLI.

Checkpoint: pip ends with Successfully installed. That one line added 59 packages, including the fastapi command and the Uvicorn server. For a fixed release later, pin a specific version with pip.

Step 3: Verify the FastAPI Version

Before writing code, confirm that the install landed in the right place. Two quick commands cover it:

fastapi --version
python -c "import fastapi; print(fastapi.__version__)"
Command Prompt showing the FastAPI CLI version and the fastapi package version
Both commands read from the .venv folder.
FastAPI CLI version: 0.0.32
FastAPI Cloud CLI version: 0.27.1

0.162.2

Checkpoint: you see version 0.162.2, or a newer one.

Step 4: Write Your First API in main.py

Create main.py in the store-api folder and paste this complete file. Each decorator maps a URL to a plain function, and {city} becomes the function’s city argument:

from fastapi import FastAPI, HTTPException

app = FastAPI(title="Store Hours API")

STORE_HOURS = {
    "austin": {"city": "Austin, TX",
               "opens": "8:00 AM", "closes": "9:00 PM"},
    "denver": {"city": "Denver, CO",
               "opens": "9:00 AM", "closes": "8:00 PM"},
    "boston": {"city": "Boston, MA",
               "opens": "7:30 AM", "closes": "6:00 PM"},
}


@app.get("/")
def home():
    return {"message": "Store Hours API is running"}


@app.get("/hours/{city}")
def get_hours(city: str):
    store = STORE_HOURS.get(city.lower())
    if store is None:
        raise HTTPException(status_code=404, detail="No store in that city")
    return store
VS Code editor showing the complete FastAPI main.py for the Store Hours API with a syntax check in the terminal
The whole API fits on one screen.

Whatever dictionary you return is sent as JSON. An unknown city raises HTTPException, which FastAPI turns into a 404 response. The capitals on STORE_HOURS follow the naming convention for Python constants.

Step 5: Start the Server with fastapi dev

In the same terminal, with (.venv) still showing, run the development server. Any editor works here, and PyCharm vs VS Code compares the two popular ones:

fastapi dev main.py
VS Code terminal running fastapi dev main.py with the server listening on 127.0.0.1 port 8000
The server is up on port 8000.
Server started at http://127.0.0.1:8000
Documentation at http://127.0.0.1:8000/docs
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Application startup complete.

Checkpoint: the terminal shows the server address and stays busy. That’s normal, so leave it running and press Ctrl+C only when you’re finished.

Step 6: Open Your Endpoint in the Browser

Go to http://127.0.0.1:8000/hours/austin in any browser:

Browser showing the JSON store hours for Austin returned by the FastAPI endpoint
The Austin entry from the dictionary, returned as JSON.

Checkpoint: the page shows Austin, TX, opening at 8:00 AM and closing at 9:00 PM.

Step 7: Open /docs and Try the Endpoint

FastAPI generates a Swagger UI page from your code. Open http://127.0.0.1:8000/docs, then:

  1. Click GET /hours/{city} to expand it.
  2. Click Try it out.
  3. Type austin in the city box.
  4. Click Execute.
Swagger UI showing a 200 response with the Austin store hours after executing the get hours endpoint
Swagger sends a real request and shows the response below it.

Checkpoint: Code reads 200 and the response body matches what the browser showed.

Test the Store Hours API

Let’s prove the edge cases too. This script uses httpx, which the standard extras installed. Run it from a second terminal while the server keeps going:

import httpx

BASE = "http://127.0.0.1:8000"

for path in ("/", "/hours/austin", "/hours/DENVER", "/hours/tampa"):
    response = httpx.get(BASE + path)
    print(path, "->", response.status_code)
    print(response.json())

Output:

/ -> 200
{'message': 'Store Hours API is running'}
/hours/austin -> 200
{'city': 'Austin, TX', 'opens': '8:00 AM', 'closes': '9:00 PM'}
/hours/DENVER -> 200
{'city': 'Denver, CO', 'opens': '9:00 AM', 'closes': '8:00 PM'}
/hours/tampa -> 404
{'detail': 'No store in that city'}
VS Code output of a Python script calling the FastAPI store hours endpoints with 200 and 404 responses
Three successful lookups, then a 404.

The first three requests return 200, and DENVER works because we lowercase the city. Tampa gets a 404 since it isn’t in our three stores. Those checks run on the str type FastAPI reads from the URL.

pip install fastapi vs fastapi[standard]: Which Should You Use?

Same store-hours file, different install. In a second environment I ran plain pip install fastapi, then tried the same start command:

Command Prompt showing the fastapi dev command failing after a plain pip install fastapi
A plain install has no server, so the command stops here.
To use the fastapi command, please install "fastapi[standard]":

	pip install "fastapi[standard]"
pip install fastapipip install “fastapi[standard]”
Packages added (my run)1159
fastapi dev worksNoYes
Uvicorn server includedNoYes
Best forSlim production imagesLearning and everyday work

Plain installs still work when you add a server yourself. After this, the Boston lookup returned the right JSON from the same main.py:

pip install uvicorn
uvicorn main:app --reload

Troubleshooting FastAPI Install Errors

I triggered the first three of these for real, so the messages are exact. The last three come from shells I didn’t run this on:

ErrorFix
'fastapi' is not recognized as an internal or external commaThe environment isn’t active. Run the activate line again.
ModuleNotFoundError: No module named 'fastapi'You installed into a different Python. Activate .venv and reinstall.
To use the fastapi command, please install...Run pip install "fastapi[standard]".
Address already in use on macOS or LinuxAnother server owns port 8000. Stop it, or add --port 8001.
zsh: no matches found on macOSYou left off the quotes around fastapi[standard].
PowerShell says running scripts is disabledRun Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process, then activate again.

Note: on my Windows machine, a second fastapi dev on port 8000 started without any error, and both servers listened at once. If you edit code and nothing changes, close your old terminals first.

Still stuck on an import? This ModuleNotFoundError guide walks through the usual causes.

Where to Take It Next

Your install works, so the natural next step is the FastAPI tutorial for beginners, which adds POST requests and Pydantic validation. When you’ve got settings to protect, keep them in environment variables.

Curious about something heavier? See how to deploy a machine learning model with FastAPI and Docker.

A few more pages worth opening from here:

Frequently asked questions

Do I need a virtual environment to install FastAPI?

It isn’t strictly required, but I’d always use one. It keeps FastAPI and its dependencies away from your other projects.

What Python version does FastAPI need?

The current release on PyPI requires Python 3.10 or newer. Run python --version to check yours.

What’s the difference between fastapi dev and uvicorn?

fastapi dev starts Uvicorn with auto-reload for you. Calling uvicorn main:app --reload does a similar job by hand.

How do I update FastAPI?

Activate the environment and run pip install --upgrade "fastapi[standard]", then confirm with fastapi --version.

Where are the official FastAPI install instructions?

The FastAPI tutorial’s install section is the official reference and tracks each release.