[FIXED] Python REST API flask


I have a script which accepts arguments as JSON and gets executed. However I need to call the script through FLASK from a third party application POST method.

My Script is as below

import argparse
import os
import win32security, win32con
import ntsecuritycon as con
import pywintypes
import json
import sys, json

# Set up the argument parser
parser = argparse.ArgumentParser()
parser.add_argument('JSON', metavar='json',type=str, help='JSON to parse')

args = parser.parse_args()

# Get JSON data
json_str = args.JSON

# Parse JSON data
json_data = json.loads(json_str)

path = os.path.join(json_data["parentdir"], json_data["dirname"])

The above scripts works when i run

python test.py "{\"parentdir\": \"D:\\Important\", \"dirname\": \"test\"}"

How I can call the same script as HTTP POST from a 3rd party API through flask. I have got idea on creating flask script but not sure how to pass the parameters to the script through flask route api

I tried below :
@app.route(‘/’, methods=[‘POST’])

def hello_world():
    #parentdir = request.values.get("parentdir")
    #dirname = request.values.get("dirname")
    parentdir = request.get_json("parentdir")
    dirname = request.get_json("dirname")
    path = os.path.join(parentdir, dirname)

if __name__ == '__main__':

Error - Failed to decode JSON object: Expecting value: line 1 column 1

Please help.


You create a flask route witch receives parentdir and dirname as parameters.
The route can execute the part of your script that create the dir.

import locale
import os

from flask import Flask, request, jsonify

# Create Flask APP
app = Flask(__name__)

@app.route('/', methods=['POST'])
def hello_world():
    parentdir = request.json.get("parentdir")
    dirname = request.json.get("dirname")
    path = os.path.join(parentdir, dirname)
    # makedirs create directory recursively 

    return jsonify()

if __name__ == "__main__":
    app.run(port=5000, host="", use_reloader=True)

The postman request

curl --location --request POST '' \
--header 'Content-Type: application/json' \
--data-raw '{
    "parentdir": "okn",
    "dirname": "okn"

Answered By – AlexisG

Answer Checked By – Robin (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published