Question

I'm creating REST API that will be used by a web page.
There are several types of data I should provide, and I'm wondering what would be the best practice:

  1. Create one method that will return a complex object with all the needed data.
    • Pros: one call will be needed from the UI side to get all the data.
    • Cons: not generic solution at all.
  2. Create multiple autonomous method.
    • Pros: generic enough to be used in the future by other components.
    • Cons: will require the UI to make several calls to the server.

Which one adheres more to best practices?

Was it helpful?

Solution

It ultimately depends on your environment, the data-size and the quantity of methods. But there are several reasons to go with the second option and only one to go with the first.

First option: One complex method

Reason to go with the first: The HTTP overhead of multiple requests.

Does the overhead exist? Of course, but is it really that high? HTTP is one of the lightest application layer protocols. It is designed to have little overhead. It's simplicity and light headers are some of the main reasons to its success.

Second option: Multiple autonomous methods

Now there are several reasons to go with the second option. Even when the data is large, believe me, it still is a better option. Let's discuss some aspects:

  • If the data-size is large
    • Breaking data transfer into smaller pieces is better.
    • HTTP is a best effort protocol and data failures are very common, specially in the internet environment - so common they should be expected. The larger the data block, the greater the risks of having to re-request everything back.
  • Quantity of methods: Maintainability, Reuse, Componentization, Learnability, Layering...
    • You said yourself, a generic solution is easier to be used by other components. The simpler and more concise the methods' responsibilities are, the easier to understand them and reuse them in other methods it is.
    • It is easier to maintain, to learn: the more independent they are, the less one has to know to change it (or get rid of a bug!).

To take REST into consideration here is important, but the reasons to break down the components into smaller pieces really comes from understanding the HTTP protocol and good programming/software engineering.

OTHER TIPS

So, here's the thing: REST is great. But not every pattern in its purest form works in every situation. If efficiency is an issue, go the one-call route. Or maybe supply both, if others will be consuming it and might not need to pull down the full complex object every time.

I'd say REST does not care about data normalization. Having two ways to get at the same data is not going to hurt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top