FastAPI, a lightning-fast Python web framework!

FastAPI, a lightning-fast Python web framework! Hey, folks! Today let's talk about an incredibly cool Python web framework—FastAPI. Just by the name, you can tell that this guy is all about "speed"! In this fast-paced era, who wouldn't want their website to be as fast as lightning? Let's see how FastAPI can help us achieve this effortlessly!



Getting Started with FastAPI FastAPI, in simple terms, is a modern, fast (high-performance) web framework for building APIs. It's based on Python 3.7+ type hints, which means you can use Python's type system to define your API parameters and return types, and FastAPI will automatically generate API documentation for you (such as Swagger UI and ReDoc). Does it sound impressive? Hold on, let's slowly unveil its mysteries.

Installing FastAPI First, you need to install FastAPI in your Python environment. You can use pip for the installation:

pip install fastapi uvicorn

Here, we also install uvicorn, which is an ASGI server used to run our FastAPI application.

Creating a Simple FastAPI Application Next, let's create a simple FastAPI application. Imagine we want to create an API that, when accessing the root path /, it returns a "Hello, World!" text.

from fastapi import FastAPI

app = FastAPI()

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

In the code above, we did a few things:

  1. Import the FastAPI class.

  2. Create an instance of FastAPI, named app.

  3. Use the @app.get("/") decorator to define a path operation function. When an HTTP GET request is sent to the root path /, this function will be called.

  4. Define an asynchronous function read_root that returns a dictionary containing the "Hello, World!" message.

Running the Application With the code above, it's time to run the application. In the terminal or command line, run the following command:

uvicorn main:app --reload

Assuming your Python file is named main.py. The --reload option means that when your code changes, the server will automatically restart, which is very convenient for development.

Open your browser and visit http://127.0.0.1:8000, you should see the following JSON response:

{
    "message""Hello, World!"
}

Defining Path Operation Functions FastAPI supports not only GET requests but also POST, PUT, DELETE, and other HTTP methods. Next, let's see how to define these path operation functions.

Example: POST Request Suppose we want to create an API that receives item information in JSON format and returns its confirmation message.

from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

@app.post("/items/")
async def create_item(item: Item):
    return {"item_name": item.name, "item_price": item.price}

In this example, we did a few things:

  1. Use the BaseModel class from the pydantic library to define a data model Item. This model includes fields for item's name, description (optional), price, and tax (optional).

  2. Use the @app.post("/items/") decorator to define a path operation function for POST requests.

  3. Define an asynchronous function create_item that receives an Item type parameter item and returns a dictionary containing item_name and item_price.

Now, you can use tools (like Postman or curl) to send a POST request to http://127.0.0.1:8000/items/ with JSON item information. For example:

{
    "name""Foo",
    "price"100.0
}

You should receive the following response:

{
    "item_name""Foo",
    "item_price"100.0
}

Friendly Reminder: FastAPI will automatically parse the JSON data in the request body and convert it into an Item type object.

Query Parameters and Path Parameters In addition to JSON data, FastAPI also supports query parameters and path parameters.

Query Parameters Query parameters are passed through key-value pairs following the ? in the URL. For example, ?name=foo&age=30.

from typing import List

@app.get("/users/")
async def read_users(q: str = None, limit: int = 10):
    items = [{"name""Foo"}, {"name""Bar"}]  # Example data
    if q:
        items = [item for item in items if q.lower() in item["name"].lower()]
    return items[:limit]

In this example, q is an optional query parameter for searching user names; limit is a default query parameter for limiting the number of returned results.

Path Parameters Path parameters are passed through variables in the URL path. For example, /items/{item_id}.

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

In this example, item_id is a path parameter that must be an integer; q is an optional query parameter.

Dependency Injection and Middleware FastAPI also supports dependency injection and middleware, which makes it easier for you to implement complex logic, such as authentication and logging.

Dependency Injection Dependency injection allows you to define logic that can be reused in path operation functions or other dependencies.

from fastapi import Depends, HTTPException
from typing import Optional

fake_users_db = {"foo": {"username""foo""email""[email protected]"}}

async def get_current_user(username: str = Depends(lambda: "foo")):
    user = fake_users_db.get(username)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@app.get("/users/me/")
async def read_users_me(current_user: dict = Depends(get_current_user)):
    return current_user

In this example, get_current_user is a dependency function that returns information about the current user. In the read_users_me path operation function, we use Depends to inject this dependency.

Middleware Middleware allows you to execute some logic before the request reaches the path operation function or after the response is sent back to the client.

@app.middleware("http")
async def add_process_time_header(request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

In this example, we define a middleware that records the processing time of the request and adds it to the response headers.

Summary Today, we learned about FastAPI, this lightning-fast Python web framework. From installation to creating simple applications, defining path operation functions, query parameters and path parameters, as well as dependency injection and middleware, FastAPI provides us with very convenient and powerful features. Most importantly, FastAPI also supports automatic generation of API documentation, which is a boon for API developers!

I hope this article can give you a preliminary understanding of FastAPI and inspire your interest in further learning and exploration. Remember to practice hands-on, as that is the only way to truly master this framework!

发表评论

后一页 前一页