Using Fedora to implement REST API in JavaScript: part 2

In part 1 previously, you saw how to quickly create a simple API service using Fedora Workstation, Express, and JavaScript. This article shows you the simplicity of how to create a new API. This part shows you how to:

  • Install a DB server
  • Build a new route
  • Connect a new datasource
  • Use Fedora terminal to send and receive data

Generating an app

Please refer to the previous article for more details. But to make things simple, change to your work directory and generate an app skeleton.


$ cd our-work-directory
$ npx express-generator –no-view –git /myApp
$ cd myApp
$ npm i

Installing a database server

In this part, we’ll install MariaDB database. MariaDB is the Fedora default database.

$ dnf module list mariadb | sort -u ## lists the streams available
$ sudo dnf module install mariadb:10.3 ##10.4 is the latest

Note: the default profile is mariadb/server.

For those who need to spin up a Docker container a ready made container with Fedora 31 is available.

$ docker pull registry.fedoraproject.org/f31/mariadb
$ docker run -d --name mariadb_database -e MYSQL_USER=user -e MYSQL_PASSWORD=pass -e MYSQL_DATABASE=db -p 3306:3306 registry.fedoraproject.org/f31/mariadb

Now start the MariaDB service.

$ sudo systemctl start mariadb

If you’d like the service to start at boot, you can also enable it in systemd:

$ sudo systemctl enable mariadb ## start at boot

Next, setup the database as needed:

$ mysql -u root -p ## root password is blank
MariaDB> CREATE DATABASE users;
MariaDB> create user dbuser identified by ‘123456‘;
MariaDB> grant select, insert, update, create, drop on users.* to dbuser;
MariaDB> show grants for dbuser;
MariaDB> \q

A database connector is needed to use the database with Node.js.

$ npm install mariadb ## installs MariaDB Node.js connector

We’ll leverage Sequelize in this sample API. Sequelize is a promise-based Node.js ORM (Object Relational Mapper) for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server.

$ npm install sequelize ## installs Sequelize

Connecting a new datasource

Now, create a new db folder and create a new file sequelize.js there:

const Sequelize = require('sequelize'),
  sequelize = new Sequelize(process.env.db_name || 'users', process.env.db_user || 'dbuser', process.env.db_pass || '123456', {
    host: 'localhost',
    dialect: 'mariadb',
    ssl: true
})

module.exports = sequelize

Note: For the sake of completeness I‘m including a link to the related Github repo: https://github.com/vaclav18/express-api-mariadb

Let‘s create a new file models/user.js. A nice feature of a Sequelize model is that it helps us to create the necessary tables and colums automatically. The code snippet responsible for doing this is seen below:

sequelize.sync({
force: false
})

Note: never switch to true with a production database – it would drop your tables at app start!

We will refer to the earlier created sequelize.js this way:

const sequelize = require('../db/sequelize')

Building new routes

Next, you’ll create a new file routes/user.js. You already have routes/users.js from the previous article. You can copy and paste the code in and proceed with editing it.

You’ll also need a reference to the previously created model.

const User = require('../models/user')

Change the route path to /users and also create a new post method route.

Mind the async – await keywords there. An interaction with a database will take some time and this one will do the trick. Yes, an async function returns a promise and this one makes promises easy to use.

Note: This code is not production ready, since it would also need to include an authentication feature.

We‘ll make the new route working this way:

const userRouter = require('./routes/user')
app.use(userRouter)

Let‘s also remove the existing usersRouter. The routes/users.js can be deleted too.

$ npm start

With the above command, you can launch your new app.

Using the terminal to send and retrieve data

Let’s create a new database record through the post method:

$ curl -d 'name=Adam' http://localhost:3000/users

To retrieve the data created through the API, do an HTTP GET request:

$ curl http://localhost:3000/users

The console output of the curl command is a JSON array containing data of all the records in the Users table.

Note: This is not really the usual end result — an application consumes the API finally. The API will usually also have endpoints to update and remove data.

More automation

Let‘s assume we might want to create an API serving many tables. It‘s possible and very handy to automatically generate models for Sequelize from our database. Sequelize-auto will do the heavy lifting for us. The resulting files (models.js) would be placed and imported within the /models directory.

$ npm install sequelize-auto

A node.js connector is needed to use this one and we have it already installed for MariaDB.

Conclusion

It‘s possible to develop and run an API using Fedora, Fedora default MariaDB, JavaScript and efficiently develop a solution like with a noSQL database. For those used to working with MongoDB or a similar noSQL database, Fedora and MariaDB are important open-source enablers.


Photo by Mazhar Zandsalimi on Unsplash.

For Developers For System Administrators

12 Comments

  1. Ilis

    Is there any reason to use JS if you can use dotnet?

    • Sebastiaan Franken

      dotnet is a Windows / Microsoft technology, and not all of it is ported to Linux by Microsoft yet, as far as I’m aware. Why not use PHP?

      • Ondrej

        Why not use Python? There is so many options from the techstack. I am personally writing this in Python, because I like the language, the ecosystem, etc.

        Javascript has this huge advantage, that you can use some of the code on the backend and on the frontend (like f.e. content validation). Disadvantegees? Javascript is a monkey language with some weird behaviour, which is only clear if you do it for a long time

        • IAmKing

          Why not use Rust? Why make it crawl, when you can make it fly?

          • Backend apps written in JavaScript are usually fast enough for practical use. Also frontend apps (like single page applications) are quite zippy. A Smart TV is mostly not the fastest device (comparing to a slow office laptop) and JavaScript itself never caused any visible performance issue. I was tweaking smart TV apps and bottlenecks were never caused by a programming language itself (backend or frontend parts). As for Node.js – “your programming language” can be added to a node.js project when performance matters. Would you share your solution too?

      • You undoubtedly need to develop in JavaScript too, don’t you? The idea is to use one main programming language for front end and backend. Some people say that PHP is easier to learn (your framework may take much longer time to master). If you mainly maintain a large LAMP stack project (typically an e-commerce site or any existing profitable service) then you are probably happy with PHP. Some pros of Express / Node.js: very good for real-time apps like streaming or instant messaging, projects with heavy data load, single page applications

        • Yuuko

          Dart? one normal and simply typed language for mobile, web & backend

          • Dart is new enough to make any consideration now. Looking at Flutter: Well, the web part is still in beta – a simple boilerplate app that makes a GET request compiles to a 1MB JavaScript file (minified) excluding html and other assets. It requires Chrome browser as a device to build a web app (I built a Flutter web app). Ionic is more flexible in terms of browser selection (Safari, Firefox, Edge). Will probably populate an API using Dart later.

            • Yuuko

              AngularDart?

              Flutter, beta, compiles to PWA like application,
              Flutter runtime minimal size: native ~4+- MB, js 200-800KB

              Dart has tree shaking, and supports partial loading.

  2. First of all I want to say great blog! I had a quick question in which I’d like to ask if you don’t mind.
    I was curious to find out how you center yourself and
    clear your head before writing. I have had difficulty clearing my mind in getting my ideas out.
    I do take pleasure in writing however it just seems like the first 10 to 15 minutes tend to
    be lost simply just trying to figure out how
    to begin. Any ideas or tips? Appreciate it!

  3. Vaclav

    Can you use Fedora to develop, deploy and run it? I think it’s partly possible only but am rather skeptical about running and debugging a dotnet in a browser.
    JavaScript gained more traction and is being increasingly used on the back-end.
    Please share your experience and thoughts about your reasons to use what you use.

  4. Hey there, You’ve done an excellent job. I’ll certainly digg
    itt and personally recommend tto my friends.I’m sure they will be benefited from
    this site.

Comments are Closed

The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat. Fedora Magazine aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. The Fedora logo is a trademark of Red Hat, Inc. Terms and Conditions