1- Python-based FastAPI web framework APIs

Posted by


FastAPI is a modern web framework for building APIs with Python. It is built on top of Starlette for the web parts and Pydantic for the data parts. FastAPI is known for its speed and performance, providing an easy-to-use interface for developers to create robust and efficient APIs.

In this tutorial, we will walk through the process of creating a simple API using FastAPI, including setting up a project, defining routes, handling request and response data, and testing the API.

Step 1: Setting up a FastAPI project
First, you will need to install FastAPI and Uvicorn, which is a lightweight ASGI server for running FastAPI applications. You can install them using pip:

pip install fastapi uvicorn

Next, create a new Python file for your project, for example, app.py. In this file, you will define your FastAPI application and routes. Here is a basic example of a FastAPI application:

from fastapi import FastAPI

app = FastAPI()

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

Step 2: Defining routes
In FastAPI, routes are defined using the @app.get(), @app.post(), @app.put(), and @app.delete() decorators for the HTTP methods GET, POST, PUT, and DELETE respectively. You can also specify path parameters in the route definition by using curly braces {}. Here is an example of defining a route with a path parameter:

@app.get('/hello/{name}')
def read_item(name: str):
    return {'Hello': name}

Step 3: Handling request data
FastAPI automatically handles request data and performs input validation using Pydantic models. You can define Pydantic models as function parameters to validate incoming JSON data. Here is an example of defining a Pydantic model for request data:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str

@app.post('/items/')
def create_item(item: Item):
    return item

Step 4: Handling response data
You can also define response models using Pydantic classes to standardize the structure of your API responses. Simply specify the response model as a function return type using the Response class. Here is an example of defining a response model:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str

class ItemResponse(BaseModel):
    item: Item

@app.get('/items/{id}', response_model=ItemResponse)
def read_item(id: int):
    return {'item_id': id, 'name': 'Item Name', 'description': 'Item Description'}

Step 5: Running the FastAPI application
To run your FastAPI application, use the Uvicorn server by running the following command:

uvicorn app:app --reload

This will start the ASGI server on http://localhost:8000. You can now access your API endpoints in a web browser or using a tool like curl or Postman.

Step 6: Testing the API
You can test your FastAPI application by sending requests to your API endpoints. Here is an example of sending a GET request to http://localhost:8000/hello/John using curl:

curl http://localhost:8000/hello/John

You should see the response {"Hello": "John"} in the terminal.

In conclusion, FastAPI is a powerful and intuitive web framework for building APIs with Python. By following this tutorial, you should now have a good understanding of how to create APIs using FastAPI and leverage its features for handling request and response data. Happy coding!