carnava1
carnava1

Reputation: 319

POST request for .txt file

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

Upvotes: 2

Views: 3651

Answers (2)

Aleksei Iancheruk
Aleksei Iancheruk

Reputation: 1

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

pip install python-multipart

Upvotes: 0

Glyphack
Glyphack

Reputation: 886

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.

Upvotes: 3

Related Questions