HTSagara / PRJ-566-ZAA-Team-1

3 stars 0 forks source link

API Upload Book #118

Closed JonPeeAir closed 2 weeks ago

JonPeeAir commented 1 month ago

The implementation for this will be pretty similar to Fragments in CCP

this task needs:

Before implementing endpoint, we need to create Book class

Implementing POST /book

from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
from pydantic import BaseModel
import os

app = FastAPI()

# Define the folder to store uploaded files
UPLOAD_FOLDER = './uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# Allowed file types
ALLOWED_EXTENSIONS = {'pdf', 'epub'}

class Metadata(BaseModel):
    title: str
    author: str
    description: str

@app.post("/upload")
async def upload_file(file: UploadFile = File(...), metadata: Metadata):
    # Check if the uploaded file has an allowed extension
    if not file.filename.endswith(tuple(ALLOWED_EXTENSIONS)):
        return JSONResponse(content={'error': 'File type not allowed. Only PDF or EPUB is allowed.'}, status_code=400)

    # Save the file
    file_path = os.path.join(UPLOAD_FOLDER, file.filename)
    with open(file_path, "wb") as f:
        content = await file.read()
        f.write(content)

    # Return response with file path and metadata
    return {
        'message': 'File successfully uploaded',
        'file_path': file_path,
        'metadata': metadata.dict()  # Convert Pydantic model to dict
    }

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

How to call api using curl

curl -X POST "http://127.0.0.1:8000/upload" \
     -F "file=@path_to_your_file.epub" \
     -F 'metadata={"title": "Your Book Title", "author": "Author Name", "description": "A brief description of the book."}'
HTSagara commented 2 weeks ago

Updates

We are able to save the file in the S3 and the metadata in the MongoDB.

However it throws an 500 error that we need to dig a little deeper. Image

Also, it is not saving the last modified and the size. It might be some problem with the Book class that I will investigate.

Image

Regarding the metadata. It seems solid.

Image