Introduction and Environment Setup
7 min read
Setting up a new project can sometimes feel like trying to assemble furniture without an instruction manual. But don't worry—FastAPI was built with developer experience as its highest priority.
In this guide, we are going to explore why FastAPI is taking the Python backend world by storm, how to set up an industry-standard environment, and how to write and document your very first API. Let's dive in! 🌊
1. Why FastAPI? Features and Modern Python Capabilities
The Problem
In the old days of Python web development, building a robust API meant writing endless validation logic. You had to manually write code to check if an age parameter was an integer, if an email contained an @ sign, and manually write documentation that would inevitably be outdated by the time you hit "Save." Furthermore, legacy frameworks were built before Python introduced native asynchronous programming, making it difficult to handle thousands of concurrent requests efficiently.
The Definition
FastAPI is a modern, high-performance web framework for building Application Programming Interfaces (APIs) with Python (version 3.8+), heavily relying on standard Python type hints.
The Solution
By leveraging Python's native type hinting (e.g., specifying that age: int), FastAPI inherently understands your data. It automatically validates inputs, serializes outputs (like converting Python dictionaries to JSON), and catches errors before your application logic even runs.
Because it was built from the ground up to support native asynchronous programming (async and await), it provides high concurrency. You get performance on par with NodeJS and Go, which is incredibly rare for a Python framework.
💡 Interesting Fact: FastAPI was created by Sebastián Ramírez because he was tired of plugging together different libraries to get validation, documentation, and performance. He basically built his dream tool, and it took the Python world by storm, becoming one of the fastest-growing open-source frameworks in history!
What is happening under the hood?
FastAPI is smart because it doesn't reinvent the wheel. It stands firmly on the shoulders of two giant libraries:
- Starlette: Handles the web routing and the heavy async mechanics.
- Pydantic: Handles all the complex data validation and serialization.
2. Setting Up the Environment: Python, Virtual Envs, and Uvicorn
The Problem
If you install every Python package directly into your computer's global system, eventually packages will conflict. Project A might need an older version of a library, while Project B needs the newest version. Chaos ensues, and suddenly your system Python is broken.
The Definition
A Virtual Environment (venv) is an isolated directory tree that contains its own Python installation and its own set of packages, completely separate from your global system.
The Solution
We create a virtual environment for every new project so dependencies stay isolated. Here is the strict industry-standard way to set up your environment.
Step-by-Step Setup
Step 1: Create a Project Directory
mkdir fastapi-course
cd fastapi-courseStep 2: Create the Virtual Environment
Using Python's built-in venv module, run the following command:
python -m venv venvStep 3: Activate the Virtual Environment
You must activate the environment so your terminal knows to use this isolated folder.
- macOS/Linux:
source venv/bin/activate - Windows:
venv\Scripts\activate
(You will know it worked if you see (venv) at the beginning of your terminal prompt!)
Step 4: Install FastAPI (The Modern Way)
FastAPI recently updated its installation approach to provide a better out-of-the-box experience. Instead of installing several pieces manually, you can use the [standard] flag to get everything you need for development.
pip install "fastapi[standard]"(Make sure to include the quotation marks so your terminal doesn't get confused!)
Wait, what is Uvicorn?
When you ran that installation command, you also installed something called Uvicorn.
The Problem: FastAPI is just a web framework. It defines how to handle requests and what code to run, but it cannot actually listen to a network port (like port 8000) and translate raw HTTP network traffic into Python objects by itself.
The Definition: Uvicorn is an ASGI (Asynchronous Server Gateway Interface) web server implementation for Python.
How they flow together (The Pizza Shop Analogy):
Imagine you are running a pizza shop. Uvicorn is the front-of-house staff (the waiters and cashiers). They listen to customers walking in (network requests) and bring the written orders to the kitchen. FastAPI is the head chef. The chef doesn't talk to customers directly; the chef looks at the order, prepares the pizza (processes the data and creates a JSON response), and hands it back to the waiter (Uvicorn) to serve to the customer.
You need both to run a successful API restaurant! 🍕
3. Your First FastAPI Program: Hello World
The Problem
Now that we have a framework and a server, we need a way to map an incoming HTTP GET request at the root URL (/) to a specific Python function that returns data.
The Definition
In FastAPI, a Route (or path operation) is a mapping between a specific URL path, an HTTP method (like GET, POST, PUT), and a Python function. We create this mapping using a Python decorator.
The Solution
Let's write the code. Create a file named main.py and add the following:
from fastapi import FastAPI
# 1. Create an instance of the FastAPI application
app = FastAPI()
# 2. Define the path operation decorator
@app.get("/")
def read_root():
# 3. Return a standard Python dictionary
return {"message": "Hello, FastAPI! 🚀"}Running the Server
In the past, developers had to memorize the Uvicorn command to run their apps. Now, FastAPI includes a sleek CLI (Command Line Interface) built right in.
In your terminal, run:
fastapi dev main.pyWhat happens here?
- The
fastapi devcommand finds yourappinstance insidemain.py. - It spins up the Uvicorn server in development mode, which means auto-reload is enabled. If you change your code and hit save, the server restarts automatically!
- It starts listening on
http://127.0.0.1:8000.
Open your browser and navigate to http://127.0.0.1:8000. You will see:
{"message": "Hello, FastAPI! 🚀"}(Notice how FastAPI automatically converted your Python dictionary into perfectly formatted JSON!)
4. Exploring Interactive API Documentation: Swagger UI and ReDoc
The Problem
Historically, whenever you built an API, you had to manually write and update a separate document (often a massive Wiki page or Word document) to tell front-end developers how to use it. When code changed, the documentation quickly became outdated.
🤦♂️ Fun Exaggeration: Before automatic docs, backend developers spent 40% of their time writing code and 60% of their time arguing in Slack about whether an endpoint expected an integer or a string.
The Definition
Interactive API documentation is a dynamically generated, web-based interface that describes your API endpoints, expected inputs, and outputs directly from your code's logic.
The Solution
Because FastAPI relies on standard Python type hints, it strictly knows what your API expects and returns. It uses this knowledge to automatically generate a standard OpenAPI schema. Without writing a single extra line of code, FastAPI serves this schema as interactive UI pages.
With your server still running (fastapi dev main.py), try visiting these two URLs:
1. Swagger UI (/docs)
Navigate to http://127.0.0.1:8000/docs.
You will see a beautiful interface provided by Swagger UI. This isn't just a static document; it is an interactive playground! You can click on your / endpoint, click the "Try it out" button, and execute a request directly from your browser to see the live response.
2. ReDoc (/redoc)
Navigate to http://127.0.0.1:8000/redoc.
You will see an alternative automatic documentation provided by ReDoc. This view is highly structured and incredibly readable, making it perfect for complex APIs with massive amounts of data structures. It is widely loved by teams who need to read documentation like a book.
Both views are generated automatically and will update instantly every time you add a new route or change a parameter in your Python code. No more Slack arguments! 🎉
References and Extra Reading 📚
Challenge
Task
Your goal is to create a complete, basic FastAPI application in a single file.
The application must meet the following requirements:
- Import the necessary class from the
fastapilibrary. - Create an instance of the FastAPI application and name it
app. - Implement a path operation to handle
GETrequests at the URL path/health.- This endpoint should return a JSON response with a single key-value pair:
{"status": "healthy"}.
- This endpoint should return a JSON response with a single key-value pair:
- Implement a second path operation to handle
GETrequests for dynamic item IDs at the URL path/items/{item_id}.- The
item_idin the path must be validated as an integer. - This endpoint should return a JSON response containing the captured ID, for example:
{"item_id": 123}where123is the ID from the URL.
- The
Expected result
Your code should define a FastAPI application with two endpoints. It must first import FastAPI, then create an instance named app.
It should include a function decorated with @app.get("/health") that returns the dictionary {"status": "healthy"}.
It must also include a second function decorated with @app.get("/items/{item_id}"). This function must accept one argument, item_id, with a Python type hint of int. The function should return a dictionary containing the received ID, like {"item_id": item_id}.