Rest – Custom functions in a REST API

apiapi-designrest

Looking at two of our entities Company and Address. A company has a billingAddress and a profileAddress.

I'm unsure of how to implement a function to set the billing address versus the profile. Here are the options I can see:

  1. Create a new address using a POST to /address. Update the company object at /company with profileAddress = {/* the new id of the address */}

  2. Execute /company/:id?function=updateBillingAddress&{/* rest of parameters go here */}

  3. Execute /updateBillingAddress?company={companyId}&{/* rest of parameters go here */}

  4. Execute /company/:id?billingAddress={ /* address data here */ }

The first method requires two calls and more responsibility on the part of the developer hooking up to the API. However, I'm not sure the second two methods are appropriate structure.

The last one seems like it might be okay, it gives flexibility for updates without holding the responsibility of managing pointers or executing two calls.. still unsure.

Has anyone seen use of methods 2 or 3 before. Are they okay to use? Why / why not? Which would you suggest to use and why?

Best Answer

In my mind, you have two different ways to handle this:

1) One resource to rule them all:

To create a new company:

 `POST /company`

POST body has full details of the company, including both profile address and billing address. As noted by v0idnull, return value should be a 201 Created with a Location header with the URL of the newly created resource.

To set the billing address:

Fetch the current company representation:

GET /company/123

Update the representation with the new billing address, and do:

PUT /company/123

With the full new representation of the company.

PROS

  • Reduce the number of requests for some workflows.
  • Caching is "easier" as you need to only worry about the caching of the one resource.
  • Easier to understand for more API customers.

CONS

  • If you have frequent updates to the company resource for different reasons, you can hit issues with concurrent updates
  • No ability to have fine grained cache control for the different aspects of the company.

2) Separate sub-resources for billing address and profile address

To create a new company:

POST /company

Response looks something like:

201 Created
Location: /company/123
Link: </company/123/billing_address>;rel=billing_address
Link: </company/123/profile_address>;rel=profile_address

Clients can then follow the billing_address or profile_address link relations to update those attributes respectively.

PROS

  • Allows fine grained updates to different aspects of the company with potentially less concurrent update failures.
  • Fine grained caching of each resource.
  • By using hypermedia/links, can restructure URLs/application later.

CONS

  • Requires multiple requests for many workflows (Mobile clients?)
  • Harder to grok for some API consumers not familiar with hypermedia APIs.
Related Topic