FastAPI Study Diary (5) — Handling Request Headers and Error Responses

contente

In the last couple of articles, we learned how to receive request data in FastAPI, covering parameters in GET requests and the body in POST requests. This time, I want to delve into other aspects, such as how to handle headers.

Retrieving the Header

You can receive information stored in the header using the Header class as shown below.

Surprisingly, the code above automatically searches for the value of User-Agent in the header and assigns it to the variable `user_agent`. Behind the scenes, it converts the key ‘User-Agent’ from the header to all lowercase ‘user-agent’ and then transforms the hyphen into an underscore, following Python’s variable naming conventions, allowing the parameter with the same name `user_agent` to be received by the path operation function.

This conversion applies not only to mandatory header keys like User-Agent but also to custom key-value pairs that you might add from the client-side program. The rule of conversion is the same for these as well.

For instance, if you set up to receive a value into the variable `hello_beautiful_world` from the header, as shown below,

If a value is passed with the key ‘Hello-Beautiful-World’ in the header, this value will be input into `hello_beautiful_world`.

All uppercase letters are converted to lowercase, so I was worried that sending ‘hEllO-beautiful-worlD’ like below might not work the same way, but it was converted without any issues.

Status Code

FastAPI defaults to returning a Status Code of 200. If you wish to change this status code, you can do so by receiving a Response object in the path operation function and modifying the value of status_code as shown below.

(Make sure to import the Response class from the fastapi module beforehand.)

You can also set the default status code for a successful operation as a parameter in the path definition (which seems to be referred to as a decorator in FastAPI).

(Make sure to import the status class from the fastapi module)

The former method is used when you want to dynamically change the status code based on the content of the program’s process, whereas the latter method seems to be used when there is an intention to change the default status code.

Throwing Errors

Finally, I learned how to implement a response for when you want to return an error (an error status code) as follows.

(Make sure to import the HTTPException class from the fastapi module).

When something goes wrong, if you create an object of the HTTPException class and raise it, FastAPI will automatically handle this exception and return a response with the status error code set in the HTTPException object to the client.

As you can see from the actual response above, the string specified in the detail of the HTTPException object appears to be inserted into the response body’s JSON data as the value for the key ‘detail’.

By the way, ‘raise’ in Python is equivalent to ‘throw’ in other programming languages.

Stay tuned for more in this series…

If you have any questions about this article or our blog, feel free to drop me an email at:
[email protected]

By the way, I work at Goldrush Computing, a mobile app and web development company based in Tokyo and Ho Chi Minh City, Vietnam. Our current focus is on creating web services and backend systems that specialize in processing data and documents utilizing the OpenAI API. If you’re on the lookout for an external team to bring your product to life, don’t hesitate to get in touch!

Resumir
The article discusses how to handle headers in FastAPI, showing how to retrieve information stored in the header using the Header class. It explains the conversion process for header keys and how to set status codes for responses. Additionally, it covers how to throw errors using the HTTPException class to return error status codes. The article emphasizes the importance of handling errors and provides examples of how to dynamically change status codes based on program content. It also mentions the option to set default status codes for successful operations. The author invites readers to stay tuned for more articles in the series and encourages reaching out with any questions about the content or their company, Goldrush Computing, which specializes in web development and processing data using the OpenAI API.