Deployed FastAPI application can't handle API key

54 views Asked by At

This is my FastAPI code:

from fastapi import FastAPI, HTTPException, Security, status
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
from pymongo import MongoClient
import os
import logging

app = FastAPI()

# Database setup
connection_string = os.environ["URI"]
client = MongoClient(connection_string)
db = client['gpt-4-vision-images']
collection = db['images']

# API Key setup

API_KEY = os.environ['API_KEY']
api_keys = [API_KEY]
api_key_header = APIKeyHeader(name="access_token", auto_error=False)


def get_api_key(api_key_header: str = Security(api_key_header), ) -> str:
    if api_key_header in api_keys:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )


logging.info(f"Expected API Key: {API_KEY}")  # Log the expected API key


class ImageData(BaseModel):
    image_data: str
    image_name: str


@app.post('/image/upload')
async def upload_image(image_data: ImageData, api_key: str = Security(get_api_key)):
    collection.insert_one({
        'image_name': image_data.image_name,
        'data': image_data.image_data
    })
    return {
        'url': f'https://gpt-vision-webserver.replit.app/image/{image_data.image_name}?token={api_key}'
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

The purpose of the code is to have an endpoint to upload images to, then after that is done. Return a response in the form of a URL to an image

I have deployed this application on Replit for ease and testing purposes.

But the issue here is this:

Screenshot of the swagger UI response

Swagger UI

Replit screenshot

For some reason even though I have typing in the correct token, the API still responds back with invalid key. I have no idea what is going on, because the token authentication code is copy pasted from another project of mine where I use the exact same method for API key auth.

There is something wrong with this code, what it is, I have no idea.

Note: I don't want to use another auth method, it needs to be through API keys (Also, yeah. I will change the API key after this.)

Link to my replit code: https://replit.com/@developeradmin1/Python

1

There are 1 answers

0
Marcus Peterson On

I fixed it, I literally just had to enable certain network access in the mongodb atlas account. Also, there was never an issue with the API key functionalites, I just had to delete the deployment and redo the whole deployment process (Because I changed the api key so many times). Then, another came, some internal server error stuff. I solved using the above mentioned solution.

This was my TED talk, have a nice day.