DEV Community

Cover image for Create REST API with MySQL using DENO secured Javascript Lib
Abhay Kochar
Abhay Kochar

Posted on

Create REST API with MySQL using DENO secured Javascript Lib

Deno js

Deno is a Secure Runtime for Javascript and TypeScript

In this tutorial we will learn how to do

  1. Deno Installation
  2. Running HTTP Server on Deno
  3. Routing using Oak Middleware
  4. How to connect to MySQL Database
  5. REST API with Database Connection

If you prefer YouTube :

1. Deno Installation

Deno ships as a single executable and doesn’t require any dependencies.

We will install it using these shell commands, which can be found on https://deno.land

Run following command on terminal
Shell (Mac, Linux):

$ curl -fsSL https://deno.land/x/install/install.sh | sh

PowerShell (Windows):

> iwr https://deno.land/x/install/install.ps1 -useb | iex

You can verify if deno installed correctly or not using following command

deno -V

If you have deno already installed you can upgrade that using

deno upgrade

Now lets install Deno Extension for VScode.

You can browse and install extensions from within VS Code. Bring up the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of VS Code or the View: Extensions command (⇧⌘X).

Search for Deno Extension and Install it.

2. Running HTTP Server

To run HTTP Server on deno, use the following code.

import { serve } from "https://deno.land/std/http/server.ts";
const s = serve({ port: 8000 });

console.log('Http Server started. Press Ctrl + C to stop');

for await (const req of s) {
 req.respond({ body: "Hello World\n" });
}

Save this file as http-server.ts or any name of your choice.

Now lets run this file using

deno run --allow-net http-server.ts

Open http://localhost:8000/

3. Routing using Oak Middleware

We will be using Oak a middleware framework for Deno's http server, including a router middleware.

import {Application, Router} from "https://deno.land/x/oak/mod.ts";

const app = new Application();
const router = new Router();

const books = new Map([[ 1, 'one' ],[ 2, 'two' ],[3,'three']]);

router
.get('/',(context)=>{
   context.response.body = 'I am at homepage';
})
.get('/about',(context)=>{
   context.response.body = 'This is about page';
});

app.use(router.routes());

await app.listen({ port: 80 });

Now let's switch to browser and check if that works ?

http://localhost/

http://localhost/about

In routing you will need to pass parameters in url


.get('/book/:id',(context)=>{
context.response.body = 'Book name:\n';
    context.response.body += books.get(Number(context.params.id));
})

http://localhost/book/2

This way we can pass parameters in URL.

You can find more information about Oak on https://deno.land/x/oak/

MySQL

4. Connecting to MySQL Database

Now let’s see how we can connect to mysql database

We will be using third party module: MySQL and MariaDB (5.5 and 10.2+) database driver for Deno.

import { Client } from "https://deno.land/x/mysql/mod.ts";
const client = await new Client().connect({
hostname: "127.0.0.1",
username: "root",
password: "password",
});
await client.execute("CREATE DATABASE IF NOT EXISTS webgile");
await client.execute("USE webgile");

I have installed MySQL on my localhost with above details

await client.execute(`
   CREATE TABLE IF NOT EXISTS books (
       id int(11) NOT NULL AUTO_INCREMENT,
       name varchar(100) NOT NULL,
       PRIMARY KEY (id)
   );
`);

As we have created table in mysql, lets insert some data in that.

let result = await client.execute(`INSERT INTO books(name) values(?)`, ["My Book One"]
);
console.log(result);

const books_all = await client.query(select * from books);
console.log(books_all);

You can pass parameters in query as follows

const book = await client.query(
 "select * from books where id = ?",[3]
);
console.log(book);

await client.close();

REST <br>
API

5. REST API Example with Database

Lets combine REST API and MySQL database code


import {Application, Router} from "https://deno.land/x/oak/mod.ts";
import { Client } from "https://deno.land/x/mysql/mod.ts";

const client = await new Client().connect({
hostname: "127.0.0.1",
username: "root",
password: "password",
});
await client.execute("USE webgile");

const app = new Application();
const router = new Router();

app.use(router.allowedMethods());
app.use(router.routes());

router
.get('/',(context)=>{
   context.response.body = 'I am at homepage';
})
.get('/books',async (context)=>{
   const books_all = await client.query("select * from books");
   context.response.body = books_all;
})
.get('/book/:id',async (context)=>{

   const book = await client.query(
       "select * from books where id = ?",
       [Number(context.params.id)]
      );
      console.log(book);
   context.response.body = book;
})
.post('/book/add',async (context)=>{
   if(await context.request.hasBody)
   {
       var body = await context.request.body();
       var data = body.value;
       let result = await client.execute(`INSERT INTO books(name) values(?)`, [data.name]);
       console.log(result);
       context.response.body = {"message":"Success","error":0};
   }
   else{
       context.response.body = {"message":"Invalid Request","error":1};
   }
});


await app.listen({ port: 80 });

To verify book/add method you can use Postman to sent POST request.

Post URL : http://localhost/book/add

With RAW data

{“name”:”Book name”}

You can find all these files on this link

Deno Installation
How to Run HTTP Server on Deno ?
How to do Routing using Oak Middleware on Deno ?
How to connect to MySQL Database in Deno ?
How to build REST API with MySQL on Deno ?

Top comments (0)