DEV Community 👩‍💻👨‍💻

Cover image for Stop writing API functions

Stop writing API functions

Saeed Mosavat on September 17, 2022

If you are developing a front-end application which uses a back-end with RESTFUL APIs, then you have got to stop writing functions for each and eve...
Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Interesting take on this. I will put you in the right direction: wj-config has a feature called URL Functions. Basically it takes a section of your configuration file and creates URL functions based on the information contained within that section, such as scheme, host, port and root paths.

You can have a config.json like this:

{
    "api": {
        "host": "", // <-- Blank if you want relative URL's.
        "rootPath": "/api",
        "users": {
            "rootPath": "/users",
            "all": "", // so the 'all' URL is /api/users
            "single": "/{userId}" // so the URL is /api/users/{userId}, and {userId} is replaceable
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

And then you write your config.js module and import it. Once imported you have the URL functions good to go.

import config from './config.js';

...
const allUsersUrl = config.api.users.all(); // Just like that.  The 'all' property is converted to a function.
const userId = 123;
const singleUserUrl = config.api.users.single({ userId: userId }); // Yields /api/users/123
// And searching:
const searchUsersUrl = config.api.users.all(null, { firstName: 'john augustus' });
console.log(searchUsersUrl); // Outputs /api/users?firstName=john%20augustus
Enter fullscreen mode Exit fullscreen mode
Collapse
 
saeedmosavat profile image
Saeed Mosavat

Cool. Thanks for the suggestion.
This doesn't give all the functionalities that I have in mind, but I'm sure it has some good ideas in creating the routes. I will definitely dig deeper in its source code.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Agreed. wj-config will provide you with the URL construction. All you need now is to build upon this an API client. You could take a configuration section and assume it will have sub-objects (or sub-sections) with all and single URL's. The sub-object's name is the entity name, while the URL's used with GET, POST, PUT, PATCH and DELETE would provide the common CRUD you want, maybe with friendly names like addNew (uses POST), upsert (uses PUT), etc. You can borrow the function-creation algorithm to create the CRUD functions.

Then all other URL's could create objects with functions for each of the HTTP verbs.

import ApiClient from 'xxx';
import config from './config.js';

const apiClient = new ApiClient(config.api.entities);
export default apiClient;
Enter fullscreen mode Exit fullscreen mode

Consumption:

import apiClient from './apiClient.js';

await apiClient.users.getAll();
await apiClient.users.search({ name: 'brutus caesar' }); // GET to config.api.entities.users.all(null, { name: 'brutus caesar' });
await apiClient.users.addNew({ username: 'webJose', firstName: 'Jose' }); // POST
await apiClient.users.upsert('webJose', { username: 'webJose', firstName: 'Jose' }); // PUT to config.api.entities.users.single({ id: 'webJose' })
await apiClient.users.deactivate.delete({ id: 123 }); // config.api.entities.users.deactivate({ id: 123 });
await apiClient.users.verifyEmail.post({ id: 123, email: 'abc@example.com' }); // config.apip.entities.users.verifyEmail({ id: 123, email: 'abc@example.com' });
Enter fullscreen mode Exit fullscreen mode

That would be fantastic, actually. If you don't make this package, I will for sure. :-)

Thread Thread
 
saeedmosavat profile image
Saeed Mosavat

That's interesting. Thanks.

Collapse
 
ecyrbe profile image
ecyrbe • Edited on

You should take a look at zodios.
You just need to declare your api, and you are ready to go.

Works in both JavaScript and typescript and with autocompletion.

Collapse
 
bartoszkrawczyk2 profile image
Bartosz Krawczyk

There's also ts-rest. I haven't used it, but it looks promising. Inspired by tRPC, but more focused on REST, like zodios.

Collapse
 
saeedmosavat profile image
Saeed Mosavat

Looks interesting. I will give it a try.

Collapse
 
xr0master profile image
Sergey Khomushin • Edited on

Instead of something simple, you created something complex. The complex exponentially increases the probability of bugs. And if you need something that doesn't fit in this "code for everything", you'll add more ifs. I think it's better to use the WET/AHA pattern at the end. IMO

Collapse
 
saeedmosavat profile image
Saeed Mosavat

Well, it's a trade-off and depends on how it is used.
This is meant to be used for a set of standard and similar APIs, not for all APIs in the project. Using unique API functions should be preffered for special cases.

Collapse
 
ryannerd profile image
Ryan Jentzsch

Too much boilerplate for my taste. I cringe any time a complex config file is imported. Nearly impossible to debug.

Collapse
 
saeedmosavat profile image
Saeed Mosavat

Thanks for sharing your opinion. Any suggestion on how to avoid this kind of repeated work with less complexity?

Collapse
 
wee profile image
Jelena Sokic

Weeeeeeeeeeeeeeeee
Image description

Collapse
 
wee profile image
Jelena Sokic

Weeeeeeeeee
Image description

Collapse
 
lico profile image
SeongKuk Han

That's a really good idea. Making consistency for APIs.
I'll try that with react-query.

Collapse
 
saeedmosavat profile image
Saeed Mosavat

It would be a good idea. react-query is the best 😍
I will be happy to see the result

Collapse
 
orubel profile image
Owen Rubel

CRUD does not dictate business logic. And your business logic does not fit neatly into CRUD. If you try to, you are going to overengineer EVERY... SINGLE... TIME.

This is why no professional shop uses RESTful. They use RPC API's.

Collapse
 
saeedmosavat profile image
Saeed Mosavat

Yeah, this is approach is not meant to be used for every API in the project. But, when we have true CRUD APIs, it works really well. For example in most management dashboards, there is a lot of CRUD APIs to just list, create and update some entities.

Collapse
 
akmjenkins profile image
Adam

This is great, but please make sure you actually have a REST API in use everywhere in your application before creating this abstraction. And make sure you don’t try and make this work everywhere, even for the 5% of your API calls that aren’t actually REST

Collapse
 
saeedmosavat profile image
Saeed Mosavat

You're right. It should not be used for EVERY API in the application. It can even be more customized to only generate a subset of the CRUD actions fo an entity to prevent not-availavle actions from existing.

Collapse
 
skmohammadi profile image
skmohammadi

Great article !

Collapse
 
otumianempire profile image
Otu Michael

As a back-end developer I believe that your suggestion actually is right. This way of designing has more advantage compared to the previous.

Collapse
 
sasanazizi profile image
sasan azizi

Interesting idea, thanks

Collapse
 
annie profile image
Annie

Hello, can I reprint and translate your article? I will include a link to the article.

Collapse
 
saeedmosavat profile image
Saeed Mosavat

Yeah, of course

Collapse
 
brunotag profile image
Bruno Tagliapietra • Edited on

The REST + JSON world finally discovers encapsulation, cute <3
reminds me of the code generators we used to run on good ol' WebServices

Collapse
 
saeedmosavat profile image
Saeed Mosavat

Sure. I wanted this to handle data transformation etc, but If you need to make this more static, you can remove those functionalities and create the functions just from a JSON file that describes the APIs. Even some kind of validation could be done with JSON-schema I think.

Collapse
 
zhouyg profile image
zhou-yg

why not auto generate the boilerplates of api function ? I guess the standard api already existing in somewhere before you writing these code.Building a abstract layer about api description make developers reach a consensus

Collapse
 
jefflindholm profile image
Jeff Lindholm

If you are actually using REST not RPC over HTTP (which is what 90% of the 'REST' APIs you see are) then you will lose out on the extra information that comes along with the data etc.
HATEOS or the original REST document are good places to start to see what you would lose.
Now I like abstractions and such, but this also really only works when you can control the front and the back ends...

Collapse
 
bias profile image
Tobias Nickel

on this topic I like to share one of my articles.
restful verbs vs real actions

Collapse
 
jwp profile image
John Peters

The miracles of string interpolation.

Collapse
 
z7pz profile image
z7pz

good point... and you can use classes and i think this is a better approach e.g github.com/z7pz/DD-frontend/blob/m...