python | fastapi

How to develop APIs with Python FastAPIs

How to develop APIs with Python FastAPIs

FastAPI is a modern, fast, and highly efficient Python web framework for building web APIs. It is designed to make it easy to create RESTful APIs with Python while providing features like automatic documentation generation, validation, and asynchronous support. Here are some key features and characteristics of FastAPI:

  1. High Performance: FastAPI is built on top of Starlette and Pydantic, two asynchronous Python libraries known for their performance. This makes FastAPI one of the fastest web frameworks available for Python.

  2. Automatic API Documentation: FastAPI includes an interactive and automatically generated API documentation system. You can use tools like Swagger UI and ReDoc to explore and test your API endpoints without writing additional documentation.

  3. Type Annotations: It leverages Python type hints and annotations to define the expected request and response data models. This not only helps with automatic validation but also makes your code more readable and maintainable.

  4. Asynchronous Support: FastAPI fully supports asynchronous programming, allowing you to create efficient and non-blocking APIs, which is crucial for handling concurrent requests.

  5. Data Validation: FastAPI uses Pydantic models for data validation. It automatically validates incoming data against your defined models, making it easy to handle request and response data.

  6. Dependency Injection: You can use FastAPI’s built-in dependency injection system to manage shared objects, dependencies, and database connections in a clean and organized way.

  7. Middleware: Like other web frameworks, FastAPI supports middleware to customize request and response handling. You can add middleware for authentication, logging, and other purposes.

  8. WebSockets: FastAPI also provides WebSocket support, allowing you to build real-time applications and features.

  9. Security: FastAPI includes built-in security features, such as authentication, OAuth2, and automatic generation of OpenAPI security documentation.

  10. Extensible: It’s easy to extend FastAPI by integrating it with other Python libraries and frameworks. You can use it with databases like SQLAlchemy and ORMs or with front-end frameworks like React and Vue.js.

  11. Community and Ecosystem: FastAPI has gained significant popularity within the Python community, and it has an active ecosystem with various extensions and third-party packages.

Overall, FastAPI is an excellent choice for developing web APIs and microservices in Python. Its combination of performance, automatic documentation, and data validation makes it a compelling option for both new and experienced Python developers.

Setting up a basic FastAPI Python application involves a few steps. In this example, I’ll guide you through the process of creating a simple FastAPI project and running a “Hello, World!” API.

Prerequisites:

  1. Python 3.6 or higher installed on your system.

  2. A code editor or IDE of your choice (e.g., Visual Studio Code, PyCharm).

Here’s how to set up a basic FastAPI project:

1. Create a Project Directory:

Open your terminal and create a directory for your FastAPI project:

mkdir fastapi_project
cd fastapi_project

2. Create a Virtual Environment (Optional but recommended):

It’s a good practice to work within a virtual environment to isolate your project’s dependencies. Run the following commands:

python -m venv venv
source venv/bin/activate  # On Windows, use "venv\Scripts\activate"

3. Install FastAPI and Uvicorn:

FastAPI is the web framework, and Uvicorn is a lightweight ASGI server that will run your FastAPI application. Install them using pip:

pip install fastapi uvicorn

4. Create a FastAPI App:

Create a Python script (e.g., main.py) in your project directory to define your FastAPI application:

from fastapi import FastAPI

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

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

5. Run the FastAPI App:

Use Uvicorn to run your FastAPI application:

uvicorn main:app --reload
  • main:app refers to the module and the instance of the FastAPI app you created in main.py.
  • --reload enables auto-reloading, which is helpful during development.

6. Access Your API:

Open a web browser or use a tool like curl or httpie to access your API:

  • http://localhost:8000

You should see a JSON response: {"message": "Hello, World!"}.

7. Deactivate the Virtual Environment (Optional):

When you’re done working on your FastAPI project, deactivate the virtual environment:

deactivate

That’s it! You’ve set up a basic FastAPI Python application. From here, you can expand your project by adding more routes, defining data models, integrating with databases, and building more complex APIs. FastAPI’s automatic documentation generation and data validation will make it easier to develop robust and well-documented APIs.

Build CRUD Operation using FastAPI

Building a simple API using FastAPI in Python involves defining routes, handling requests, and returning responses. In this example, I’ll guide you through creating a basic API with FastAPI that serves a list of items.

1. Create a Project Directory:

Start by creating a project directory for your FastAPI project:

mkdir fastapi_simple_api
cd fastapi_simple_api

2. Create a Virtual Environment (Optional but recommended):

It’s a good practice to work within a virtual environment to isolate your project’s dependencies. Run the following commands:

python -m venv venv
source venv/bin/activate  # On Windows, use "venv\Scripts\activate"

3. Install FastAPI and Uvicorn:

Install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn

4. Create a FastAPI App:

Create a Python script (e.g., main.py) in your project directory to define your FastAPI application:

from fastapi import FastAPI

app = FastAPI()

# Define a list to store items
items = []

# Define a route to create an item
@app.post("/items/")
def create_item(item: str):
    items.append(item)
    return {"message": "Item added", "item": item}

# Define a route to retrieve all items
@app.get("/items/")
def read_items():
    return {"items": items}

# Define a route to retrieve a specific item by index
@app.get("/items/{item_id}")
def read_item(item_id: int):
    if 0 <= item_id < len(items):
        return {"item": items[item_id]}
    return {"error": "Item not found"}

In this example, we have three routes:

  • POST /items/: Adds an item to the list.
  • GET /items/: Retrieves all items.
  • GET /items/{item_id}: Retrieves a specific item by index.

5. Run the FastAPI App:

Use Uvicorn to run your FastAPI application:

uvicorn main:app --reload

6. Access Your API:

Open a web browser or use a tool like curl or httpie to interact with your API:

  • Create an item:

    curl -X POST "http://localhost:8000/items/" -d "item=apple"
  • Retrieve all items:

    curl "http://localhost:8000/items/"
  • Retrieve a specific item by index (e.g., index 0):

    curl "http://localhost:8000/items/0"

You can add more items, retrieve specific items, and explore other API functionalities as needed.

7. Deactivate the Virtual Environment (Optional):

When you’re done working on your FastAPI project, deactivate the virtual environment:

deactivate

This example demonstrates a simple API using FastAPI. You can expand this API by adding more routes, data models, and features to suit your specific application requirements. FastAPI’s features, including automatic documentation generation and data validation, make it a powerful tool for building robust APIs quickly.

Certainly! Here’s an example of a FastAPI application that performs CRUD (Create, Read, Update, Delete) operations on a list of items. In this example, we’ll create a simple API for managing a list of tasks.

1. Create a Project Directory:

Start by creating a project directory for your FastAPI project:

mkdir fastapi_crud
cd fastapi_crud

2. Create a Virtual Environment (Optional but recommended):

Set up a virtual environment to isolate your project’s dependencies:

python -m venv venv
source venv/bin/activate  # On Windows, use "venv\Scripts\activate"

3. Install FastAPI and Uvicorn:

Install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn

4. Create a FastAPI App:

Create a Python script (e.g., main.py) in your project directory to define your FastAPI application:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI()

# Define a data model for tasks
class Task(BaseModel):
    id: int
    title: str
    description: str
    done: bool

# Initialize a list to store tasks
tasks = []

# Create a new task
@app.post("/tasks/", response_model=Task)
def create_task(task: Task):
    tasks.append(task)
    return task

# Get all tasks
@app.get("/tasks/", response_model=List[Task])
def read_tasks():
    return tasks

# Get a specific task by ID
@app.get("/tasks/{task_id}", response_model=Task)
def read_task(task_id: int):
    if task_id < 0 or task_id >= len(tasks):
        raise HTTPException(status_code=404, detail="Task not found")
    return tasks[task_id]

# Update a task by ID
@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
    if task_id < 0 or task_id >= len(tasks):
        raise HTTPException(status_code=404, detail="Task not found")
    tasks[task_id] = updated_task
    return updated_task

# Delete a task by ID
@app.delete("/tasks/{task_id}", response_model=Task)
def delete_task(task_id: int):
    if task_id < 0 or task_id >= len(tasks):
        raise HTTPException(status_code=404, detail="Task not found")
    deleted_task = tasks.pop(task_id)
    return deleted_task

In this example, we have defined routes for the following CRUD operations:

  • POST /tasks/: Create a new task.
  • GET /tasks/: Retrieve all tasks.
  • GET /tasks/{task_id}: Retrieve a specific task by ID.
  • PUT /tasks/{task_id}: Update a task by ID.
  • DELETE /tasks/{task_id}: Delete a task by ID.

5. Run the FastAPI App:

Use Uvicorn to run your FastAPI application:

uvicorn main:app --reload

6. Access Your API:

You can use a tool like curl or a REST client like Postman to interact with your API. Here are some sample commands:

  • Create a task:

    curl -X POST "http://localhost:8000/tasks/" -d '{"id": 0, "title": "Buy groceries", "description": "Milk, eggs, bread", "done": false}'
  • Retrieve all tasks:

    curl "http://localhost:8000/tasks/"
  • Retrieve a specific task by ID (e.g., ID 0):

    curl "http://localhost:8000/tasks/0"
  • Update a task by ID (e.g., ID 0):

    curl -X PUT "http://localhost:8000/tasks/0" -d '{"id": 0, "title": "Buy groceries", "description": "Milk, eggs, bread", "done": true}'
  • Delete a task by ID (e.g., ID 0):

    curl -X DELETE "http://localhost:8000/tasks/0"

This example demonstrates a basic FastAPI CRUD application for managing tasks. You can expand on this foundation by adding data persistence with databases or more advanced features based on your specific needs.

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Is this page helpful?

Related ArticlesView All