0

I'm trying to get data from API with GET query in Django. I get as response HTML-code, where the JSON is included too. It seems like Content-Type header isn't working and that's why I get HTML-code as response.

I tested to do queries with Postman:

  • When I didn't have Content-Type header at all, I got same HTML-code as now.
  • When I have Content-Type header as text/json, it responded with JSON-data.

Here is my code at views.py, I don't expect this to work on website yet, so I don't return/render anything

def json_search(request):
    query = request.GET.get('query')
    final_url =  urllib2.Request('http://APIwebsite.com', None, {'Content-Type':'text/json'})
    base64string = base64.encodestring('%s:%s' % ('username', 'password')).replace('\n', '')
    final_url.add_header("Authorization", "Basic %s" % base64string)   
    json_obj = urllib2.urlopen(final_url)
    decoded_data = json_obj.read()
    print decoded_data

As response I get HTML-page code, with CSS and JSON-data. How I can get just only the JSON data?

2
  • I believe the Content-Type should be application/json rather than text/json and json.loads call should work on the returned response. Also, what's the python version that you are using? Commented Apr 21, 2016 at 9:41
  • No change for me. I'm using 2.7.10. Commented Apr 21, 2016 at 9:47

3 Answers 3

1

you can write a utility method and pass the arguments in that, for example

class JsonResponse(HttpResponse):
    '''
        Handling content type for json no more to add content-type.
    '''

    def __init__(self, content={}, status=None,content_type='application/json'):
        super(JsonResponse, self).__init__(
            json.dumps(content),
            status=status, content_type=content_type)

after this you just need to pass the data to the above method like

response_json.update({"message": "success"})
return JsonResponse(response_json)

This might solve your issue.

Sign up to request clarification or add additional context in comments.

Comments

0

Try using,

json.loads(request.body)

Json responses can be handled using this way.

1 Comment

I'm not sure if I understood you, but I get error that attribute body doesn't exist. Without it, I get error "TypeError: expected string or buffer".
0

HTML-page had a link to page, where is only the JSON-code. So, I made query to that page, and it works. Though, I have made the same query with Javascript and it worked with correct Content-Type header.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.