18

I am using Python Flask to create a server. I want to send application/json back to the client (my customer requires this). When I use json.dumps() it is sending back text.

(Incase your wondering, if I use jsonify() instead of json.dumps(), I do get application/json, however this function seems to have problems with some data (if I dont get a solution here, I will look further into jsonify)).

server..............

import json
from flask import Flask, render_template, url_for, current_app, request, jsonify

app = Flask(__name__)

@app.route("/<arg1>")
def route1(arg1):
    dict1 = {"prop1": "p1", "prop2": "p2"}
    #return jsonify(dict1)      # this sends 'application/json'
    return json.dumps(dict1)  # this sends ' text/html; charset=utf-8'

app.run(host="0.0.0.0", port=8080, debug=True)

Test client (actual client is provided by customer) ......

import pycurl
import cStringIO

SERVER_URL = "http://192.168.47.133:8080"  

buf = cStringIO.StringIO()
c = pycurl.Curl()

c.setopt(c.URL, SERVER_URL + '/index.html?city=perth')
c.setopt(c.HTTPHEADER, ['Accept:application/json']) 
c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.VERBOSE, True)

c.perform()
buf1 = buf.getvalue()
buf.close()

print(buf1)
spiderplant0
  • 3,872
  • 12
  • 52
  • 91
  • 1
    http://stackoverflow.com/questions/11773348/python-flask-how-to-set-content-type – Doobeh Sep 04 '14 at 13:38
  • possible duplicate of [Forcing application/json MIME type in a view (Flask)](http://stackoverflow.com/questions/11945523/forcing-application-json-mime-type-in-a-view-flask) – tbicr Sep 04 '14 at 14:00
  • could you please specify what kind of data has the `jsonify` problems with? (I'm looking for similar solution to your problem) – Erbureth Jan 22 '15 at 12:35

3 Answers3

32

Change it like this:

from flask import Response

@app.route("/<arg1>")
def route1(arg1):
    dict1 = {"prop1": "p1", "prop2": "p2"}
    return Response(json.dumps(dict1), mimetype='application/json')
mehdix
  • 4,984
  • 1
  • 28
  • 36
12

I would recommend you to use jsonify which is inbuilt from Flask.

from flask import jsonify
@app.route("/<arg1>")
def route1(arg1):
    return jsonify({'data':{"prop1": "p1", "prop2": "p2"}})

Access in templates using javascript

if (typeof result['data'] !== "undefined"){
    alert(result["data"]);
}
Nava
  • 6,276
  • 6
  • 44
  • 68
1

If you want to return your response as application/json use "return jsonify()"

Sathwik Boddu
  • 41
  • 2
  • 6
  • Op wrote: *Incase your wondering, if I use jsonify() instead of json.dumps(), I do get application/json, however this function seems to have problems with some data (if I dont get a solution here, I will look further into jsonify* – Leviand Jul 25 '18 at 09:18