[Python] FastAPI - How to pass a dictionary/JSON data in HTTP multipart request?

Discussão em 'Python' iniciado por Stack, Novembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a POST request:

    import requests


    files = {'template': open('template.xlsx', 'rb')}
    payload = {
    'context': {
    'OUT': 'csv',
    'SHORT': 'short'
    },
    'filename': 'file.xlsx',
    'content_type': 'application/excel'
    }

    r = requests.post('http://localhost:8000/render', files=files, data=payload)


    to a FastAPI server:

    from fastapi import FastAPI, UploadFile, Form
    from pydantic import Json

    app = FastAPI()


    @app.post('/render')
    def render(template: UploadFile, context: Json = Form(), filename: str = Form(...), content_type: str = Form(...)):
    # processing
    return "ok"


    but I get this error (422 status code):

    {"detail":[{"loc":["body","context"],"msg":"Invalid JSON","type":"value_error.json"}]}


    As you can see, I'm trying to pass both a file and request body in the same request. I guess I could fix this if converted payload['context'] into JSON. But I'd like to fix this on server side.

    How can I fix the error? Maybe convert some before params passed into view or something like this?

    Continue reading...

Compartilhe esta Página