Content Type Response API is not consistent

Hallo,

I try use MAAS Restful API, but get not consistent content type response. Some time I get Content-Type text/xml, some time Content-Type application/json, Content-Type application/python-pikle. This affects when I parse data, all I need is content-type application / json.

I write code on django (python).

this code maas_connect

from django.conf import settings
from requests_oauthlib import OAuth1Session, OAuth1



def maas_connect():
    consumer_key, token_key, token_secret = settings.MAAS_API_KEY.split(":")
    return OAuth1(
        consumer_key,
        client_secret='',
        resource_owner_key=token_key,
        resource_owner_secret=token_secret,
        signature_method='PLAINTEXT',
    )

and this request on view django

def machines(request):
    auth = maas_connect()
    headers = {'content-type': 'application/json'}
    res = requests.get(settings.MAAS_URL + "api/2.0/machines/", headers=headers, auth=auth)
    print(res.headers['content-type'])
    context = {
        'title': 'Machines',
        'machines': res.json(),
        'menu_active': 'machines',
    }
    return render(request, 'maas/machines.html', context)

in line 'machines': res.json(), always error JSONDecodeError because the data obtained is not json.

this screnshoot console from content type and error

You need to add an “Accept” header to your request indicating that you want a JSON response. I tripped over this as well. As long as you send Accept: application/json the response will be reliably encoded how you want.

Cheers

1 Like

Thank for your answer, it’s work.