Create REST API with MySQL using DENO secured Javascript Lib
Tags: javascript, webdev, beginners, tutorial
Published: 2020-06-10 04:26:57


<img src="https://dev-to-uploads.s3.amazonaws.com/i/28hitofsvqhhktfnf1y1.png" alt="Deno js" width="200" border="10" />


***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 : {% youtube 1VtA2Q3w6cY %}

## 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.
```javascript
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.
 
```javascript
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 
```javascript
 
.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/



<img src="https://dev-to-uploads.s3.amazonaws.com/i/38b7e81rw08lsqendfs1.png" alt="MySQL" width="200" border="10" />

##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.

```javascript
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
 
```javascript
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.
 
```javascript
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

```javascript
const book = await client.query(
 "select * from books where id = ?",[3]
);
console.log(book);
 
await client.close();
```
<img src="https://dev-to-uploads.s3.amazonaws.com/i/lr6ewymofkz0mn0prt5k.png" alt="REST 
API" width="200" border="10" />

##5. REST API Example with Database
Lets combine REST API and MySQL database code
```javascript

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

{% github webgile/deno %}


[Deno Installation](https://youtu.be/1VtA2Q3w6cY?t=31)
[How to Run HTTP Server on Deno ?](https://youtu.be/1VtA2Q3w6cY?t=98)
[How to do Routing using Oak Middleware on Deno ?](https://youtu.be/1VtA2Q3w6cY?t=175)
[How to connect to MySQL Database in Deno ?](https://youtu.be/1VtA2Q3w6cY?t=364)
[How to build REST API with MySQL on Deno ?](https://youtu.be/1VtA2Q3w6cY?t=582)