Skip to content

Chapter 9

Chapter 9

  • Exception Handling
  • The HTTP protocol has an elaborate system of including an appropriate status code in the server's response. Whenever the FastAPI operation function encounters a runtime error, it raises HTTPException. It inherits Python's Exception class, with an API-specific argument status_code that refers to the type of client error response.
  • The Exception classes defined in FastAPI (in addition to the HTTPException discussed earlier, the WebSocketException class is also available) inherit Python's Exception. Hence, it is entirely possible to define a custom exception class, subclassing the Exception.

    • FastAPI's exception handler function is decorated by @app.exception_handler().
  • Security

  • Basic Access Authentication
    • A very basic authentication mechanism is provided by the HTTP protocol itself. First included in the HTTP 1.0 specification, it has since been superseded by RFC 617 in 2015. The implementation of this authentication scheme requires the browser to send the username and passowrd when it sends the request. Base64 encoding is used to formulate the credentials. The request is packed with a header in the format Authorization: Basic .
    • The HTTPBasic class is at the core of FastAPI's BA(Basic Access) authentication support. AN object of the class HTTPBasicCredentials contains the username and password provided by the client.
  • OAuth

    • FastAPI has an out-of-the-box support for OAuth2 security standard specification. OAUth stands for Open Authorization. OAuth version 2.0 provides simple authorization flows for web applications, desktop and mobile applications.
    • One of the important features of OAuth is that it enables sharing information with another service without exposing your password. OAuth uses "access tokens". An access token is a random string of alphanumeric characters. A bearer token is the most commonly used. Once the OAuth client has the possession of the bearer token, it is able to make request for the associated resources with the server.
    • In the OAuth specification, the term grand type refers to the mechanism by which the application gets the acces token. A grant type is also sometimes referred as a flow. THere are various grant types:
    • authorization code
    • client credentials
    • implicit
    • password
      • we can use pydantic and sqlalchemy to model database
  • Testing

  • Fastapi's testing functionality is based on HTTPX library and Pytest