Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

FastAPI upload file using path into S3 with bucket name and path as query parameters

$
0
0

I'm building a FastAPI endpoint to upload a file into a S3 bucket with bucket name and path as input parameters. When I don't specify the file path, the file is getting uploaded successfully. But when i mention the path, the file is not getting uploaded. Please help me to fix this issue.

#upload.py    from fastapi import FastAPI, File, UploadFile, HTTPException, Depends    from pydantic import BaseModel    from typing import Optional    from botocore.exceptions import NoCredentialsError, PartialCredentialsError, ClientError    import boto3    import uvicorn    app = FastAPI()    AWS_ACCESS_KEY = "XXX"    AWS_SECRET_KEY = "YYY"    AWS_REGION_NAME = "ap-northeast-1"    # Pydantic model for the request body    class S3UploadRequest(BaseModel):        bucket_name: str        file_path: Optional[str] = None  # Make file_path optional    @app.post("/upload/")    async def upload_file_to_s3(            s3_request: S3UploadRequest = Depends(),            file: UploadFile = File(...)    ):"""        Upload a file to an S3 bucket.        :param s3_request: S3UploadRequest. Contains the bucket name and file path.        :param file: UploadFile. The file to upload."""        try:            s3_client = boto3.client('s3',                aws_access_key_id=AWS_ACCESS_KEY,                aws_secret_access_key=AWS_SECRET_KEY,                region_name=AWS_REGION_NAME            )            # Set default file path if not provided            if s3_request.file_path is None:                s3_request.file_path = file.filename            # Upload file to S3            s3_client.upload_fileobj(file.file, s3_request.bucket_name, s3_request.file_path)            return {"message": f"File '{file.filename}' uploaded successfully to bucket '{s3_request.bucket_name}' at '{s3_request.file_path}'"}        except NoCredentialsError:            raise HTTPException(status_code=403, detail="AWS credentials not found.")        except PartialCredentialsError:            raise HTTPException(status_code=403, detail="Incomplete AWS credentials.")        except ClientError as e:            raise HTTPException(status_code=500, detail=str(e))    if __name__ == "__main__":        uvicorn.run(app='upload:app', reload=True)

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>