Skip to content

Chapter 7

Chapter 7

  • APIRouter: the use of APIRouter allows you to group your routes into different file structures so that they are easily manageable. All the routs in a bigger application are clubbed into small units of APIRouters.
  • First, declare an object of the APIRouter class (it is in the fastapi module) instead of the FastAPI class as we normally do. Set the prefix attribute to "/books" and define a tag that appears in the documentation.
  • As far as the REST operations on the book resource are concerned, books - the APIRouter object itself is the application object. Hence, the path operation decorators are @books.get(), @books.post()

  • Sub-Application

  • in addition to use APIRouter, we can also mount sub-application. Assuming that books and albums are two FastAPI() application, we can create a root store Application that mounts both of them.

  • Dependency

  • sometimes, the path operation function depends upon certain other factors. These are called the dependencies of the operation. We need to inject these dependencies into the function's context. FastAPI has Depends() function whose return value is injected as the dependency parameter

  • MiddleWare

  • A middleware is a function that intercepts every HTTP request before being processed by the corresponding path operation function. If required, the function can use the request to perform some process. The request object is then handed over to the path operation function. The middleware can also modify the response before it is rendered.
  • The middleware function is decorated by @app.middleware("http"). It receives two arguments. The first one is the client request, the second is a call_next function.
    • the call_next function passes the request to the intended path operation function. Its response may be manipulated by the middleware before returning to the client.
  • HTTPSRedirectMiddleWare: enforces that all incoming requests must either be https or wss. Any incoming requests to http or ws will be redirected to the secure scheme instead.
  • TrustedHostMiddleWare: Ensures that all incoming requests have a correctly set Host header to prevent HTTP Host Header Attack.
  • GZipMiddleware: Handles GZip responses for any request that includes "gzip" in the Accept-Encoding header.

  • CORS: Cross-origin resource sharing

  • a front-end application running on www.xyz.com will try to communicate a back-end application running on www.abc.com. Here the front-end and back-end applications are on different origins. Browsers normally restrict such cross-origin requests.
  • FastAPI's CORSMiddleware makes it possible to accept URL requests from certain domains whitelisted in the application.
  • To configure the FastAPI app for CORS, import CORSMiddleware and specify the allowed origins.
  • [???]TODO:
  • persons_cred endpoint, which checks the api_key before showing the content, is not working yet
  • CORS is not really working yet