[Python] How to send multiple files with Python requests to FastAPI server?

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following endpoint in my FastAPI server:

    @app.post("/submit")
    async def submit(file1: List[UploadFile] = File(...), file2: List[UploadFile] = File(...), file3: List[UploadFile] = File(...)):
    # do something
    return 'hello'


    It works as expected if I use Swagger UI. However, I cannot figure out how to send a POST request to this endpoint using Python requests module. Here is what I've tried:

    import requests

    headers = {
    'accept': 'application/json',
    'Content-Type': 'multipart/form-data',
    }

    files = [
    ('file1', open('file1.zip', 'rb')),
    ('file2', open('file2.txt', 'rb')),
    ('file3', open('file3.rar', 'rb')),
    ]

    response = requests.post('http://localhost:8000/submit', headers=headers, files=files)

    print(response.text)


    But I am getting an error:

    {"detail":"There was an error parsing the body"}

    Continue reading...

Compartilhe esta Página