2

I'm trying to post the following data. But I'm getting an error. Can you please take look? Thanks a lot.

I'm posting the same data using Postman. And it works.

def _build_post_data(bike_instance):
    """
    data = {
        "apikey": "XXX",
        "data": {
            "created_at": "date_XX",
            "Price": "Decimal_XX"
        }
    }
    """
    data = {}
    raw_data = serializers.serialize('python', [bike_instance])
    actual_data = [d['fields'] for d in raw_data]
    data.update(
        {
            "apikey": XXX,
            "data": actual_data[0]
        }
    )
    return data

Posting data

bike = Bike.objects.get(pk=XXX)

data = _build_post_data(bike)

dump_data = json.dumps(data, cls=DjangoJSONEncoder)

requests.post(url, data=dump_data)

error

u'{"error":{"message":"422 Unprocessable Entity","errors":[["The data field is required."],["The apikey field is required."]],"status_code":422}}'

data and apikey already in the dict. then why I'm getting an error? Any idea?

Postman works

enter image description here

1 Answer 1

3

With Postman you are sending a multipart/form-data request, with requests you only send JSON (the value of the data field in Postman), and are not including the apikey field.

Use a dictionary with the JSON data as one of the values, and pass that in as the files argument. It probably also works as the data argument (sent as application/x-www-urlencoded):

form_structure = {'apikey': 'XXXX', 'data': dump_data}
requests.post(url, files=form_structure)
# probably works too: requests.post(url, data=form_structure)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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