[Python] How to pass a List of strings as FormData to FastAPI using JavaScript Fetch API?

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have this NextJs code:

    // Create FormData to send files, URLs, and username to the API
    const formData = new FormData();

    if (files && files.length > 0) {
    files.forEach((file) => {
    formData.append('files', file);
    });
    } else {
    const emptyBlob = new Blob([''], { type: 'application/pdf' });
    formData.append('files', emptyBlob, 'empty.pdf');
    }

    formData.append('urls', JSON.stringify(validUrls ?? ["https://example.com"])); // always append something

    if (user) {
    formData.append('username', user.sub);
    }
    try {
    console.log("FormData keys:");
    for (const pair of formData.entries()) {
    console.log(pair[0], pair[1]);
    }

    const response = await fetch('/api/add_document_to_knowledge_base', {
    method: 'POST',
    body: formData,
    });



    And this is the FastAPI backend:

    @app.post("/add_document_to_knowledge_base/", response_model=APIResponse)
    async def add_documents_to_knowledge_base(
    request: Request,
    files: List[UploadFile] = File(...),
    urls: Optional[str] = Form(None),
    username: Optional[str] = Form(None),
    token: str = Depends(verify_token),
    ):
    print("=== RAW REQUEST DUMP ===")
    form = await request.form()
    for key, value in form.items():
    print(f"{key}: {value}")
    """
    Upload and process multiple documents. Each is parsed, chunked, and added to the vector DB.
    """
    try:
    print("USER", username)
    print("URLs", urls)
    print("FILES", files)

    parsed_urls: List[str] = json.loads(urls) if urls else []
    print("Parsed URLs", parsed_urls)


    When I send the request from the frontend, I can see that it logs on the console correctly and there are URLs in the array:

    urlsss ["https://mail.google.com/mail/u/0/#inbox"]
    VM2480 KBPageFileProcessor.jsx:238 username auth0|68156591d0d1ef36e79e


    But, at the backend, the list urls prints None, even though the files and username are received correctly.

    You can see that urls are not even there in the request body:

    === RAW REQUEST DUMP ===
    files: <starlette.datastructures.UploadFile object at 0x16be31280>
    username: auth0|68156591d0d1ef36e79e7961
    USER auth0|68156591d0d1ef36e79e7961
    URLs None
    FILES [<starlette.datastructures.UploadFile object at 0x16be31280>]
    Parsed URLs []
    INFO:httpx:HTTP Request: POST


    Any idea why this is happening? Or any alternatives that will fix this issue?

    Continue reading...

Compartilhe esta Página