Move your API outside your application

Fixing mistakes of my previous post

Your API layer when you move all app logic to it

Not so far I published a post about the most common mistake of writing API requests and showed some features of Apicase. You can read it here.

After this, I got one fair remark. As I said at the end, handling API requests inside services makes your API layer inflexible and inseparable from the application.

It’s not good, BUT… we can fix it! So, I won’t take a lot of your time.

What we have

Imagine we have API layer like this one:

Why is it bad?

We can’t use this API layer in another application because it depends on app structure too much. As Roma Sabirov and some guys from reddit noted — API shouldn’t know about your application.

#1 and #4. Connect store to API layer directly makes it impossible to use in another application

#2 and #3. Getting data from side and setting to it may cause problems too. What if our another application uses token too and it differs from token required by API?

I always was a hater of un-reusable code so I’m gonna hate my previous post BUT… Not at all. Because we can go another way.

How we can fix it?

We need to just remove all side bindings from our API layer.

Clear API tree will look like:

Pretty and clean, even cleaner than I wanted

– But why do we need Apicase? We can just put raw json and wrap it into fetch? And where we’ll handle our API? Back to store and cross out all your advices?

NO. You still can handle your API in API layer, but a little elsewhere.

We will import our API and add listeners remotely:

Now we need to return our store binding and authorization, so we can do it:

Now we can move our apis/tree.js outside our application, for example, to @myorg/api package and use it in all of our apps.

What we may improve?

In our apis/tree.js we can add some API-specific checks that don’t depend on API. For example, we can add payload validation:

And, the most important thing is you don’t need to write API in your application code. Only business logic and work with API like it’s just a library with some methods.

TODO

Auto-generation of API based on schemas, docs or smth another (e.g. swagger)

Add opportunity to define converter callbacks for services to reduce requests code

Write some (built-in?) testing/validation tools

If you still haven’t tried Apicase — time to fix it!

Good luck ;)