Home > Enterprise >  How to give image as an user input in api request using flask in python
How to give image as an user input in api request using flask in python

Time:11-19

I am creating an API where I want to give image as an user input.

I know request.args.get take user input in dictionary format. I want to know if in any way user can give image as input to api in below api script.

My image path is E:\env\abc.png

a.py

import pandas as pd
from datetime import datetime
from pandas import json_normalize
from flask import request, Flask, Response
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

@app.route("/api_endpoint", methods=["GET"])
def function_for_api():
    
    user_input_image = request.args.get('user_input_image')
    print("USER IMAGE",user_input_image)

    status = 200
    resJson = "python_file_name output will be here in json format"
    return Response(response=resJson, status=status, mimetype="application/json")

if __name__ == "__main__":
    app.run()

CodePudding user response:

First, this method should be a POST and not a GET. You are putting information on the server. Second, you want to read the file from the files parameter and not one of the query parameters.

@app.route("/api_endpoint", methods=["POST"])
def function_for_api():
    img = request.files['file']
    print(img.filename)
    return Response(status=200)

Here is an example of you could call this function uploading an image.

import requests
pic_file = "picture_filename"
# post a request with file and receive response
with open(pic_file, 'rb') as f:
    resp = requests.post(f"{your_server_address}/api_endpoint", files={'file': f})
  • Related