FastAPI — authentication revisited: Enabling API key authentication
Intro
So, in my last article, I wrote about adding Basic Authentication to the example tutorial app, which is based on the excellent work of Sebastián Ramírez of the FastAPI framework.
Now I am exploring a new type of authentication, API key-based authentication. This is authentication in the form of an arbitrary string with an arbitrary length, which gives access to an API.
For the API it would be great if it supports API key validation by:
- Checking for a query parameter containing the API key
- Checking for a header containing the API key
- Checking for a cookie containing the API key
The reason behind this order is that to me, it is great if you can override an API key by supplying a query parameter to the API call. If you want to call the endpoint multiple times, but do not want to use the API key as a query parameter, you can put the API key in the header and make calls with this header. Finally, if you want to explore the API as a user, a cookie is a great way to persist the API key and use it for subsequent calls.
We will create a very simple API, just to show how this can be built.