简体   繁体   中英

REST API - Is it allowed to use different representations for POST and PUT/PATCH?

Assume that I have a function for processing POST requests, which takes following representation for POST request:

 ' { "name": "name", "nestedObject": { "prop1": "v1", "prop2": "v2" } } '
It creates new object with given name and also creates nested object for it with props: prop1 and prop2.

For PUT/PATCH requests however, it would be more convenient for me to use URL of (already existing) object to make it nested object for top-level object, instead passing its data, something like this:

 ' { "name": "updatedName", "nestedObject": "http://alreadyExistingObjectUrl" } '
GET on the other hand would return nested object data, not its URL:

 ' { "name": "name", "nestedObject": { "prop1": "v1", "prop2": "v2" } } '

Is it good practice to use different representations of resource for different methods? POST takes nested object data and creates it, PUT/PATCH only takes already existing object url and makes that object nested for parent object. GET returns nested object data, not URL.

If you need a different format, it's a good idea to define specific mimetypes for each.

Generally it's a very good design property to allow a user to do something like:

foo = resource.get();
foo.name = 'new name';
resource.put(foo);

Basically, if I can assume that the format that GET returns can be re-used in a PUT request, it also means the server can add new required properties and this will still work.

Anyway, this is a best practice but not a hard recommendation. If the representations of PUT and GET are different I would expect a different mimetype however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM