0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Possible duplicate of https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request – Rob Jul 17 '23 at 09:09

1 Answers1

0

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())
Detlef
  • 6,137
  • 2
  • 6
  • 24
  • Hi, thanks for responding . while i dont get any errors after running both codes (and after running the calling code i can see the output in the console) . What I also need to do is to see the output in the localhost site, Still when i refresh the localhost site i get the error "Bad Request Did not attempt to load JSON data because the request Content-Type was not 'application/json'." – K_python2022 Jul 17 '23 at 12:52
  • What do you mean by "refresh the localhost"? As already described, the header for the content type is set automatically when the client script is called. If you want the server to interpret the JSON data without checking the header, set the `force` parameter to `True`. `request.get_json(force=True)` – Detlef Jul 17 '23 at 14:27