Create rest API quickly with Axe API framework: Part 4

Pavel Salauyou
5 min readOct 10, 2023

--

In the previous article, we looked at how to organise relationships in models and how to query them, as well as exploring how to sort and filter data in the API. In this article, we’ll take a closer look at data queries, as well as another important functionality such as hooks.

More about querying data

No doubt, having a flexible API and the ability to get data whenever you want is very convenient. In this section, we’ll discuss the advantages of Ax API projects and how they can help you.

When you query data on APIs, you’re basically asking the server for specific information by using a special URL with instructions. These instructions, like filters or search criteria, tell the server what data you want.

Once the server gets your request, it sends back the data you asked for. Querying helps you get exactly what you need from the API, which saves time and resources.

This way of getting data allows your apps to interact with the server effectively, giving you the power to customize and manipulate the data as you need it.

Axe API query features

The Axe API already has all the necessary query features built-in, and you don’t have to do anything extra to use them. It works effortlessly without any effort on your part.

In the previous article we already made an API request that returned only certain fields, let’s make an http request to the menu and return only one name field, http://localhost:3000/api/v1/menus?fields=name. As a result, we see:

{
"data": [
{
"name": "Launch"
},
{
"name": "Regular"
}
],
"pagination": {
"total": 2,
"lastPage": 1,
"prevPage": null,
"nextPage": null,
"perPage": 10,
"currentPage": 1,
"from": 0,
"to": 2
}
}

We used the “fields” parameter to choose specific fields from the endpoint, and the response only showed those selected fields.

This is a basic example to show how it functions. There are many other query features that HTTP clients can make use of.

Other query features

You have a wide range of query features available for use:

Selecting fields

Query params: ?fields=id,name

http://localhost:3000/api/v1/menus?fields=id,name

Sorting items by multiple fields:

Query params: ?sort=id,name

http://localhost:3000/api/v1/menus?sort=id,name

Sorting items by descending Z-A: ?sort=-name, just add minus before field name.

http://localhost:3000/api/v1/menus?sort=-name

Pagination

Deciding the record per page: ?per_page=25

http://localhost:3000/api/v1/menus?per_page=25

Fetching the current page: ?page=10

http://localhost:3000/api/v1/menus?page=10

The coolest thing is that even if such a page does not exist, the pagination will be built correctly without any errors.

Filtration

Query items by where conditions:

Query params: ?q={"name":"John"}

http://localhost:3000/api/v1/menus?q={"name":"Regular"}

Query items by multiple conditions (AND condition):

Query params: ?q=[{"menu_id":1},{"price":22}]

http://localhost:3000/api/v1/menu-items?q=[{"menu_id":1},{"price": 22}]

Query items by different operators:

Query params: ?q={"price.$in":[2,5]}

Find price greater then 20 — http://localhost:3000/api/v1/menu-items?q={"price.$gt":20}

Find multiple menu items with identifiers 2, 5: http://localhost:3000/api/v1/menu-items?q={"price.$in":[2, 5]}

Axe api supports many operators equivalent to mysql where operators, the full list can be seen in the table:

Fetching related data:

Query params: ?with=menu{name,description}

Find menu items and fetch related menu with name and description:

http://localhost:3000/api/v1/menu-items?with=menu{name,description}

All these query features are already enabled by default, the developer does not need to do anything at all. See more about queries in API documentation https://axe-api.com/reference/queries-q.html.

Adding hooks

In programming, hooks are like entry points or triggers that allow developers to change how a program behaves without changing its original code. They help to add new features or modify existing ones in a flexible and organized way. Hooks can be used to intercept specific events or actions and apply custom actions or changes to them. They make it easier to customize software without directly modifying the underlying code.

The Axe API can analyze your models, create routes, and handle HTTP requests. However, the real programming is more complicated.

Until now, we’ve only seen the amazing features of the Axe API. But as developers, we should be able to customize the APIs. For example, we might want to protect user passwords, send welcome emails, or perform other checks. Luckily, the Axe API supports hooks and events that let us add our own custom logic to every HTTP request.

Almost every web application needs to store users and these users should have encrypted passwords. Now we have the user password in the public domain and it is strictly forbidden to do this in real web applications. Let’s use hooks to automatically encrypt the password.

How it will work? In the directory app/v1/Hooks we will create a file with a function (hook), which will track post http request and encrypt the password using the crypto library bcrypt. As a result, every new user will be logged into the database with an encrypted password

First, we need to install some required tools:

npm i --save bcrypt
npm i --save-dev @types/bcrypt

After you’ve finished the previous steps, all you need to do is add the following hook to your project:

app/v1/Hooks/User/onBeforeInsert.ts

import bcrypt from 'bcrypt';
import { IHookParameter } from 'axe-api';

export default async ({ formData }: IHookParameter) => {
formData.password = bcrypt.hashSync(formData.password, 10);
};

Let’s have a look at the created file, this file was created in the User directory, it means that the hook will be applied to the User model and also the name of the file determines the hook that will be called in our case will be called hook onBeforeInsert. simply put the function will be called, which does something before writing the user to the database.

Let’s add a new user to the database via the API:

curl \
-d '{"email": "christina.barber@example.com", "firstName": "Christina", "lastName":"G. Barber", "password": "111111"}' \
-H "Content-Type: application/json" \
-X POST http://localhost:3000/api/v1/users

We will not be able to see the added password through our API, because we have added the password field to the hiddens property of the User model. The only way to see the encrypted password is to go to the database and make a selection on the users table:

SELECT * FROM users;

Don’t forget to completely restart the server after adding the file.

Conclusion

In this article we have learnt how to make complex queries for data selection and filtering, as well as added a basic hook for password encryption. In the next article we will learn in more detail what other Axe Api hooks there are and consider them by examples.

--

--