REST API using Deno

In my last article, Deno - A First Look we have discussed a basic understanding of Deno. Haven’t checked out? Just have it once. I am waiting here, dude!
.
.
.
Finished? Great. Well, I hope you are now comfortable and want to know more about Deno. Especially how we build our fist application. Right? Let’s start building a simple REST API using DENO.
Step1: Application Structure
Since we are building a very very simple REST API, lets maintain the simplicity. So, first, we need to start the server or start the application then for API endpoints we need routers and finally the controller to define its functionality that's it.
app.ts
router.ts
controller.ts
Step2: Choose a web framework
You may be heard of Express.Js in NODE. If not no worries, it’s a popular web framework. Here in Deno, we will use a web framework thatis called Oak, and it is inspired by Koa.
Step3: Let’s set up a localhost server
Just create an app.ts file and simply import Application from https://deno.land/x/oak/mod.ts and setup the port that's it.
import{ Application } from 'https://deno.land/x/oak/mod.ts'
const port = 8000
console.log(`Wow! The server is running at port ${port}`)
Now execute the app.ts
deno run --allow-net app.ts
Step4: set up routes
Well, the server is ready to work now so we have to focus on the next part that is the routing part. Let’s create a new file called router.ts and declare all routing endpoints. Seebelow...
import{ Router} from'https://deno.land/x/oak/mod.ts';
import{ getEmployees, getEmployee, addEmployee, updateEmployee, deleteEmployee } from'./controller.ts';
const router= newRouter();
router.
get('/employees', getEmployees).
get('/employee/:empId', getEmployee).
post('/employee', addEmployee).
put('/employee/:empId', updateEmployee).
delete('/employee/:empId', deleteEmployee)
export default router;
You might get confused with the functions written in routes. You will find all of them in controllers.ts
Now back to app.ts and use router through import. See the complete app.ts code below.
import{ Application} from'https://deno.land/x/oak/mod.ts';
import router from'./router.ts';
const PORT = 8000;
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log(`Wow! The server is running at port ${PORT}`)
await app.listen({port:PORT});
Step5: Let’s create the controller
First we need to hold the interface of the employee table
interfaceEmployees {
empId:string;
deptName:string;
designation:string;
}
We can separate this interface part to a separate TS file as model but to make it simple we will continue with this controller file.Now we will initialize the array of the employee
let employees: Array<Employees>=
[{
empId:"1",
deptName:"Growth",
designation:"Sr. Developer"
},{
empId:"2",
deptName:"ACE",
designation:"Pro. Developer"
},{
empId:"3",
deptName:"Growth",
designation:"BDM"
},{
empId:"4",
deptName:"ACE",
designation:"ADM"
},{
empId:"5",
deptName:"Bench",
designation:"Trainee Developer"
}]
And finally, we create all the routing methods here one by one...
getEmployees We can find all employee details by simply requesting /employees
const getEmployees = ({ response}: { response: any}) => { response.body= employees }
Now check here
getEmployee We can fetch all employees details to the main employee list. So we request a post method and the endpoint would be /employee:id
const getEmployee = ({ params,response }: { params:{ empId: string}; response: any}) => {
const employee: Employees| undefined =searchEmpByEmpId(params.empId)
if(employee) {
response.status= 200
response.body= employee
}else {
response.status= 404
response.body= { message: 'Employeenot found.' }
}
}
Now check here
addEmployee We can add any employee’s details to the main employee list. So we request a post method and the endpoint would be /employee
const addEmployee = async({ request, response}: { request: any;response: any}) => {
const body = await request.body()
const employee: Employees = body.value
employees.push(employee)
response.body= { message: 'OK'}
response.status= 200
}
Now check here
updateEmployee We can update any employee’s details by its employee id. So we request a put method and the endpoint would be /employee:id
const updateEmployee = async({ params, request,response }: { params:{ empId: string}; request: any;response: any}) => {
let employee: Employees| undefined =searchEmpByEmpId(params.empId)
if(employee) {
const body = await request.body()
const updateInfos: { deptName?:string; designation?:string } = body.value
employee= { ...employee, ...updateInfos}
employees= [...employees.filter(employee=> employee.empId!== params.empId),employee]
response.status= 200
response.body= { message: 'OK'}
}else {
response.status= 404
response.body= { message: `Employeenot found` }
}
}
Now check here
deleteEmployee We can delete any employee’s details by its employee id. So we requesta delete method and the endpoint would be /employee:id
const deleteEmployee = ({ params,response }: { params:{ empId: string}; response: any}) => {
employees= employees.filter(employee=> employee.empId!== params.empId)
response.body= { message: 'OK'}
response.status= 200
}
Now check here
You have to add the search method as below
const searchEmpByEmpId = (empId: string): ( Employees | undefined ) => employees.filter(employee => employee.empId === empId )[0]
At the end of your controller.ts you need to export all the methods so that router.ts can import them.
export{ getEmployees, getEmployee,addEmployee, updateEmployee,deleteEmployee }
Now its time to execute the whole thing, so simply run the below command
deno run --allow-net app.ts
Summary
We are now happy to see a complete guide on Deno REST API. Is it useful to you? If so, please leave a comment at info@codinghub.net and share this article as much as you can. Thank you very much!
We are on Facebook, Twitter, LinkedIn, Medium, Quora, Instagram, etc.
By the way, want to learn more about Deno? Just check out the official Deno documentation.