Skip to main content

FastAPI Hello World

Welcome to the world of FastAPI! In this lesson, we'll create our very first FastAPI application - the classic "Hello World" example. This simple project will help you understand the basics of FastAPI and set you up for building more complex applications in the future.

What is FastAPI?

Before diving in, let's briefly understand what FastAPI is. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It's designed to be easy to use while providing automatic interactive documentation, data validation, and more.

Key features of FastAPI include:

  • Fast: Very high performance, on par with NodeJS and Go
  • Easy: Designed to be easy to use and learn
  • Short: Minimize code duplication
  • Robust: Get production-ready code with automatic interactive documentation
  • Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI and JSON Schema

Prerequisites

Before we start, make sure you have:

  • Python 3.7+ installed
  • Basic understanding of Python
  • pip (Python package installer)

Setting Up Your Environment

First, let's create a virtual environment and install FastAPI and Uvicorn (an ASGI server we'll use to run our application).

bash
# Create a virtual environment
python -m venv fastapi-env

# Activate the virtual environment
# On Windows
fastapi-env\Scripts\activate
# On macOS/Linux
source fastapi-env/bin/activate

# Install FastAPI and Uvicorn
pip install fastapi uvicorn

Creating Your First FastAPI Application

Now, let's create our first FastAPI application. Create a new file called main.py and add the following code:

python
from fastapi import FastAPI

# Create an instance of the FastAPI class
app = FastAPI()

# Define a route using a decorator
@app.get("/")
def read_root():
return {"message": "Hello, World!"}

Let's break down this code:

  1. Import FastAPI: We import the FastAPI class from the fastapi module.
  2. Create an app instance: We create an instance of the FastAPI class and assign it to the variable app.
  3. Define a route: We use the @app.get("/")decorator to define a route for HTTP GET requests to the root path /.
  4. Create a function: The function read_root() is called when a request is made to the route.
  5. Return a response: The function returns a JSON response with the message "Hello, World!".

Running Your FastAPI Application

To run your application, use the following command in your terminal:

bash
uvicorn main:app --reload

This command tells Uvicorn to:

  • Look for the app variable inside the main.py module
  • Run it as an API server
  • The --reload flag enables auto-reloading when code changes

If everything works correctly, you should see output similar to:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.

Testing Your API

Now that your API is running, let's test it:

  1. Using a Web Browser: Open your web browser and navigate to http://127.0.0.1:8000/. You should see a JSON response: {"message":"Hello, World!"}.

  2. Using Curl: If you have curl installed, you can use it from your terminal:

    bash
    curl http://127.0.0.1:8000/

    Output:

    json
    {"message":"Hello, World!"}

Exploring FastAPI's Automatic Documentation

One of the great features of FastAPI is its automatic interactive documentation. Visit:

  • http://127.0.0.1:8000/docs - for Swagger UI documentation
  • http://127.0.0.1:8000/redoc - for ReDoc documentation

These pages provide interactive documentation for your API, allowing you to:

  • See all available endpoints
  • Test the API directly from the browser
  • View expected parameters and responses

Adding a Path Parameter

Let's enhance our API by adding a new endpoint with a path parameter:

python
@app.get("/hello/{name}")
def read_item(name: str):
return {"message": f"Hello, {name}!"}

In this code:

  1. We define a new route /hello/{name} where {name} is a path parameter.
  2. The function read_item() takes a parameter name with type annotation str.
  3. FastAPI automatically validates that name is a string.
  4. We return a personalized greeting.

Now restart your server (if it's not auto-reloading) and try:

  • Visit http://127.0.0.1:8000/hello/FastAPI in your browser
  • You should see: {"message":"Hello, FastAPI!"}

Adding Query Parameters

Now, let's add query parameters to our API:

python
@app.get("/greeting")
def greeting(name: str = "World", enthusiastic: bool = False):
if enthusiastic:
return {"message": f"Hello, {name}!!!"}
return {"message": f"Hello, {name}"}

In this example:

  1. We define a route /greeting with no path parameters.
  2. The function has two query parameters: name with a default value of "World" and enthusiastic with a default value of False.
  3. The response changes based on the parameters.

Try these URLs:

  • http://127.0.0.1:8000/greeting{"message":"Hello, World"}
  • http://127.0.0.1:8000/greeting?name=FastAPI{"message":"Hello, FastAPI"}
  • http://127.0.0.1:8000/greeting?enthusiastic=true{"message":"Hello, World!!!"}
  • http://127.0.0.1:8000/greeting?name=FastAPI&enthusiastic=true{"message":"Hello, FastAPI!!!"}

A Complete Example

Here's our complete main.py file with all the routes we've created:

python
from fastapi import FastAPI

app = FastAPI(
title="Hello World API",
description="A simple API to demonstrate FastAPI basics",
version="0.1.0"
)

@app.get("/")
def read_root():
return {"message": "Hello, World!"}

@app.get("/hello/{name}")
def read_item(name: str):
return {"message": f"Hello, {name}!"}

@app.get("/greeting")
def greeting(name: str = "World", enthusiastic: bool = False):
if enthusiastic:
return {"message": f"Hello, {name}!!!"}
return {"message": f"Hello, {name}"}

Real-world Application: Simple User Management API

Let's create a slightly more complex example that resembles a real-world scenario - a simple user management API:

python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import uuid

app = FastAPI(title="User Management API")

# Define a Pydantic model for our User data
class User(BaseModel):
id: str
name: str
email: str
active: bool = True

# In-memory database
users_db = {}

@app.post("/users/", response_model=User)
def create_user(name: str, email: str):
user_id = str(uuid.uuid4())
user = User(id=user_id, name=name, email=email)
users_db[user_id] = user
return user

@app.get("/users/", response_model=List[User])
def read_users(skip: int = 0, limit: int = 10):
return list(users_db.values())[skip : skip + limit]

@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: str):
if user_id not in users_db:
raise HTTPException(status_code=404, detail="User not found")
return users_db[user_id]

@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: str, name: Optional[str] = None, email: Optional[str] = None):
if user_id not in users_db:
raise HTTPException(status_code=404, detail="User not found")

user = users_db[user_id]

if name is not None:
user.name = name
if email is not None:
user.email = email

return user

@app.delete("/users/{user_id}")
def delete_user(user_id: str):
if user_id not in users_db:
raise HTTPException(status_code=404, detail="User not found")

del users_db[user_id]
return {"message": "User deleted successfully"}

This example demonstrates a more complete API with:

  • Data models using Pydantic
  • Multiple HTTP methods (GET, POST, PUT, DELETE)
  • Error handling
  • Query parameters for pagination

Summary

In this lesson, we've covered:

  1. Setting up a FastAPI application
  2. Creating a basic "Hello World" endpoint
  3. Working with path parameters
  4. Using query parameters
  5. Exploring FastAPI's automatic documentation
  6. Building a more complex API with multiple endpoints

FastAPI makes it incredibly easy to create APIs with minimal code while providing powerful features like automatic documentation, data validation, and more. This "Hello World" example is just the beginning of what you can do with FastAPI!

Exercises

To reinforce your learning, try these exercises:

  1. Add a new endpoint that returns the current time in your timezone.
  2. Create a calculator API with endpoints for addition, subtraction, multiplication, and division.
  3. Enhance the user management API to include user details like age and address.
  4. Implement input validation in your user management API (e.g., email format validation).

Additional Resources

Happy coding with FastAPI!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)