In this tutorial, we will build a simple API Server using Deno, Oak, and MySQL.

Grab the code from Github to understand better.

Prerequistics

You need to have Deno and MySQL installed in your system. To install Deno in Mac or Linux based system, run the following command.

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

In Windows, you can install Deno using Powershell.

iwr https://deno.land/x/install/install.ps1 -useb | iex
  • Deno basics and installation.
  • install MySQL in Mac.

Let’s set up the MySQL.

Setting up MySQL

Assuming you have installed MySQL in your system. Login to MySQL server and create a new database.

Note: Make sure you have created a user in MySQL with no password. Deno MySQL driver is still in WIP and it does not work with password authentication, yet

create database codeforgeek_test;

Then, select the database.

use codeforgeek_test;

Create a new table in the database.

  CREATE TABLE users (
      id int(11) NOT NULL AUTO_INCREMENT,
      name varchar(100) NOT NULL,
      created_at timestamp not null default current_timestamp,
      PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Let’s check out our code.

Deno Server using Oak

Oak is a third-party module to develop HTTP servers in Deno. Oak is inspired by the Koa framework of Node.js.

Here is our Server code.

import { Application } from 'https://deno.land/x/oak/mod.ts'
import router from './routes.ts'
const port = Deno.env.get("PORT") || 3000

const app = new Application()

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

console.log(`Server running on port ${port}`)

await app.listen({ port: +port })

Here is the router code.

import { Router } from 'https://deno.land/x/oak/mod.ts'
import { getUsers, getUser, addUsers, updateUsers, deleteUsers } from './controllers/users.ts'

const router = new Router()

router.get('/api/v1/users', getUsers)
    .get('/api/v1/users/:id', getUser)
    .post('/api/v1/users', addUsers)
    .put('/api/v1/users/:id', updateUsers)
    .delete('/api/v1/users/:id', deleteUsers)

export default router

We specified five routes in the Oak router. Each route calling a specified function that in turn deals with MySQL.

In a controllers folder, we have written all the functions that performs CRUD operations in MySQL database.

#deno #node #mysql #oak #api

How to Build API Server Using Deno, Oak and MySQL
10.70 GEEK