DEV Community

Cover image for A very simple REST API built-in Deno using oak 3rd party module
badalkhatri
badalkhatri

Posted on

A very simple REST API built-in Deno using oak 3rd party module

In this post I am going to show simple REST API using Deno (an alternative of Node.js)

I am going to make 2 routes, one for GET request and other is POST request, I have taken an example to get and add users which are stored in an array, we can also store into the database but I want to make this app simple.

For simplicity I have put the whole code in a single file, you can use a modular approach too.

As I am using ‘oak’ 3rd party library we will need to import it first into our file

You can find it on — https://deno.land/x/oak

Alt Text

Application — The Application class wraps the serve() function from the http package.
Router — The Router class produces middleware that can be used with an Application to enable routing based on thepathname of the request.

Let us make an interface for User, as Deno out of the box supports TypeScript

Alt Text

Now let us store dummy data of the user in an array

Alt Text

This can also be fetched from database but that would make this post bit longer

Now as I mentioned above I want to make 2 routes for GET and POST, for that I am going to make 2 functions.

To get all the user
Alt Text

You might wondering what is context, it just hold request, response related values, as you can see i am sending response using response.body of context

To Add new users
Alt Text

In this function I am taking value passed in the body and simply pushing it into an existing array, I am not validating any values as of now but for the real application we should validate.

And after pushing it to the array I am simply sending a response with the updated values of an array.

So we are done with the logic of getter and setter methods, but still how to define routes?

For that we have to use Router class that we have imported at the very beginning of the post.

Alt Text

Using router I have defined get and post request with the name of routes(paths) and corresponding functions to be called when that route hits

Now to bind our router with our application we need to instantiate Application first and using .use method to set the middleware for router

Alt Text

The final step is to start the application with the listen method of the Application class

Alt Text

To run this code we need to fire following command

Alt Text

Note: As you can see i have put --allow-net which is mandatory in Deno.

Now we can test our API in Postman or Insomnia

GET Request
Alt Text

POST request
Alt Text

That’s the end of this simple Deno app!

Happy Coding!!!

If you have not installed Deno yet you can find the guide here.

Top comments (0)