简体   繁体   中英

REST - GET returns different result than POST/PUT

In our project, a book can be added by sending the book structure (in XML, JSON, ..) via a POST or PUT request. For example, in XML, the book structure looks like this (simplified):

<book>
    <title>My Book</title>
    <author>John Q.</author>
</book>

When this book is inserted in our backend database, some auto-generated properties are automatically added, such as the creation date, the user id who submitted the book, an identifier, ...

When the book is retrieved through a GET, these additional properties are included in the book definition:

<book>
    <title>My Book</title>
    <author>John Q.</author>
    <info>
        <creation_date>2011...</creation_data>
        <user_id>48</user_id>
        <identifier>my_book_john_q</identifier>
    </info>
</book>

This basically means that the XML scheme of a new/edited book (= from client to server) is different than a retrieved book (= from server to client). This makes things confusing.

A possiblity is to make these additional properties available in a different URI, for example:

http://server/books/:id/             -> returns the short version
http://server/books/:id/information/ -> returns the generated properties

A downside of this approach is that two separate requests are needed to have all data.

How would you solve this inconsistency?

This is perfectly normal. There is no problem having the server augment the representation with some additional information. A good example of this is when the server adds links to the representation. There is no requirement for the client to send "copies" of those links to the server when doing a PUT. The resource representations that you GET and PUT should be conceptually the same, not necessarily byte for byte identical.

You're not using mimetypes correctly. I bet you're using an application/xml generic mimetype and your clients know what to expect based on the endpoint, right?

The proper way to deal with your problem would be having different representations for the same resource, with different mimetypes. For instance, you can have a application/vnd.yourcompany.book.short+xml for the short representation, and application/vnd.yourcompany.book+xml for the complete representation. Clients can use the Content-Type header to say which one they are sending, and the Accept header to say which one they want.

This doesn't mean the clients must send the short representation in the POST or PUT. You can document some fields as optional and it's perfectly fine for the clients to omit them.

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