API key based Authentication package for FastAPI, focused on simplicity and ease of use:
sqlite or postgres database backend, working with both header and query parametersexample.env file to show how to use environment variables.README.md to reflect changes.mysql database backend.pip install fastapi_auth2
from fastapi import Depends, FastAPI
from fastapi_auth import api_key_router, api_key_security
app = FastAPI(
description="FastAPI Auth is a package that provides authentication based API security with FastAPI and Postgres Database, SQLite Database or MongoDB Database",
title="FastAPI Auth Example",
version=1.0,
)
app.include_router(api_key_router, prefix="/auth", tags=["_auth"])
@app.get("/unsecure")
async def unsecure_endpoint():
return {"message": "This is a unsecure endpoint"}
@app.get("/secure", dependencies=[Depends(api_key_security)])
async def secure_endpoint():
return {"message": "This is a secure endpoint"}Resulting app is:

Start your API and check the logs for the automatically generated secret key if you did not provide one through environment variables.

Go to /docs on your API and inform this secret key in the Authorize/Secret header box.
All the administrator endpoints only support header security to make sure the secret key is not inadvertently
shared when sharing an URL.

Then, you can use /auth/new to generate a new API key.

And finally, you can use this API key to access the secure endpoint.

You can of course automate API key acquisition through python with requests and directly querying the endpoints.
If you do so, you can hide the endpoints from your API documentation with the environment variable
FASTAPI_AUTH_HIDE_DOCS.
Environment variables:
FASTAPI_AUTH_SECRET: Secret administrator key
FASTAPI_AUTH_HIDE_DOCS: Whether or not to hide the API key related endpoints from the documentation
FASTAPI_AUTH_DB_LOCATION: Location of the local sqlite database file
sqlite.db in the running directory by defaultFASTAPI_AUTH_AUTOMATIC_EXPIRATION: Duration, in days, until an API key is deemed expired
DATABASE_MODE: If set to postgres, the package will use a postgres database instead of sqlite
URI: Location of the postgres database
postgresql://postgres:postgres@localhost:5432/postgres by defaultDEV_MODE is set to FalseSee CONTIBUTING.md for more information.
poetry install
poetry shellpre-commit installpytestThe attached docker image runs a test app on localhost:8080 with secret key TEST_SECRET. Run it with:
docker-compose build && docker-compose up