[Python] how to send/receive binary data to an web application in python?

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

  1. Stack

    Stack Membro Participativo

    I am learning web development, i have some experience in python scripting. this time, I wanted to create an api in python , so review fast api docs. i have following set up (example contrived for the purpose of this post) . based on the examples in fast api site, i created following python code, which has two methods. also , i have defined classes that represent the data i want to read in these methods . my understading is pydantic library validates data. so for testing , i used curl command as such, which works. pydantic maps the data {'name': 'foo'} i sent in curl command , to the class i have define Item. is there any documentation on how does it maps data?for my next method , i want to post contents of a file, like video/audio data , which i understand i can send as raw binary data. i have defined FileContent class with a field that can store bytes. but when i try to post file contents,

    curl -X POST -F "file=@somefile.wav" http://127.0.0.1:5000/upload_file_content



    i get json serialization error. how can i map the binary content of the file, i send via curl command to the FileContent class ?

    curl -X "POST" \
    "http://127.0.0.1:5000/items" \
    -H "accept: application/json" \
    -H "Content-Type: application/json" \
    -d "{\"name\": \"foo\"}"


    from fastapi import FastAPI
    from pydantic import BaseModel, bytes

    app = FastAPI()

    class FileContent(BaseModel):
    data: bytes

    class Item(BaseModel):
    name: str

    @app.post("/items/")
    async def create_item(item: Item):
    return item

    @app.post("/upload_file_content/")
    async def upload_file_content(file_content: FileContent):
    # do something with file content here

    Continue reading...

Compartilhe esta Página