api key authentication using a query parameter this defines the name of the query parameter that should be provided in the request with the api key and integrates that into the openapi documentation it extracts the key value sent in the query parameter automatically and provides it as the dependency result but it doesn t define how to send that api key to the client usage create an instance object and use that object as the dependency in depends the dependency result will be a string containing the key value example python from fastapi import depends fastapi from fastapi security import apikeyquery app fastapi queryscheme apikeyquerynameapikey app getitems async def readitemsapikey str dependsqueryscheme return apikey apikey security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs by default if the query parameter is not provided apikeyquery will automatically cancel the request and sebd the client an error if autoerror is set to false when the query parameter is not available instead of erroring out the dependency result will be none this is useful when you want to have optional authentication it is also useful when you want to have authentication that can be provided in one of multiple optional ways for example in a query parameter or in an http bearer token api key authentication using a header this defines the name of the header that should be provided in the request with the api key and integrates that into the openapi documentation it extracts the key value sent in the header automatically and provides it as the dependency result but it doesn t define how to send that key to the client usage create an instance object and use that object as the dependency in depends the dependency result will be a string containing the key value example python from fastapi import depends fastapi from fastapi security import apikeyheader app fastapi headerscheme apikeyheadernamexkey app getitems async def readitemskey str dependsheaderscheme return key key security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs by default if the header is not provided apikeyheader will automatically cancel the request and send the client an error if autoerror is set to false when the header is not available instead of erroring out the dependency result will be none this is useful when you want to have optional authentication it is also useful when you want to have authentication that can be provided in one of multiple optional ways for example in a header or in an http bearer token api key authentication using a cookie this defines the name of the cookie that should be provided in the request with the api key and integrates that into the openapi documentation it extracts the key value sent in the cookie automatically and provides it as the dependency result but it doesn t define how to set that cookie usage create an instance object and use that object as the dependency in depends the dependency result will be a string containing the key value example python from fastapi import depends fastapi from fastapi security import apikeycookie app fastapi cookiescheme apikeycookienamesession app getitems async def readitemssession str dependscookiescheme return session session security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs by default if the cookie is not provided apikeycookie will automatically cancel the request and send the client an error if autoerror is set to false when the cookie is not available instead of erroring out the dependency result will be none this is useful when you want to have optional authentication it is also useful when you want to have authentication that can be provided in one of multiple optional ways for example in a cookie or in an http bearer token type ignore attr defined api key authentication using a query parameter this defines the name of the query parameter that should be provided in the request with the api key and integrates that into the openapi documentation it extracts the key value sent in the query parameter automatically and provides it as the dependency result but it doesn t define how to send that api key to the client usage create an instance object and use that object as the dependency in depends the dependency result will be a string containing the key value example python from fastapi import depends fastapi from fastapi security import apikeyquery app fastapi query_scheme apikeyquery name api_key app get items async def read_items api_key str depends query_scheme return api_key api_key security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs by default if the query parameter is not provided apikeyquery will automatically cancel the request and sebd the client an error if auto_error is set to false when the query parameter is not available instead of erroring out the dependency result will be none this is useful when you want to have optional authentication it is also useful when you want to have authentication that can be provided in one of multiple optional ways for example in a query parameter or in an http bearer token type ignore arg type api key authentication using a header this defines the name of the header that should be provided in the request with the api key and integrates that into the openapi documentation it extracts the key value sent in the header automatically and provides it as the dependency result but it doesn t define how to send that key to the client usage create an instance object and use that object as the dependency in depends the dependency result will be a string containing the key value example python from fastapi import depends fastapi from fastapi security import apikeyheader app fastapi header_scheme apikeyheader name x key app get items async def read_items key str depends header_scheme return key key security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs by default if the header is not provided apikeyheader will automatically cancel the request and send the client an error if auto_error is set to false when the header is not available instead of erroring out the dependency result will be none this is useful when you want to have optional authentication it is also useful when you want to have authentication that can be provided in one of multiple optional ways for example in a header or in an http bearer token type ignore arg type api key authentication using a cookie this defines the name of the cookie that should be provided in the request with the api key and integrates that into the openapi documentation it extracts the key value sent in the cookie automatically and provides it as the dependency result but it doesn t define how to set that cookie usage create an instance object and use that object as the dependency in depends the dependency result will be a string containing the key value example python from fastapi import depends fastapi from fastapi security import apikeycookie app fastapi cookie_scheme apikeycookie name session app get items async def read_items session str depends cookie_scheme return session session security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs by default if the cookie is not provided apikeycookie will automatically cancel the request and send the client an error if auto_error is set to false when the cookie is not available instead of erroring out the dependency result will be none this is useful when you want to have optional authentication it is also useful when you want to have authentication that can be provided in one of multiple optional ways for example in a cookie or in an http bearer token type ignore arg type
from typing import Optional

from fastapi.openapi.models import APIKey, APIKeyIn
from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.status import HTTP_403_FORBIDDEN
from typing_extensions import Annotated, Doc  


class APIKeyBase(SecurityBase):
    pass


class APIKeyQuery(APIKeyBase):
    

    def __init__(
        self,
        *,
        name: Annotated[
            str,
            Doc("Query parameter name."),
        ],
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model: APIKey = APIKey(
            **{"in": APIKeyIn.query},  
            name=name,
            description=description,
        )
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(self, request: Request) -> Optional[str]:
        api_key = request.query_params.get(self.model.name)
        if not api_key:
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        return api_key


class APIKeyHeader(APIKeyBase):
    

    def __init__(
        self,
        *,
        name: Annotated[str, Doc("Header name.")],
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model: APIKey = APIKey(
            **{"in": APIKeyIn.header},  
            name=name,
            description=description,
        )
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(self, request: Request) -> Optional[str]:
        api_key = request.headers.get(self.model.name)
        if not api_key:
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        return api_key


class APIKeyCookie(APIKeyBase):
    

    def __init__(
        self,
        *,
        name: Annotated[str, Doc("Cookie name.")],
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model: APIKey = APIKey(
            **{"in": APIKeyIn.cookie},  
            name=name,
            description=description,
        )
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(self, request: Request) -> Optional[str]:
        api_key = request.cookies.get(self.model.name)
        if not api_key:
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        return api_key