The Elements of APIs

Side effects

Manipulating some resources might result in changes being applied to other resources. Your Cart resource might have a subtotal attribute, and creating a new Cart Item resource that relates to the Cart may update that attribute.

This kind of calculated attribute can be very powerful and useful. It’s important to express to your client that these fields are read-only. It’s also helpful to document how they are calculated, not only on the resource that owns them but also on the resources that affect the value.

Avoid creating dependencies between resources that don’t have an explicit relationship. In fact, it’s quite alright to create a read-only relationship! This can be useful for splitting up a resource that would otherwise be enormous, especially if your clients are unlikely to use all of that resource’s attributes at the same time. For example, a User resource may have many fields for an Instagram username, GitHub username, Facebook username, and so on. Creating a “User Social” or “User External” resource, which is automatically created when a “User” resource is created, can be helpful here.

Also, remember that your resources don’t have to (and in many cases shouldn’t) mirror your data store. You might have a users table in your relational database with 50 columns, but maybe only 10 of those actually belong to the User resource. You can even use the same primary key for the related resources, so User 1 relates to User Social 1. Just make sure your clients are not expecting these to be identical, and always following the resource relationships. That way, if it someday makes sense to use a second table with its own primary key, nothing breaks.