No history yet

Introduction to FastAPI

Meet FastAPI

When building a web API, you want it to be fast, reliable, and easy to maintain. Python has many tools for this, but one of the most popular modern frameworks is FastAPI. As its name suggests, speed is a core feature. It's built to be one of the highest-performing Python frameworks available.

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

But it's not just about raw performance. FastAPI is designed for a great developer experience. It's simple to learn and use, which means you can build things quickly. One of its standout features is the automatic generation of interactive API documentation. This means you get a user-friendly interface to test and explore your API right out of the box, with almost no extra effort.

Your First FastAPI Project

Let's get a basic project up and running. First, you need to install FastAPI and a server to run it. We'll use Uvicorn, a lightning-fast server ideal for FastAPI. You can install them both using pip.

pip install fastapi
pip install "uvicorn[standard]"

With the packages installed, create a new file named main.py. This file will hold your application's code. Add the following lines to it.

from fastapi import FastAPI

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

# Define a path operation decorator
@app.get("/")
def read_root():
    return {"Hello": "World"}

This small snippet is a complete API. Let's break it down:

  1. from fastapi import FastAPI: This imports the main FastAPI class.
  2. app = FastAPI(): This creates an instance of your application.
  3. @app.get("/"): This is a "path operation decorator." It tells FastAPI that the function below it is in charge of handling requests that go to the main URL (/) using a GET method.
  4. def read_root(): ...: This is the function that will be called when a user visits the / URL. It returns a Python dictionary, which FastAPI automatically converts into a JSON response.

Running the Server

Now you're ready to run your API. Open your terminal in the same directory as your main.py file and type the following command.

uvicorn main:app --reload

Here’s what that command does:

  • main: Refers to your main.py file.
  • app: Refers to the app = FastAPI() object you created inside the file.
  • --reload: This is a helpful option for development. It tells Uvicorn to automatically restart the server whenever you save changes to your code.

Once you run the command, Uvicorn will start a local server. You can now open your web browser and navigate to http://127.0.0.1:8000. You should see the JSON response {"Hello":"World"}.

The Magic of Auto-Docs

Remember the automatic documentation? Let's see it in action. With your server still running, go to http://127.0.0.1:8000/docs in your browser. You'll see an interactive API documentation page (powered by Swagger UI) that lists all your endpoints. You can even try them out directly from this page.

FastAPI also provides an alternative documentation interface. If you go to http://127.0.0.1:8000/redoc, you'll find a clean, comprehensive view of your API provided by ReDoc.

Lesson image

These built-in documentation tools are incredibly useful. They make testing, sharing, and collaborating on APIs much simpler because the documentation is always up-to-date with your code.

Creating Another Endpoint

Let's add one more endpoint to see how easy it is. This one will take a parameter from the URL. Update your main.py file:

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

Here, we've added a new path @app.get("/items/{item_id}"). The {item_id} part declares a path parameter. The function read_item accepts an argument with the same name, item_id. By adding the type hint item_id: int, we're telling FastAPI to validate that the input is an integer.

Because you started the server with --reload, it should have already updated. Go back to your browser and visit http://127.0.0.1:8000/items/5. You'll see {"item_id":5}. If you try a non-integer like http://127.0.0.1:8000/items/foo, FastAPI automatically returns a clear error message.

This is just a small taste of what FastAPI can do. You've set up a project, created endpoints, and seen its powerful automatic features in action.