python-3.xflaskflask-restfulpython-jsons

Posting JSON to Python API (created using flask)


I have below code where I am making an API using flask:

from flask import Flask, request, jsonify
import json

app = Flask(__name__)

@app.route('/post', methods=['GET','POST'])
def post():
   payload = request.data

  # return jsonify(data)
  # json_object = json.dumps(data, indent=4)
  return payload
  # return jsonify(payload)

if __name__ == '__main__':
   app.run(debug=True)

and using below code to call the localhost hosted API:

    import requests
    headers =  {'Content-Type': 'application/json; charset=utf-8'}
    url = "http://localhost:5000/post"
    text = {"filename": "my_file.csv"}

    response = requests.post(url, json=text , headers=headers )


    if response.status_code == 200:
        print("CSV file is valid")
    #   print(data)
    #   print(getjson)
        print(text)
    else:
       print("CSV file is invalid")

The problem is

  1. that when I call the localhost URL using the calling code I get a successful connection, however no data gets "posted" on the URL,

  2. if I try to jsonify (or use JSON dumps) and then run the calling code it stills runs successfully however the localhost site gives below error:

    Bad Request

    Did not attempt to load JSON data because the request Content-Type was not 'application/json'.

How can I rectify this? My aim is to push JSON using the flask API and display it on the localhost site. The long term goal being is that we need to create an app that is validating the JSON passed, so to begin with I am trying to see if it is reading the JSON successfully as-is, or not?


Solution

  • To send data in JSON format to the server and receive its response, the following example code is effective. The Content-Type header is set automatically, so it shouldn't be necessary to use request.get_json(force=True) on the server side to assume transmission as JSON.

    For server-side validation of the JSON data, I recommend taking a look at webargs. The library offers you various validators to check the sent data.

    from flask import Flask, jsonify, request
    
    app = Flask(__name__)
    
    @app.post('/echo')
    def echo():
        data = request.get_json()
        return jsonify(data)
    
    import requests
    
    url = 'http://127.0.0.1:5000/echo'
    dat = { 'lang': 'python' }
    
    r = requests.post(url, json=dat)
    r.raise_for_status()
    print(r.json())