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'sExceptionclass, with an API-specific argumentstatus_codethat refers to the type of client error response. -
The Exception classes defined in FastAPI (in addition to the
HTTPExceptiondiscussed earlier, theWebSocketExceptionclass is also available) inherit Python'sException. Hence, it is entirely possible to define a custom exception class, subclassing theException.- FastAPI's exception handler function is decorated by
@app.exception_handler().
- FastAPI's exception handler function is decorated by
-
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
HTTPBasicclass is at the core of FastAPI's BA(Basic Access) authentication support. AN object of the classHTTPBasicCredentialscontains the username and password provided by the client.
- 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
-
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
HTTPXlibrary andPytest