How to Generate API Routes Easily and Error-Free with api-route-builder

Alexandre PENOMBRE
3 min readApr 21, 2024

--

Today we’re going to address a common issue encountered by everyone when interacting with APIs: writing routes!

Whether you’re coding with React, Angular, or any other framework and need to make API calls, this article might be helpful.

How do we usually write our routes?

Typically, we manually concatenate all parameters in the route, ensuring to avoid typing errors:

const categoryId = 'tech';
const sortBy = 'date';
const order = 'desc';
const endpoint = `http://example.com/api/posts/${categoryId}?sortBy=${sortBy}&order=${order}`;

fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Post',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
})
}).then(response => {
// Response handling
}).catch(error => {
// Error handling
});

This block looks like something I often see in projects, especially the lines:

const categoryId = 'tech';
const sortBy = 'date';
const order = 'desc';
const endpoint = `http://example.com/api/posts/${categoryId}?sortBy=${sortBy}&order=${order}`;

Or even this one:

const groupId = '5678';
const query = 'role=admin';
const endpoint2 = `http://example.com/api/groups/${groupId}/members?${query}`;

So, I ask myself: what happens when the query parameters are optional?

Do we use conditions before generating the variable?

We agree:

  • it’s tedious 🥱
  • we repeat ourselves whenever two blocks use the same endpoint 😵‍💫
  • manually writing URLs risks typos 😵
  • we have no control over what the developer types, so there’s no control over whether they enter an existing URL 😓

In this case, we’re not following the principles of KISS or DRY.

I thought to myself, I don’t want to repeat these lines to craft my routes every time I need them, and I thought of a simple solution to have control, leverage the power of Typescript, generate route params effortlessly, as well as query params.

I created api-route-builder, a library that removes this complexity for you. Whether you’re in frontend or backend, it doesn’t matter, just follow along…

Automatically generate our API routes

Let’s start by installing it, to go to npm page, click here.

npm install api-route-builder
# or
yarn add api-route-builder

The principle is simple, we start by declaring our routes in a file that will serve as a library:

// src/libs/apiRoutes.ts
import { buildRoutes } from "api-route-builder";

// Define your route paths
type RoutePath = "UsersList" | "UserGet" | "GroupJoin";

type Paths = {
[K in RoutePath]: string;
};

const paths: Paths = {
UsersList: "/users",
UserGet: "/users/:userId",
GroupJoin: "/groups/:groupId/join",
};

export default buildRoutes<RoutePath>("http://localhost:3000", paths);

How to use the api-route-builder library?

Then in use:

apiRoutes.UserGet({ userId: "95dbd66e-c548-4d83-9aca-6087d27e1a87" });

apiRoutes.UsersList(null, { limit: 50, offset: 25 });

Beyond just generating routes easily, we mainly want to benefit from Typescript autocomplete.

The strength of the tool lies in doing nothing by hand, except passing the variables.

Why it will save you from errors

Hoping this keeps you away from typing errors. 😋

See you soon and happy coding! 😉

--

--

Alexandre PENOMBRE

Tech Enabler, Typescript Expert Freelance @TheFork By TripAdvisor #Typescript #React #WorkflowAutomation