Deno REST API Setup

We will create the initial project files and set up our environment

Deno REST API setup#

A Deno project has similarities to a Node project, but there are some important differences. We will in this lesson set up the base for a Deno project and discuss its components.

We will be adding the following files:

  • Deno config file (deno.jsonc)

  • Import Map (import_map.json)

  • Makefile (Makefile)

  • dotenv file (.env and .env.example)

  • GitIgnore (.gitignore)

  • Application entrypoint (main.ts)

Deno config file#

As you learned in the previous module, Deno has an optional config file, and we can make use of the tasks property to store scripts. For now, we want to add one task to run the above command easily. Create a new file called deno.jsonc and add the following.

Import Map#

As Deno supports import maps, and this is an application (not a library), we will be using import maps to keep track of our dependencies instead of adeps.ts file as you would commonly see in libraries.

Add a import_map.json file with the following content:

And then add the importMap property to the deno.jsonc

Environment variables#

As we will be using a few secrets and some environment-specific variables, the best way to proceed is by creating a .env file. For projects where we have multiple environments and developers, it is beneficial to have an example file which contains the environment variables with either empty values or with the development values (for local development). This file can be added to git as it does not contain production values, and it gives the developers an indication of what it should contain.

Create a .env.example file with the following content.

Once this file has been created, copy its content to .env. This is so we can have the local development variables in the example file, while the .env file will be used by our programs.

Runtime check#

The first thing we need to do before starting is to set up the initial files for development. As you have done for the previous modules, you can create a new project folder to house the REST API.

When starting the development of a REST API, you want to make sure that the server is actually running before anything else. To do this, we will useOak which is an HTTP middleware framework for Deno inspired by Koa. Oak will handle all our routing and endpoints so we only have to worry about the logic.

We also want to take advantage of our new .env file, and to do this, we will be using the standard module dotenv. Dotenv will read the .env file and set the Deno.env values from it.

Add the imports to the import_map.json:

Now create a file called main.ts and use the imports to create a simple application. Note that we are creating an empty AppState interface, but dont worry, we will soon populate it.

 

This page is a preview of Build and deploy a REST API with Deno

Start a new discussion. All notification go to the author.