user3264316
user3264316

Reputation: 332

Python (tastypie) - Bad request on POST, returns "error" dict

I'm trying to send data to my Django-powered server using Tastypie.

I have this model

class Open(models.Model):
    name=models.TextField()

and this URLconf

open_resource=OpenResource()

urlpatterns = patterns('',
    url(r'^api/', include(open_resource.urls)),
    url(r'^admin/', include(admin.site.urls)),
)

when I run the tastypie curl command

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name","awdawd"}' http://localhost:8000/api/open/

I get the error

HTTP/1.0 400 BAD REQUEST
Date: Sat, 05 Apr 2014 12:18:48 GMT
Server: WSGIServer/0.1 Python/2.7.3
X-Frame-Options: SAMEORIGIN
Content-Type: application/json

{"error": ""}

I've tried everything and can't seem to get this working.

Does anyone have a clue on this one?

Thanks a lot in advance

Upvotes: 3

Views: 1631

Answers (2)

Nick M
Nick M

Reputation: 1242

I get this unhelpful error whenever I provide invalid JSON data.

Correct JSON format is:

{"foo": "bar"}                     // correct!

[{"foo": "bar"}, {"fiz": "baz"}]   // correct!

{"foo": "bar", "fiz": "baz"}       // correct!

Examples of common mistakes:

{'foo': 'bar'}    // error is using single quotes instead of double quotes
{foo: "bar"}      // error is not using double quotes for "foo"
{"foo", "bar"}    // error is using a comma (,) instead of a colon (:)  ← Your error

Examples of more complex mistakes:

[{"foo": "bar"}, {"fiz": "baz"},]
// error is using a comma at the end of a list or array

{"foo": "bar", "fiz": "baz",}  // courtesy @gthmb
// error is using a comma at the end of the final key-value pair

Think your JSON is valid? Double-check with a JSON validator.

Upvotes: 2

rawsix
rawsix

Reputation: 89

As tastypie works with JSON data you have to provide also this format. Try this as data:

--data '{"name": "myName"}'

Also I'm not sure how you build your urls, but I can show you a working url set up:

v1_api = Api(api_name='v1')
v1_api.register(OpenResource())
urlpatterns = patterns('',
url(r'^api/', include(v1_api.urls)),
...
}

This would create the following url to access your resource:

/api/v1/open/?format=json

This would finally come to this curl command:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name": "myName"}' http://localhost:8000/api/v1/open/

And don't forget to add the authorisation and authentication in your metadata of your resource

OpenResource(ModelResource)
    class Meta:
    queryset = Open.objects.all()
    authorization = Authorization()  

As by default tastypie sets up a resource with the ReadOnlyAuthorization, which forbids post, put access.

For more information read the docs: https://django-tastypie.readthedocs.org

Hopefully this helped, cheers!

Upvotes: 0

Related Questions