Home Best practices for POSTing nested objects to REST server
Reply: 0

Best practices for POSTing nested objects to REST server

user2253
1#
user2253 Published in June 18, 2018, 7:41 am

I'm wondering what is the usual approach when developing REST API servers for creating or updating nested data.

Suppose I have a set of database models as follows:

"client" (id, firstname, lastname, ForeignKey to "address")
"address" (id, street, city, state, country)
"email" (id, type, emailaddress, ForeignKey to "client")
"phone" (id, type, number, ForeignKey to "client")

In other words a client has a single address, but there can be multiple emails per client and multiple phone numbers per client. Now suppose that I am developing a REST API server that allows users to create/edit/delete any of these objects. The "address" and "email" and "phone" objects are straightforward. However, what about "client"? When a user wants to create a new client, that user would send a POST command to the server with a data structure in JSON that would look something like this:

{
    "id": 123,
    "firstname": "John",
    "lastname": "Smith",
    "address": {"street": "123 Anystreet", "city": "Los Angeles", "state": "California", "country": "USA"},
    "emails": [
        {"id": 7, "client_id": 123, "type": "home", "emailaddress": "john@home.com"},
        {"id": 12, "client_id": 123, "type": "work", "emailaddress": "john.smith@work.com"}
    ],
    "phones": [
        {"id": 28, "client_id": 123, "type": "home", "number": "(555) 555-1234"},
        {"id": 17, "client_id": 123, "type": "work", "number": "(555) 555-9876"}
    ]
}

So what should the REST server do with this information? Obviously it should save the top level client object (with the firstname and lastname fields) but what should it do with the nested objects? Should it check the database for say email with id=7 and update that email object? Or should it check the database to set ONLY email with id=7 or id=12 to point to this client? It isn't clear to me what are the expected semantics of nested REST object create and update operations. Or is it/should it be the case that REST create/update operations should only be performed on the top level object, and if a user wants to create or modify the nested/embedded objects then the user should make additional REST calls to do so?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317247 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO