3

I am having trouble with the list type in my schemas. Whenever I try to POST, I get a 422 response stating 'must be of list type'. Below is a simple example that produces this problem.

from eve import Eve

people = {
    'schema': {
        'tests': {
            'type': 'list',
            'schema': {
                'type': 'string'
            },
            'required': True,
        }
    },
    'resource_methods': ['GET', 'POST'],
}

settings = {
    'DOMAIN': {
        'people': people
    }
}
app = Eve(settings=settings)

if __name__ == '__main__':
    app.run()

Then when you POST to the people endpoint with the following:

import requests

url = "http://localhost:5000/people"

person = {
    "tests": ['a', 'b'],
}

r = requests.post(url, data=person)
print(r.json())

You get the 422 response. When I debug this, it looks like the Eve application has received the tests parameter as just a string, 'a', rather than the whole list. From what I can see in the Eve tests on GitHub, this seems to be the right way to make the request, so I can only assume I'm making a mistake in setting up the resource/schema?

Thanks.

Andrew Walker
  • 97
  • 1
  • 7

1 Answers1

1

If you print request.POST, you would see UnicodeMultiDict([('tests', u'a'), ('tests', u'b')]). Fix to this would be to use json object for your post.

person = json.dumps({
    "tests": ['a', 'b'],
})

r = requests.post(url, json=person)
print(r.json())

Or in your case, you will have to somehow tweak your POST request at API end to get a list as:- request.POST.getall('tests') and then proceed.

Please check using json in POST request. Also while using json, json.dumps may not be required, the dictionary will be jsonified automatically.

Barun Sharma
  • 1,452
  • 2
  • 15
  • 20
  • Ah, that works, thanks. I didn't realise there was a `json`argument in requests. I had already tried `data=json.dumps(payload)`, which gives a 400 error. Now looking at the [requests docs](http://www.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) I thought they would be equivalent. – Andrew Walker Sep 08 '15 at 11:40
  • Probably I should add this link to the answer. – Barun Sharma Sep 08 '15 at 11:42
  • 2
    I found that the reason `json=person` works where `data=json.dumps(person)` doesn't is because the json keyword argument also changes the request header to `application/json`, where the manual dump doesn't. – Andrew Walker Sep 08 '15 at 12:42
  • @AndrewWalker Ok. Thanks. I didn't knew this. – Barun Sharma Sep 08 '15 at 13:41