api design: a framework for thinking about responsibilities at various layers

2021-12-21

 | 

~2 min read

 | 

289 words

I was working through some API design and trying to find the right level of abstraction for my different portions of code.

I came up with a rather “heavy” framework, though I think there are some redeeming qualities.

What is the framework? There are multiple layers:

Router
Controller
Service
Data Access

What are some benefits of this approach? It’s much more testable and each portion of the stack has a clear responsibility.

On the flip side, there’s a lot of overhead and it might start to feel like some boiler plate (particularly at the data access layer where almost all of the services are going to have similar actions).

But, considering that this isn’t necessary (I’ve seen plenty of APIs that consolidate this all into one or two layers), how do I distinguish between the layers?

  • A router takes a request and routes it to the right controller.
  • A controller is the business logic. It ties a bunch of things together. This is the most complicated part of the stack.
  • A service is a business action. If a controller needs to do multiple actions, each of those actions can be described in separate services.
  • Finally, the data access methods allow the API to interface with a data store. It’s a level of abstraction so that we’re not making direct database calls except in a thin layer (which could be swapped out / modified with a change to the data layer).

This has already gone through a number of iterations and I’m sure I’m not done, but I particularly liked the distinction I made between a controller and service as the logic vs an action. Once I arrived there, the entire framework felt right.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!