Skip to content
ProCynic edited this page Apr 13, 2012 · 5 revisions

json api

Amin asked me write up an explanation of the new json api that I created, so here it is.

How to use it

The json api allows you to send json objects via http to CRUD the database. It's not fully implemented, but when it is you should be able use it to do anything that you can do via the web interface.

I'm using curl to test the api, but you can use anything that's capable of generating an http request to use it, including javascript. Here's the call to curl to the entry point of the api with bob as the user:

curl -X GET -H "Accept: application/json" --user b3bob:secret http://localhost:9000

The key to getting it to return a json object instead of an html file is that "Accept: application/json" line in the header. Speaking of which, here's the json object you get back:

{
  "things" : 
  [
    "posts" : "/posts",
    "comments" : "/comments",
    "photos" : "/photos",
    "events" : "/events",
    "threads" : "/threads",
    "messages" : "/messages/inbox"
  ]
}

Then you can get a list of all the posts that bob has access too like so: curl -X GET -H "Accept: application/json" --user b3bob:secret http://localhost:9000/posts

Note that I've just taken the value from the posts key and used that to make the new url. Here's the response:

[
   
    "/posts/11",   
    "/posts/10",   
    "/posts/9",   
    "/posts/8"  ]

Then you can get a json object representing post 9 like so: curl -X GET -H "Accept: application/json" --user b3bob:secret http://localhost:9000/posts/9

which gives:

{      
  "title"   : "Just a test of YABE",
  "author"  : "b3bob",
  "type"    : "NEWS",
  "content" : "Well, it's just a test.
"
}

You can also delete post 9 via the api like so:

curl -X DELETE --user b3bob:secret http://localhost:9000/posts/9

This only works because you make the request with bob's username and password and bob is the owner of the post. If you try to delete someone else's post, say post 11, you get a 403.

Hopefully soon you'll be able to create a new post via an http POST request to /posts , but that isn't implemented yet. Eventually this api should extend to all the user accessible objects in the database.

How it's implemented

Implementing the GET requests is actually pretty simple. Play will automatically recognize the "Accept: application/json" line in the header and take that into consideration when it formulates the response. So to return that top level list of URLs, I didn't need to make any changes at all to the controller, I simply created a app/views/Application/news.json template to return that object. I also created app/views/Posts/posts.json, app/views/Posts/post.json, app/views/Comments/comments.json, and app/views/Comments/comment.json. These are actually templates, just like the html templates, so you can use all the stuff from the play template language.

Clone this wiki locally