Message:

Subscribe rss
Blog categories
All | Backendless features
How to Build a Light REST Client with JavaScript
March 14, 2019 by Vladimir Upirov

Some Backendless users choose to use REST APIs in their JavaScript projects. While many can simply use our pre-packaged JS-SDK, that SDK may not always be able to achieve the result the user is seeking. Today we’re going to show you how to build a custom and very light API client library for working with Backendless API. Some time ago, we created a simple NPM module named “backendless-request” for sending CRUD requests to the server. That package is used in all our services such as DevConsole, JSCodeRunner, JS-SDK, etc.. If you would like to see the sources of the package, you can find it on Github.

Light REST Client using JavaScript

Setup Backendless

Make sure you have a Backendless developer account. If you do not have one, you can register for a free account at https://develop.backendless.com.

Register for Backendless Developer Account

Create a new Backendless application (you can use a pre-existing application if you have one you’d like to build upon). My application will be called RestApiClient .

Setup a New NPM Module

Let’s create a new directory and call it rest-api-client . Run the following command in your terminal:

Go into the directory and initialize our NPM module.

Leave all settings as default and open the project in a code editor that you’re comfortable with.

Install Backendless Request

As I mentioned at the beginning, we use the package in the all of our JS services, in a NodeJS environment and in a WEB/Browser environment as well, so it’s completely adapted for use everywhere. Also, I want to note that it’s a very light library for making REST requests. The non-minimized build for browsers weighs just 28KB, and the minimized build weighs just 11KB. That sounds good enough, doesn’t it?

Just install the package from NPM by running the following command:

Once it’s installed, we can use the package in our project simply by requiring it:

Generic API Client

As you know, our the main goal is to build a library for making requests to any servers as well as having the ability to have several API clients at the same time. Therefore, we’re going to create a generic API-client class for keeping baseServerPath  and userAuth  settings as well, which will be persistenced in the instance context. Let’s create a new file ./src/client.js  and put the following code in there:

Let’s take a more in-depth look at the class to see what exactly the class contains. In the beginning, in the constructor, we just store the base API path. It may be any base url to our API server such as  http://our-server-host.com/api  or   http://localhost:3000 .

As you can see, the class is simple; in fact, it’s just an additional layer between the client code and a real API request.

In the end, our Client class should look like this:

Let’s take a look at another important item: middleware. Through it, we can decorate any requests before sending them to the server. We will need this a little bit later for setting the user auth header.  

Method addMiddleware  expects two arguments: the first is an optional “method” – REST method ( get , post , put , delete , …)  and handler  for decoration requests before sending. If we want that handler to be applied for all of the requests, we just need to pass to the addMiddleware  method one argument, handler , but in the event that we want that handler to be applied only for specific method – for example, for GET – we should pass both arguments. Below is an example of how to use the addMiddleware  method.

In the code below, we simply create a few API methods and inside every one, we just call the request  method with upgraded path  parameters. After that, our instance will have all of the methods that BackandlessRequest  has.  

The request  method, in turn, will create a new Request , decorate it with middleware, and process it.

User Auth Settings

Most likely, you will need to have the ability to add a user auth header to each request for making the request as authorized.  So let’s add a few lines in our Client class:

  1. In the constructor, we should get key of the auth header and we may already have auth value, so add authHeaderKey  and authHeaderValue  right after the basePath  parameter.
  2. Also, add the following code at the end of the constructor:

  3. And add a new class method:

Now we can easily change the auth state from not-authorized to authorized by calling the setAuth  method and passing a token there that we got from a login  API request.

Backendless API Client

Now it’s time to create an API client for working with Backendless API. First, let’s create a new directory backendless  inside our directory src  and create there a new JS file with the name constants.js  and the following content:

BACKENDLESS_API_HOST  is a host of Backendless API.

BACKENDLESS_AUTH_KEY  is a header key which should be sent with a request if we want to make an authorized request.

Now let’s create the  ./src/backendless/index.js  file with the following content:

As you can see, we don’t have a ./users.js  file yet. Let’s fix that. Create a file with that name and the following code:

There are just three simple methods for user: register , login  and logout . With the register  method, I assume everything is straightforward. Let’s go through other two.

  1. User login  – when the API call is finished successfully, the server returns a  user  object in the response body and there is an additional property, user-token , containing the value we should add to all of the next requests. As you recall, we have a setAuth  method in the Client class, so that’s exactly what we need.
  2. User logout  method – after the user logs out, we just reset user-token  for the client instance.

Let’s do some refactoring and move urls into a separate file called ./src/backendless/urls.js . This gives us more flexibility.

Next we’ll modify the  ./src/backendless/users.js  file a little. When we’re done, the file should look like this:

Now, let’s create a simple service for working with a data table. For this service, we should create a new JS file called ./persons.js  and modify the ./urls.js  and ./index.js  files.

./src/beckandless/urls.js :

./src/beckandless/persons.js :

./src/beckandless/index.js

And finally, create a new index.js  file under the  src  directory:

You can find more REST end points in the our REST Docs to extend your API client for your specific needs.

Test Backendless API Client

Now, let’s see how it will work. For that, we will write a few simple tests. Create a new JS file called ./tests/index.js  with the following content:

Then create another file called ./tests/backendless.js ; don’t forget to replace my appId  and apiKeys  with yours.

Now we can run the file with the command node ./tests , but I’m going to move that into package.json  in the scripts  section:

And now to run the tests, just input and run the command npm run test . Do the test a few times and go to your Backendless Dev Console and you will see that some records have the ownerId  property and some don’t.

Light REST Client using JavaScript

Multi API Clients

You also have the ability to have more than one beckandlessApiClient; just create as many clients as you need and they will work independently of each other.

External API Client

Creating a new API client is almost the same as creating the BackendlessApiClient. Just create a new instance of the Client  class and pass the options that you need: basePath , authHeaderKey  and authHeaderValue .

Conclusion

Today we learned how to create a simple REST API Client using the BackendlessRequest package. We also now know how to easily create a client for working with multiple Backendless apps and how to create a client for external API. The library we created can be used everywhere simply by building it with Webpack and using it in your client application. You can take a look at the source project on Github.

Thanks for reading, I hope the article was helpful for you and see you soon.

Share this post
Tweet about this on TwitterShare on FacebookGoogle+