{"id":113068,"date":"2020-05-18T08:00:00","date_gmt":"2020-05-18T08:00:00","guid":{"rendered":"https:\/\/fedoramagazine.org\/?p=31061"},"modified":"2020-05-18T08:00:00","modified_gmt":"2020-05-18T08:00:00","slug":"using-fedora-to-implement-rest-api-in-javascript-part-2","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/05\/18\/using-fedora-to-implement-rest-api-in-javascript-part-2\/","title":{"rendered":"Using Fedora to implement REST API in JavaScript: part 2"},"content":{"rendered":"<p>In <a href=\"https:\/\/fedoramagazine.org\/using-fedora-to-quickly-implement-rest-api-with-javascript\/\">part 1<\/a> 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:<\/p>\n<ul>\n<li>Install a DB server<\/li>\n<li>Build a new route<\/li>\n<li>Connect a new datasource<\/li>\n<li>Use Fedora terminal to send and receive data<\/li>\n<\/ul>\n<p> <span id=\"more-31061\"><\/span> <\/p>\n<h2>Generating an app<\/h2>\n<p>Please refer to the <a href=\"https:\/\/fedoramagazine.org\/using-fedora-to-quickly-implement-rest-api-with-javascript\/\">previous article<\/a> for more details. But to make things simple, change to your work directory and generate an app skeleton.<\/p>\n<pre class=\"wp-block-code\"> <div class=\"codecolorer-container text default\" style=\"overflow:auto;border:1px solid #9F9F9F;width:435px\"><div class=\"text codecolorer\" style=\"padding:5px;font:normal 12px\/1.4em Monaco, Lucida Console, monospace\">$ cd our-work-directory<br \/>\n$ npx express-generator \u2013no-view \u2013git \/myApp<br \/>\n$ cd myApp<br \/>\n$ npm i<\/div><\/div> <\/pre>\n<h2>Installing a database server<\/h2>\n<p>In this part, we&#8217;ll install MariaDB database. MariaDB is the Fedora default database.<\/p>\n<pre class=\"wp-block-preformatted\">$ dnf module list mariadb | sort -u ## lists the streams available\n$ sudo dnf module install mariadb:10.3 ##10.4 is the latest<\/pre>\n<p><em>Note: the default profile is mariadb\/server<\/em>.<\/p>\n<p>For those who need to spin up a Docker container a ready made container with Fedora 31 is available.<\/p>\n<pre class=\"wp-block-preformatted\">$ docker pull registry.fedoraproject.org\/f31\/mariadb<br \/>$ 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<\/pre>\n<p>Now start the MariaDB service.<\/p>\n<pre class=\"wp-block-preformatted\">$ sudo systemctl start mariadb<\/pre>\n<p>If you&#8217;d like the service to start at boot, you can also enable it in systemd:<\/p>\n<pre class=\"wp-block-preformatted\">$ sudo systemctl enable mariadb ## start at boot<\/pre>\n<p>Next, setup the database as needed:<\/p>\n<pre class=\"wp-block-preformatted\">$ mysql -u root -p ## root password is blank\nMariaDB&gt; CREATE DATABASE users;\nMariaDB&gt; create user dbuser identified by \u2018123456\u2018;\nMariaDB&gt; grant select, insert, update, create, drop on users.* to dbuser;\nMariaDB&gt; show grants for dbuser;\nMariaDB&gt; \\q<\/pre>\n<p>A database connector is needed to use the database with Node.js.<\/p>\n<pre class=\"wp-block-preformatted\">$ npm install mariadb ## installs MariaDB Node.js connector<\/pre>\n<p>We\u2019ll 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.<\/p>\n<pre class=\"wp-block-preformatted\">$ npm install sequelize ## installs Sequelize<\/pre>\n<h2>Connecting a new datasource<\/h2>\n<p>Now, create a new <em>db<\/em> folder and create a new file <em>sequelize.js<\/em> there:<\/p>\n<pre class=\"wp-block-preformatted\">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\n}) module.exports = sequelize<\/pre>\n<p><em>Note: For the sake of completeness I\u2018m including a link to the related Github repo: <a href=\"https:\/\/github.com\/vaclav18\/express-api-mariadb\">https:\/\/github.com\/vaclav18\/express-api-mariadb<\/a><\/em><\/p>\n<p>Let\u2018s create a new file <em>models\/user.js<\/em>. 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:<\/p>\n<pre class=\"wp-block-preformatted\">sequelize.sync({\nforce: false\n})<\/pre>\n<p>Note: never switch to true with a production database \u2013 it would<em> drop your tables at app start<\/em>!<\/p>\n<p>We will refer to the earlier created sequelize.js this way:<\/p>\n<pre class=\"wp-block-preformatted\">const sequelize = require('..\/db\/sequelize')<\/pre>\n<h2>Building new routes<\/h2>\n<p>Next, you&#8217;ll create a new file <em>routes\/user.js<\/em>. You already have <em>routes\/users.js<\/em> from the previous article. You can copy and paste the code in and proceed with editing it.<\/p>\n<p>You&#8217;ll also need a reference to the previously created model.<\/p>\n<pre class=\"wp-block-preformatted\">const User = require('..\/models\/user')<\/pre>\n<p>Change the route path to <em>\/users<\/em> and also create a new <strong>post<\/strong> method route.<\/p>\n<p>Mind the async \u2013 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.<\/p>\n<p><em>Note: This code is not production ready, since it would also need to include an authentication feature.<\/em><\/p>\n<p>We\u2018ll make the new route working this way:<\/p>\n<pre class=\"wp-block-preformatted\">const userRouter = require('.\/routes\/user')\napp.use(userRouter)<\/pre>\n<p>Let\u2018s also remove the existing <em>usersRouter<\/em>. The <em>routes\/users.js<\/em> can be deleted too.<\/p>\n<pre class=\"wp-block-preformatted\">$ npm start<\/pre>\n<p>With the above command, you can launch your new app.<\/p>\n<h2>Using the terminal to send and retrieve data<\/h2>\n<p>Let&#8217;s create a new database record through the post method:<\/p>\n<pre class=\"wp-block-preformatted\">$ curl -d 'name=Adam' http:\/\/localhost:3000\/users<\/pre>\n<p>To retrieve the data created through the API, do an HTTP GET request:<\/p>\n<pre class=\"wp-block-preformatted\">$ curl http:\/\/localhost:3000\/users<\/pre>\n<p>The console output of the curl command is a JSON array containing data of all the records in the <em>Users<\/em> table.<\/p>\n<p><em>Note: This is not really the usual end result &#8212; an application consumes the API finally. The API will usually also have endpoints to update and remove data.<\/em><\/p>\n<h2>More automation<\/h2>\n<p>Let\u2018s assume we might want to create an API serving many tables. It\u2018s 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 (<em>models.js<\/em>) would be placed and imported within the <em>\/models<\/em> directory.<\/p>\n<pre class=\"wp-block-preformatted\">$ npm install sequelize-auto<\/pre>\n<p>A node.js connector is needed to use this one and we have it already installed for MariaDB.<\/p>\n<h2>Conclusion<\/h2>\n<p>It\u2018s 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.<\/p>\n<hr class=\"wp-block-separator\" \/>\n<p><em>Photo by\u00a0<a href=\"https:\/\/unsplash.com\/@m47h4r?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Mazhar Zandsalimi<\/a>\u00a0on\u00a0<a href=\"https:\/\/unsplash.com\/s\/photos\/javascript?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Unsplash<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[48],"tags":[971,913,1020,45,42,43,974,46,1021,1022,47,1023,1024],"class_list":["post-113068","post","type-post","status-publish","format-standard","hentry","category-fedora-os","tag-api","tag-database","tag-express-js","tag-fedora","tag-for-developers","tag-for-system-administrators","tag-javascript","tag-magazine","tag-mariadb","tag-mysql","tag-news","tag-node-js","tag-nosql"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/113068","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=113068"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/113068\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=113068"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=113068"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=113068"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}