Home > Mobile >  How to use Flask API to post two variables via Postman and run a function using them in that call?
How to use Flask API to post two variables via Postman and run a function using them in that call?

Time:11-18

I have the following function : `

def file(DOCname,TABLEid):
 directory = DOCname
 parent_dir = "E:\\Tables\\Documents\\" TABLEid
 path = os.path.join(parent_dir, directory)

 try:
      os.makedirs(path, exist_ok = True)
      print("Directory '%s' created successfully" % directory)
 except OSError as error:
      print("Directory '%s' can not be created" % directory)

`

Now I want to use a Flask API and call this function to run with two variables that I will provide via Postman, DOCname and TABLEid, but I'm not sure how to run this at the same time I make an API call ?

I tried to run the file under a post request but nothing seems to happen.

CodePudding user response:

It can be done in following way. The data from the Postman should be send through the forms .

from flask import Flask
from flask import request
app = Flask(__name__)

@app.route("/")
def file():
 dic_data = request.form 
 DOCname= dic_data["DOCname"]
 TABLEid = dic_data["TABLEid"]

 directory = DOCname
 parent_dir = "E:\\Tables\\Documents\\" TABLEid
 path = os.path.join(parent_dir, directory)

 try:
      os.makedirs(path, exist_ok = True)
      print("Directory '%s' created successfully" % directory)
 except OSError as error:
      print("Directory '%s' can not be created" % directory)

enter image description here

CodePudding user response:

First you'd need to define your API call. For instance whether you'd be using json. This example assumes json messaging so that the endpoint will accept a POST request and json message of:

{ 
  "docname": "mydoc",
  "tableid": "tid0001" 
}

If you look at the Flask quickstart guide:

You can simply make a basic route which takes a POST request like so

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/", methods['POST'])
def endpoint1():
    my_args = request.get_json()
    try:
        success, message = file(my_args["docname"],my_args["tableid"])
    except KeyError:
        success = False
        message = "Invalid arguments"
    return jsonify({"success": success, "msg": message})


def file(DOCname,TABLEid):
   directory = DOCname
   parent_dir = "E:\\Tables\\Documents\\" TABLEid
   path = os.path.join(parent_dir, directory)

   try:
       os.makedirs(path, exist_ok = True)
       return (True, "Directory '%s' created successfully" % directory)

   except OSError as error:
       return (False, "Directory '%s' can not be created" % directory)

and run with python -m flask --app myscriptname run

While you can test with postman, you should be able to also demo this with a basic curl command like:

curl -X POST -H "Content-Type: application/json" -d '{\
  "docname": "mydoc",\
  "tableid": "tid001"\
}' http://localhost:5000/
  • Related