Web layer

The web layer of FastAPI, which manages HTTP requests and responses, is the framework’s vital component. Imagine it as the glue that binds your application together. 

The Web layer, which is the top layer of our FastAPI application, is the subject of this blog. It manages the web interface and interfaces with the Service and Data layers. It is also referred to as the Interface or Router layer. This layer’s structure will be examined, along with issues related to what should be in each layer, how those layers interact, and how to maintain scalability and flexibility.

Navigating the FastAPI Framework

Selecting the correct framework can be crucial in the always changing world of web development. With its focus on speed, ease of use, and type safety, FastAPI has become a potent tool for creating contemporary Python APIs. In the framework of FastAPI, this pause examines three different development methodologies:

  • Top-Down Development:
      • Top-down development is similar to outlining a masterpiece before adding the finer details. It starts with the big picture and works its way down to the details. This strategy is applied to FastAPI, where the general architecture, endpoints, and high-level structure of the API are defined before the implementation details are worked out. This allows for a clear and strategic vision of the application’s functionality from the outset.
  • Bottom-Up Development:
      • On the other hand, Bottom-Up development starts with the fundamental components and works its way up. Developers employing this approach in FastAPI may start by creating individual components, such as models, database schemas, and utility functions, and progressively assembling them into a cohesive API. To encourage scalability and maintainability, this approach frequently places a strong emphasis on the development of modular and reusable building blocks.
  • Middle-Out Development:
    • The goal of middle-out development is to strike a balance between bottom-up and top-down methods, supporting an incremental and iterative development process. Developers who use this method begin with a core set of features and gradually expand outward, addressing both high-level architecture and low-level details at the same time. This approach is well-suited for projects where changing requirements and the need for quick feedback drive the development process.

RESTful API Design

Before delving into the code, we discuss RESTful API design principles. Understanding how HTTP commands and data interact between clients and servers is crucial. RESTful designs involve resources, unique identifiers (IDs), URLs, and verbs/actions (GET, POST, PUT, PATCH, DELETE). We also touch on path parameters, query parameters, and recommended naming conventions for resources.

File and Directory Site Layout

A well-organized directory structure is key to maintaining clarity and simplicity in our project. We create directories for different layers—src, web, service, data, model, and fake. Each directory contains Python modules and an __init__.py file to establish the package.

The First Website Code

We started building our website by creating a basic FastAPI application in main.py. We introduce an endpoint that responds with a simple string. Running the application using Uvicorn, we explore how changes trigger automatic restarts.

Example

from fastapi import FastAPI 

app = FastAPI() 

@app.get(“/”) 

def top(): 

return “top here” 

if __name__ == “__main__”: 

import uvicorn 

uvicorn.run(“main:app”, reload=True)

Multiple Routers

To handle different types of resources, we use API routers. We create a separate router for explorers under the web directory. The main application includes this router, allowing us to manage URLs starting with /explorer. This modular approach keeps our code organized as the project grows.

Define Data Models

We define Pydantic data models for explorers and creatures in the model directory. These models represent the structure of the data we’ll be working with.

Stub and Fake Data

In the fake directory, we create modules for explorer and creature data. These modules provide stub and fake data that will be replaced with real data in later chapters. We implement functions to get all data, get one item, create, modify, replace, and delete.

Create Common Functions Through the Stack

We identify common functions that a web service typically requires—retrieve all, retrieve one, create, replace, modify, and delete. While these functions are initially implemented in the Web layer with fake data, they will eventually be moved down to the Service and Data layers.

Test!

We manually test our web service endpoints using HTTPie. We perform tests for retrieving all data, retrieving one item, replacing, modifying, and deleting. These tests help ensure that our endpoints are functioning as expected.

Using the FastAPI Automated Test Forms

FastAPI provides automated test forms at the /docs and /redocs endpoints. We explore the /docs pages, executing tests for each endpoint and reviewing the generated documentation.

Talking to the Service and Data Layers

To maintain a clean separation of concerns, we introduce the concept of a Service layer. This layer acts as an intermediary between the Web and Data layers, handling data requests and responses. It also serves as a boundary for any business logic.

Pagination and Sorting

We discuss how to implement pagination and sorting for endpoints that return multiple items. We look at how query parameters can be used to specify desired behavior, allowing users to request a subset of data in a specific order.

 

Visited 1 times, 1 visit(s) today