What is the role of the service layer in the FastAPI architecture described in this chapter?
The service layer acts as an intermediary between the web layer and the data layer. Whenever a web-layer function needs data managed by the data layer, it calls the service layer instead of talking to the data layer directly, so the two layers stay separate and independently testable. It also owns specific business logic, such as interactions between resources, though in this chapter it initially mostly passes requests and responses through.
In the architecture described, the service layer sits between the web layer and the data layer. Its main job is to receive requests from the web layer, ask the data layer for the needed data, and return the responses back to the web layer. This keeps the web layer focused only on web concerns and the data layer focused only on external data stores and services. The source calls the service layer the heart of the website, taking requests from multiple sources, accessing data, and returning responses. It is also where specific business logic belongs, such as interactions between resources, so the web and data layers do not need to know how that work is done. The initial service modules shown are mostly pass-through functions that delegate to fake data modules, but this extra structure is intentional because it makes later changes easier and keeps the layers protected from each other's details.
Key points
- The service layer is an intermediary that web-layer functions use when data managed by the data layer is needed.
- It keeps web details and data details separate, making the layers safer and independently testable.
- The service layer takes requests from multiple sources, accesses the site's data, and returns responses.
- It holds specific business logic such as interactions between resources, hidden from the web and data layers.
- In this chapter, the service functions mostly pass requests and responses through to the fake data layer, but the added structure is meant to simplify future changes.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.