Skip to content
Visual explainer 2h 30m to learn 5 steps

Run a typed FastAPI service locally

Create, run and smoke-test a FastAPI service in a virtual environment with pinned packages.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.

Topic 2 of 29

In short

A first FastAPI service needs only a virtual environment, a few pinned packages and one Python file that creates the app. You run it with Uvicorn or the fastapi command, which reloads on code changes during development. FastAPI then serves interactive OpenAPI docs, and a curl smoke test proves the service answers correctly.

Explained simply

To build your first FastAPI service you need Python 3, a terminal and a code editor. First you create a virtual environment. This is a private folder of packages just for this project, so installing FastAPI here does not change anything else on your computer.

Next you install FastAPI and record the exact versions you got. That record, often a requirements.txt file, lets a teammate or a server install the very same versions later. Without it, a new release could change behaviour without warning.

Then you write one Python file, usually main.py, that creates the app with app = FastAPI() and adds a route or two. Type hints on your function parameters tell FastAPI what input to expect and what to check.

You start the service with fastapi dev main.py or uvicorn main:app --reload. Reload means the server restarts by itself whenever you save a file. Open http://127.0.0.1:8000/docs in a browser and you will see interactive documentation built from your code.

Finally you run a smoke test: a quick curl command that calls a route and checks the answer. If the status is 200 and the JSON looks right, your service works. When you are done, stop the server with Ctrl+C.

Press Play on a diagram to walk through it one step at a time.

FlowFrom empty folder to a tested service
  1. 1
    Create venv

    python -m venv .venv and activate it

  2. 2
    Install and pin

    pip install fastapi[standard], then freeze versions

  3. 3
    Write main.py

    app = FastAPI() and one typed route

  4. 4
    Run with reload

    fastapi dev main.py or uvicorn main:app --reload

  5. 5
    Open /docs

    Swagger UI built from your type hints

  6. 6
    Smoke-test

    curl the health and echo routes

MapA small, tidy project layout
docs-qa/
  • .venv/
    • Local packages
    • Listed in .gitignore, never committed
  • app/
    • __init__.py
    • main.py (creates app)
    • routes/ for routers later
  • requirements.txt
    • Exact pinned versions
  • tests/
    • test_smoke.py
  • .gitignore

In depth

Virtual environments and pinned packages

Create the environment inside the project with python -m venv .venv, then activate it: source .venv/bin/activate on Linux and macOS, or .venv\Scripts\activate on Windows. Your prompt changes to show (.venv), and python and pip now point into that folder. Add .venv/ to .gitignore; you commit the list of packages, never the folder.

Install with pip install "fastapi[standard]". The standard extra brings Uvicorn, the fastapi command line tool and a few helpers. Then write the exact versions to a file with pip freeze > requirements.txt. Anyone can rebuild the same set with pip install -r requirements.txt. Tools such as pip-tools, Poetry or uv produce lock files that do the same job with hashes and clearer upgrade steps. Whatever you choose, upgrade on purpose, run your tests, and commit the new lock file.

  • python -m venv .venv
  • source .venv/bin/activate
  • pip install "fastapi[standard]"
  • pip freeze > requirements.txt
  • deactivate leaves the environment

The app entry point

A server needs to know which object is your application. You tell it with module:variable. For a file main.py containing app = FastAPI(), that is main:app. In a package layout such as app/main.py it becomes app.main:app, and you run the command from the project root so Python can import the package.

Keep the entry point small. It should create the FastAPI object, set the title and version that appear in the docs, and include routers. Business logic lives in other modules. This makes the app easy to import in tests, where you build a TestClient around the same app object. Avoid doing work at import time, such as connecting to a database, because importing the module should be cheap and safe. Startup work belongs in the lifespan handler, which the next module covers.

Running it: fastapi dev, fastapi run and uvicorn

The fastapi command finds your app and starts Uvicorn for you. fastapi dev main.py is for development: it turns on auto-reload and listens on 127.0.0.1, which only your own machine can reach. fastapi run main.py is the production style: no reload, and it listens on 0.0.0.0 so it is reachable inside a container. Both default to port 8000.

You can also call Uvicorn directly: uvicorn main:app --reload --port 8000. Uvicorn on its own listens on 127.0.0.1 unless you pass --host 0.0.0.0. Reload works by watching your files and restarting the process on every save. That is great while coding but wastes resources and can hide startup problems in production, so never use it there.

CompareThree ways to start the same app
fastapi dev main.py
  • Auto-reload on
  • Listens on 127.0.0.1
  • Port 8000
  • For local development
fastapi run main.py
  • No reload
  • Listens on 0.0.0.0
  • Port 8000
  • Production style, for example in a container
uvicorn main:app
  • You choose every flag
  • 127.0.0.1 unless --host is set
  • --reload only if asked
  • Useful when you need fine control

OpenAPI and the interactive docs

FastAPI builds an OpenAPI document from your routes, parameters, Pydantic models and return types. It serves the raw JSON at /openapi.json, an interactive Swagger UI at /docs, and a reading view at /redoc. In /docs you can expand a route, press Try it out, fill in parameters and send a real request.

The docs are only as good as your code. Set title and version on FastAPI(), add a summary and tags to routes, and use clear model and field names. Because clients can generate typed code from /openapi.json, treat it as a contract: changing a field name breaks those clients. If a service must not expose its schema publicly, pass docs_url=None, redoc_url=None and openapi_url=None, or protect them behind authentication.

A smoke test you can trust

A smoke test answers one question: does the service start and answer correctly? Start the server in one terminal. In another, call the health route with curl -i so you see the status line and headers as well as the body. Then call a route with real input, such as POST /v1/echo with a JSON body, and confirm the body comes back.

Use curl --fail in scripts so curl exits with an error code when the status is 400 or higher; that lets a script or CI job stop on failure. Expected evidence: HTTP/1.1 200 OK, content-type: application/json, and the JSON you sent. Cleanup is simple: Ctrl+C stops the server, deactivate leaves the virtual environment, and deleting .venv removes everything you installed.

  • curl -i shows status and headers
  • curl --fail exits non-zero on 4xx and 5xx
  • Check status, content type and body
  • Ctrl+C, deactivate, rm -rf .venv to clean up

Learn it in 5 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Create a venv and pin packages~30m
  2. 2
    Write the app entry point~30m
  3. 3
    Run Uvicorn with reload~30m
  4. 4
    Open the OpenAPI docs~30m
  5. 5
    Smoke-test with curl~30m

Key points

  • A virtual environment keeps the project's packages separate from the system Python.
  • Pin exact versions in a requirements or lock file so every machine installs the same thing.
  • Type hints on route parameters drive validation and the generated OpenAPI schema.
  • Reload is for development only; production runs without it.
  • A smoke test is a tiny check that the service starts and answers, not a full test suite.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Docs Q&A", version="0.1.0")

class Echo(BaseModel):
    text: str

@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}

@app.post("/v1/echo")
def echo(body: Echo) -> Echo:
    return body

Save as main.py. Run with: fastapi dev main.py, then open http://127.0.0.1:8000/docs

Bootstrap a service from an empty folder

Prerequisites: Python 3.10 or newer and curl. These commands create the environment, install and pin FastAPI, and start the example app from the explainer in development mode. Expected evidence: the server log shows it is serving at http://127.0.0.1:8000, and the health check prints {"status":"ok"}. Rollback is deleting the folder.

bash
mkdir docs-qa && cd docs-qa
python3 -m venv .venv
source .venv/bin/activate
pip install "fastapi[standard]"
pip freeze > requirements.txt
echo ".venv/" > .gitignore
# write main.py from the explainer, then:
fastapi dev main.py
# in a second terminal:
curl -i http://127.0.0.1:8000/health

Typed path and query parameters in the docs

Here document_id is a path parameter typed as int and limit is an optional query parameter with a default. Open /docs and the route shows both with their types. GET /v1/documents/7?limit=3 returns 200. GET /v1/documents/abc returns 422 because abc is not an integer. That one type hint gave you validation, docs and a clear error for free.

python
from fastapi import FastAPI

app = FastAPI(title="Docs Q&A", version="0.1.0")

@app.get("/v1/documents/{document_id}", tags=["documents"])
def get_document(document_id: int, limit: int = 10) -> dict:
    return {"id": document_id, "limit": limit}

Quick reference

  • python -m venv .venv then source .venv/bin/activate (Windows: .venv\Scripts\activate).
  • pip install "fastapi[standard]" installs FastAPI, Uvicorn and the fastapi CLI.
  • pip freeze > requirements.txt pins exact versions; pip install -r requirements.txt restores them.
  • fastapi dev main.py: reload on, 127.0.0.1:8000. fastapi run main.py: no reload, 0.0.0.0:8000.
  • uvicorn main:app --reload runs module main, variable app.
  • Docs: /docs (Swagger UI), /redoc, raw schema at /openapi.json.
  • curl -i --fail URL shows headers and fails the script on 4xx or 5xx.
  • Never commit .venv; commit the requirements or lock file.

Common mistakes

  • Installing packages globally and then wondering why another project broke.
  • Leaving --reload on in production, which watches files and wastes resources.
  • Binding to 0.0.0.0 on a laptop on public Wi-Fi when 127.0.0.1 is enough.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the main reason to use a virtual environment?

Question 2

2Your app object is called api in the file service/server.py. What do you pass to Uvicorn?

Question 3

3Which command is meant for production use?

Question 4

4A route has document_id: int. What does GET /v1/documents/abc return?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a virtual environment, install FastAPI with the standard extra, pin the versions, and run a main.py that has a /health route. Show the evidence that it works.

  2. Exercise 2medium

    Add GET /v1/search with a required q string and an optional page integer that defaults to 1. Check in /docs that q is marked required, then call it without q and note the status.

  3. Exercise 3hard

    Write a shell script that starts the app in the background with fastapi run, waits until /health answers, posts to /v1/echo, checks the body, and always stops the server at the end.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use pip, Poetry or uv?
Any of them works if you pin versions and commit the lock or requirements file. Pick one per project and use it everywhere, including in CI and Docker.
Why can my phone not reach the app running on my laptop?
fastapi dev and plain uvicorn listen on 127.0.0.1, which only accepts connections from the same machine. Use --host 0.0.0.0 on a trusted network if you really need outside access.
Can I hide the /docs page in production?
Yes. Pass docs_url=None, redoc_url=None and openapi_url=None to FastAPI(), or put the docs behind authentication.
Which Python version should I use?
Use a currently supported Python 3 release that your FastAPI version supports; check the FastAPI release notes. Use the same version locally, in CI and in production.

Go deeper

ShareXLinkedInWhatsApp