0

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()

1 Answer 1

1

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})
Sign up to request clarification or add additional context in comments.

5 Comments

Do we need to give full path of image in api request. Ex: pic_file =E:\env\abc.png
You don't need to. You could give it a relative path from wherever your python file is being executed, but the full path is probably easiest and best.
Hi @inteoryx, your code works thanks. I want to know If I want to test api request using browser, how will I test?? I tried: http://127.0.0.1:5000/api_endpoint/files=linux_commands.jpg but it's not working, can we test image api using browser??
You can test using a browser, but it's more complicated. Remember, what your request is sending is the data, the actual bytes, of the file, not just a string in the url. To test in the browser you need to add some HTML and Javascript to select and upload a file to your endpoint.
Hi @inteoryx, It would be great. if you share one example for testing it in browser or any references over internet. It will work!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.