Python Requests, getting back: Unexpected character encountered while parsing value: L. Path
Question: I am attempting to get an auth token from The Trade Desk's (sandbox) api but I
get back a 400 response stating:

> "Error reading Content-Type 'application/json' as JSON: Unexpected character
> encountered while parsing value: L. Path '', line 0, position 0."

Whole `response.json()`:

    
    
    {u'ErrorDetails': [{u'Reasons': [u"Error reading Content-Type 'application/json' as JSON: Unexpected character encountered while parsing value: L. Path '', line 0, position 0."], u'Property': u'TokenRequest'}], u'Message': u'The request failed validation. Please check your request and try again.'}
    

My script (runnable):

    
    
    import requests
    
    def get_token():
    
        print "Getting token"
        url = "https://apisb.thetradedesk.com/v3/authentication"
    
        headers = {'content-type': 'application/json'}
    
        data = {
                  "Login":"logintest",
                  "Password":"password",
                  "TokenExpirationInMinutes":60
                }
    
        response = requests.post(url, headers=headers, data=data)
    
        print response.status_code
        print response.json()
    
        return
    
    get_token()
    

[Sandbox docs here](https://apisb.thetradedesk.com/v3/doc)

I believe this means my `headers` var is not being serialized correctly by
`requests`, which seems impossible, or not being deserialized correctly by The
Trade Desk. I've gotten into the `requests` lib but I can't seem to crack it
and am looking for other input.


Answer: You need to do

    
    
    import json
    

and convert your dict into json:

    
    
    response = requests.post(url, headers=headers, data=json.dumps(data))
    

Another way would be to explicitely use `json` as parameter:

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

_Background:_ In the `prepare_body` method of requests a dictionary is
explicitely converted to json and a content-header is also automatically set:

    
    
    if not data and json is not None:
            content_type = 'application/json'
            body = complexjson.dumps(json)
    

If you pass `data=data` then your data will be only form-encoded (see
<http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-
post-requests>). You will need to explicitely convert it to json, if you want
json to be the content-type of your http body.

Your follow-up question was about why headers don't have to be converted to
json. Headers can be simply passed as dictionary into the request. There's no
need to convert it to json. The reason is implementation specific.

