Chapter 3.1: Installing FastAPI and Setting Up the Environment
Time to learn: 45 minutes
1. What is FastAPI? A Hyperdrive for APIs
If Flask is a nimble reconnaissance probe and Django is a massive carrier ship, then FastAPI is a superluminal fighter jet.
FastAPI is a modern, high-performance web framework for creating APIs with Python 3.7+. Its main advantages are:
- Speed: One of the fastest Python frameworks, comparable to NodeJS and Go.
- Simplicity: Minimalist and intuitive syntax.
- Auto-documentation: Automatically creates interactive documentation for your API.
- Typing: Uses standard Python type hints for validation, autocompletion, and documentation.
💡 Space Analogy:
FastAPI is like a "hyperdrive" for your API ship. It is based on two technologies:
- Starlette (the fighter's chassis) — provides asynchronicity and top-tier performance.
- Pydantic (the onboard computer) — handles data validation and settings.
2. Preparing the Launchpad: Virtual Environment
Before we build our fighter jet, we need to create a sterile assembly laboratory. In Python, this is done using virtual environments.
Why is this necessary? To prevent the dependencies of our project (engines, navigation systems) from conflicting with other projects on your computer.
Step 1: Create a virtual environment
Open a terminal in your project folder (e.g., C:\Projects\FastAPI_Fleet
) and run:
venv
folder with an isolated version of Python.
Step 2: Activate the lab's "force field"
- Windows (PowerShell):
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
)
- Windows (CMD):
- macOS / Linux:
(venv)
will appear at the beginning of your terminal prompt. This means you are inside your lab!
3. Installing the Engine: FastAPI and Uvicorn
Now let's install two key components:
- fastapi: The framework itself.
- uvicorn: A lightning-fast ASGI server that will "run" our engine.
Execute in the activated environment:
💡 Why
[all]
? This will installfastapi
,uvicorn
, and other useful packages (e.g., for WebSocket support and Jinja2) that will be useful in future missions.
Check the installation:
You should seefastapi
, pydantic
, starlette
, uvicorn
, and other packages in the list.
4. First Contact: The main.py
File
Create a main.py
file in the root of your project — this will be the central control panel of our API.
Add the following code to main.py
:
from fastapi import FastAPI
# Create an instance of our API "spaceship"
app = FastAPI()
# Define the first "docking port" (endpoint)
# This is the root URL: /
@app.get("/")
def read_root():
"""
This is the Mission Control message that everyone sees
when they connect to the main gateway.
"""
return {"message": "Welcome to the Space Fleet Command Center!"}
@app.get("/")
: This is a decorator that tells FastAPI that the read_root
function should handle GET
requests to the root URL (/
).
5. Ignition! Starting the Server
It's time to start our hyperdrive! In the terminal (with venv
active), run:
uvicorn
: We are starting the Uvicorn server.main
: Themain.py
file (without the.py
).app
: Theapp = FastAPI()
object created insidemain.py
.--reload
: "Autopilot". The server will automatically restart every time you change the code.
Expected output in the terminal:
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]
INFO: Waiting for application startup.
INFO: Application startup complete.
6. Communicating with Mission Control
Your API is now online and listening on port 8000
!
Step 1: Check in the browser
Open http://127.0.0.1:8000
in your browser. You should see:
Step 2: A glimpse into the future (auto-documentation)
FastAPI has already created two gifts for you. Open these URLs:
http://127.0.0.1:8000/docs
: Interactive Swagger UI documentation.http://127.0.0.1:8000/redoc
: Alternative ReDoc documentation.
You will see your first endpoint, which you can test directly from the browser!
Review Quiz
🚀 Chapter Summary:
You have successfully assembled and launched the "hyperdrive" of your new API! You now have:
- 🛠️ An isolated development environment (
venv
) - 🚀 FastAPI and the Uvicorn server installed
- 🛰️ A running API with a single endpoint
- 📊 Automatically generated documentation
All systems are go! In the next chapter, we will create our first full-fledged endpoint that will return a list of spacecraft.
📌 Checkpoint:
- The
(venv)
environment is active in the terminal- The
uvicorn
server is running without errors- The address
http://127.0.0.1:8000/docs
opens in the browser⚠️ If you have errors:
command not found
: Make sure you have activated the virtual environment.Port ... is already in use
: Another program is using port 8000. Stop it or run uvicorn on a different port:uvicorn main:app --reload --port 8001
.- Errors activating
venv
in PowerShell: Check the script execution policy.