Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastApi - api key as parameter secure enough

Tags:

python

fastapi

i am new in this part of programming and i have few questions. First of all my project. At one side i have a Flutter App and at the other side a MS SQL Server with data. This data i need on my device logically. I read the best way is to use FastAPI, its easy and has a good performance but i am not sure about security. I read something about OAuth2 but it looks to much because just one user will have permission to use the data (the server owner). Is it possible just to use a simple api key as a parameter? Something like this...

from fastapi import FastAPI
from SqlServerRequest import SqlServerRequest

app = FastAPI()


@app.get("/openOrders/{key}")
async def openOrders(key):
    if key == "myverysecurekey":
         return "SQLDATA"
    else
         return "Wrong key"

That way works but i am not sure about the security What would you say?

like image 588
Shajko Avatar asked Jan 26 '26 21:01

Shajko


1 Answers

I have been dealing with the same issue for a while. Instead of using a oauth I needed a simple X-API-Key in the header.

You can do that with the following code

from fastapi import FastAPI, Depends
from fastapi.security import APIKeyHeader
import os

os.environ['API-KEY'] = '1234'. 
# You would use as an environment var in real life

X_API_KEY = APIKeyHeader(name='X-API-Key')


def api_key_auth(x_api_key: str = Depends(X_API_KEY)):
    """ takes the X-API-Key header and validate it with the X-API-Key in the database/environment"""
    if x_api_key != os.environ['API-KEY']:
        raise HTTPException(
            status_code=401,
            detail="Invalid API Key. Check that you are passing a 'X-API-Key' on your header."
        )


app = FastAPI()


@app.get("/do_something", dependencies=[Depends(api_key_auth)])
async def do_something():
    return "API is working OK."
like image 181
Joaquín Menéndez Avatar answered Jan 28 '26 10:01

Joaquín Menéndez