I am trying to take a file from user using Openapi 3.0 and swagger UI. However i am not getting that file for processing in my python function. Below is my code:
code.py
def get_file():
try:
file=request.files.getlist('file')[0]
with open(file, 'r') as fp:
files = {"file": (file, fp)}
response = requests.post(server, files=files)
return response.json()
except Exception as exc:
return exc
api.yaml
/get-result:
post:
summary: "A function to get file"
operationId: "code.get_file"
requestBody:
content:
application/json:
schema:
type: string
format: binary
responses:
200:
description: "executed successfully"
content:
application/json:
schema:
$ref: "#/components/schemas/myschema"
500:
description: Server is down.
I have already referred this link: Upload a file in Swagger and receive at Flask backend However this is for Openapi 2.0 and didnt help as I am using openapi 3.0
CodePudding user response:
check if
request.files['file']
can get the file from the request, I'm not sure if the line
file=request.files.getlist('file')[0]
will actually get the correct file (or only a list?)
CodePudding user response:
Below code changes helped me to get this resolved:
api.yaml
/get-result:
post:
summary: "A function to get file"
operationId: "code.get_file"
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
file:
type: string
format: binary
responses:
200:
description: "executed successfully"
content:
application/json:
schema:
$ref: "#/components/schemas/myschema"
500:
description: Server is down.
In below code.py it was essential to pass the parameter 'file' to the function which is also the field name in openapi specification. Also its important to send file pointer and filename with the post request
code.py
def get_file(file):
try:
fp=file.read()
file.save(file.filename)
response = requests.post(server, files={"file":(file.filename,fp)})
return response.json()
except Exception as exc:
return exc