2

I can't write a function, that can get a .txt file through POST-request.

I have a .txt file that contains phrase: Hello World!

server side:

from fastapi import FastAPI, File
from starlette.requests import Request
import io

app = FastAPI()
@app.post("/post_text_file")
def text_function(request: Request,
            file: bytes = File(...)):
    text = open(io.BytesIO(file), "r").read()
    return text  # Hello World!

client side:

import requests

url = 'http://localhost:8000/post_text_file'
r = requests.post(url,data=open('Hello World.txt'))

after run command uvicorn main:app and run a code in a client side I get next answer:

On the client side: {'detail': 'There was an error parsing the body'}

On the server side: "POST /post_text_file HTTP/1.1" 400 Bad Request

petezurich
  • 9,280
  • 9
  • 43
  • 57
carnava1
  • 319
  • 2
  • 6

2 Answers2

3

There is an files parameter for requests.post you can use it to send files like this:

import requests

url = "http://localhost:8000/post_text_file"
fin = open('Hello World.txt', 'rb')
files = {'file': fin}
try:
    r = requests.post(url, files=files)
finally:
    fin.close()

And usually the file sent with your request is accessible with request.files as a dictionary of files uploaded.

Glyphack
  • 876
  • 9
  • 20
0

This can happen if you don't have python-multipart installed. So be sure you have done:

pip install python-multipart