开发者

Using JSON as the format for API request parameters (designing an API for my web app)

I'm designing an API for my web app, and our content is fairly complex. For example, you can have a wiki page with multiple sub objects like tags, multiple separate content areas, and more.

I don't want to deal with a complicated, kludgy way of naming params like tag_N or tag[].

It also occurred to me that our objects can be expressed perfectly as JSON. In fact, that's our response format. If you do a GET, you receive the object in JSON format.

Is it reasonable to require that POST and PUT body of the object also be specified in JSON? For example, something like this:

{
 'name' : 'My Page',
 'body' : 'Some page body',
 'tags' : ['tag1', 'tag2', 'tag3']
}

as opposed to

name=My%20Page&body=Some%20page%20body&tag[]=tag1&tag[]=tag2&tag[]=tag3

This is a pretty simplified example. In many cases we have complicated objects with arrays of sub-objects, who themselves also contain sub-objects. It's fairly simple to describe with JSON, but gets very 开发者_JS百科difficult with query string style params.

So, the main question is: If we require the POST body to be a JSON string, is that unreasonable? Is it too far outside the norm of HTTP APIs? Would you, as the author of an API consumer, be put off by an API with a requirement like this?


It's not unreasonable. You may be mixing a few things here: (a) data format, (b) encoding, and (c) REST design philosophy.

Generally, I would suggest the following:

  • Data formats should be consistent (e.g., JSON as the basis for all CRUD methods on a resource; it would be nice if you supported XML as well because of its ubiquity -- many frameworks do this automatically for you)

  • Encoding should be separate from data transmission format; for example, URLs have encoding that differs slightly from body encoding. Don't confuse that with the data format.

  • Suggest that you model the resource as REST-ful as you can. Use POST for create, GET for read, PUT for update, and DELETE for delete in most cases


It's quite typical of JAX-RS/REST APIs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜