Home

Awesome

FastAPI simple security

codecov Python Tests Linting

Ruff Code style: black pre-commit enabled Conventional Commits

API key based security package for FastAPI, focused on simplicity of use:

This module cannot be used for any kind of distributed deployment. It's goal is to help have some basic security features for simple one-server API deployments, mostly during development.

Installation

pip install fastapi_simple_security

Usage

Creating an application

from fastapi_simple_security import api_key_router, api_key_security
from fastapi import Depends, FastAPI

app = FastAPI()

app.include_router(api_key_router, prefix="/auth", tags=["_auth"])

@app.get("/secure", dependencies=[Depends(api_key_security)])
async def secure_endpoint():
    return {"message": "This is a secure endpoint"}

Resulting app is:

app

API key creation through docs

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

secret

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.

secret_header

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

api key

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

secure endpoint

API key creation in python

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_SIMPLE_SECURITY_HIDE_DOCS.

Configuration

Environment variables:

Contributing

Setting up python environment

poetry install
poetry shell

Setting up pre-commit hooks

pre-commit install

Running tests

pytest

Running the dev environment

The attached docker image runs a test app on localhost:8080 with secret key TEST_SECRET. Run it with:

docker-compose build && docker-compose up

Needed contributions