DEV Community

Cover image for Guide to Building a REST API with Deno and Oak Framework
nnamdi nwaocha
nnamdi nwaocha

Posted on

Guide to Building a REST API with Deno and Oak Framework

This post guides you in creating a REST API using Deno, the Oak framework, and a DenoKV database.

We’ll build a simple book API to do all of this. But first, let's understand these technologies.

What is Deno?

Deno aims to uncomplicate Javascript.

It does this by fixing many of the problems developers face with Node. Deno’s straightforward approach helps developers write more secure, efficient, modern JavaScript code.

A huge selling point of Deno is its security. By default, it doesn’t allow access to the file system, network, or environment variables unless explicitly allowed by the developer. Deno also gives developers native TypeScript support without needing additional configuration.

Other features that come with Deno are:

  • A built-in standard library, removing the need for many third-party packages
  • A modern module system, directly supporting URL-based imports
  • An enhanced CLI with built-in tools for formatting, linting, and testing
  • A consistent JavaScript experience with ES Modules instead of CommonJS.

What is Oak

Oak is a middleware framework for Deno that helps developers build web apps and APIs.

It gives tools for handling HTTP requests, managing routing, and integrating middleware, similar to Express in Node.js. Oak also has TypeScript right out of the box and benefits from Deno’s security and modern runtime environment. This gives developers a familiar syntax while still enjoying more modern features.

Oak allows developers to adopt TypeScript-first practices in a safe, efficient, and progressive environment.

What is DenoKV

DenoKV is a key-value database that manages structured data for Deno.

Each piece of data or "value" has a unique identifier or "key", making it easy to fetch data by referencing its key. This approach allows developers to manage data without setting up a separate database server. DenoKV is ideal for lightweight applications and fast prototyping.

Developers get a straightforward solution for managing data right alongside their code.

Project Setup

Install Deno

curl -fsSL https://deno.land/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

For macOS: Using Shell

irm https://deno.land/install.ps1 | iex
Enter fullscreen mode Exit fullscreen mode

For Windows: Using PowerShell

curl -fsSL https://deno.land/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

For Linux: Using Shell
To test your installation run deno -version.

Installing deno using Powershell

Create new project

Run the command deno init deno-oak-demo to create a new project called deno-oak-demo, then cd into it

Initializing a new deno project using bash

Next, you’ll need to create 4 new files in the deno-oak-demo directory:

  • book.routes.ts
  • book.dto.ts
  • book.types.ts
  • And validation.ts

You’re deno-oak-demo directory now should look like this
Project directory

Install Deno VSCode Extension

Next, you’ll need to install Deno’s official VSCode extension which adds support for using Deno with Visual Studio Code.

Deno VSCode extension

Install Oak

Use the command deno add jsr:@oak/oak to install the Oak framework as a dependency.
Your deno.json file should now look like this

deno.json file

Every time we install a package in Deno, it gets placed in the deno.json file as an import. Then, if we want to import this package into a file, we can either use the alias defined in the deno.json or directly reference the package's URL.

Defining Types and DTOs

In the book.types.ts file add the following code

export interface Book {
    id: string;
    title: string;
    author: string;
    description: string;
}
Enter fullscreen mode Exit fullscreen mode

And in the book.dto.ts file add this

export interface CreateBookDTO {
    title: string;
    author: string;
    description: string;
}
Enter fullscreen mode Exit fullscreen mode

Request Validation

Add the following code to validation.ts

import { z } from "https://deno.land/x/zod@v3.17.0/mod.ts";

export const createBookSchema = z.object({
    title: z.string(),
    author: z.string(),
    description: z.string(),
});

export const updateBookSchema = z.object({
    title: z.string().optional(),
    author: z.string().optional(),
    description: z.string().optional(),
});
Enter fullscreen mode Exit fullscreen mode

Configure Book Router

To begin we’ll import the Oak Router, Book interface, createBookSchema and updateBookSchema into the book.routes.ts file:

import { Router } from "@oak/oak/router";
import type { Book } from "./book.types.ts";
import { createBookSchema, updateBookSchema } from "./validation.ts";
Enter fullscreen mode Exit fullscreen mode

Next, we’ll initialize the DenoKV database and create a new router instance to handle HTTP routes.

const kv = await Deno.openKv();
const bookRouter = new Router;
Enter fullscreen mode Exit fullscreen mode

Next, we’re going to create a helper function to get a book by its id:

async function getBookById(id: string) {
    const entry = await kv.get(["books", id]);
    return entry.value as Book | null;
}
Enter fullscreen mode Exit fullscreen mode

kv.get takes an array with two strings: one represents the namespace "books” and the other represents the key for the specific book being retrieved.
Next, let’s define the route handler to get a single book by id:

bookRouter.get('/books/:id', async (context) => {
    try {
        const id = context.params.id;
        const book = await getBookById(id);

        if (book) {
            context.response.body = book;
        } else {
            context.response.status = 404;
            context.response.body = { message: "Book not found" };
        }
    } catch (error) {
        console.log(error)
        context.response.status = 500;
        context.response.body = { message: "Failed to retrieve book" };
    }
});
Enter fullscreen mode Exit fullscreen mode

Unlike in Express, in Oak both the request and response are accessed from the context object, which has both the request data and response methods, giving a streamlined way to handle HTTP interactions.

Next, add the route handler to get all books:

bookRouter.get('/books', async (context) => {
    try {
        const entries = kv.list({ prefix: ["books"] });
        const books: Book[] = [];

        for await (const entry of entries) {
            books.push(entry.value as Book);
        }

        context.response.body = books;
    } catch (error) {
        console.log(error)
        context.response.status = 500;
        context.response.body = { message: "Failed to fetch books" };
    }
});
Enter fullscreen mode Exit fullscreen mode

Kv.list retrieves all key-value pairs that share a common prefix(namespace).

Next, add the route handler to create a new book:

bookRouter.post("/books", async (context) => {
    try {
        const body = await context.request.body.json();
        const parsedBody = createBookSchema.safeParse(body);

        if (!parsedBody.success) {
            context.response.status = 400;
            context.response.body = {
                message: "Validation failed",
                errors: parsedBody.error.format()
            };
            return;
        }

        const uuid = crypto.randomUUID();
        const newBook: Book = { id: uuid, ...parsedBody.data };

        await kv.set(["books", uuid], newBook);

        context.response.status = 201;
        context.response.body = { message: "Book added", book: newBook };
    } catch (error) {
        console.log(error)
        context.response.status = 500;
        context.response.body = { message: "Failed to add book" };
    }
});
Enter fullscreen mode Exit fullscreen mode

Kv.set can be used to save a new key-value pair in the DB, in this case, it takes an array (with two strings; the namespace, and the key) and the value to be saved.

Next, add the route handler to update a book by id:

bookRouter.put('/books/:id', async (context) => {
    try {
        const id = context.params.id;
        const existingBook = await getBookById(id);

        if (!existingBook) {
            context.response.status = 404;
            context.response.body = { message: "Book not found" };
            return;
        }

        const body = await context.request.body.json();
        const parsedBody = updateBookSchema.safeParse(body);
        if (!parsedBody.success) {
            context.response.status = 400;
            context.response.body = {
                message: "Validation failed",
                errors: parsedBody.error.format()
            };
            return;
        }

        // Update the book, preserving existing values for fields not provided
        const updatedBook = { ...existingBook, ...parsedBody.data };

        await kv.set(["books", id], updatedBook);
        context.response.status = 200;
        context.response.body = { message: "Book updated", book: updatedBook };
    } catch (error) {
        console.log(error)
        context.response.status = 500;
        context.response.body = { message: "Failed to update book" };
    }
});
Enter fullscreen mode Exit fullscreen mode

kv.set can also be used to update the value of a key-value pair. In this case, it takes an array (with two strings; the namespace, and the key whose value will be updated) and the new value to be updated with.
Lastly, let’s add the route handler to delete a book by id:

bookRouter.delete("/books/:id", async (context) => {
    try {
        const id = context.params.id;
        const book = await getBookById(id);

        if (!book) {
            context.response.status = 404;
            context.response.body = { message: "Book not found" };
            return;
        }

        await kv.delete(["books", id]);
        context.response.status = 200;
        context.response.body = { message: "Book deleted", book };
    } catch (error) {
        console.log(error)
        context.response.status = 500;
        context.response.body = { message: "Failed to delete book" };
    }
});

export { bookRouter }
Enter fullscreen mode Exit fullscreen mode

kv.delete deletes a given key-value pair.

Initialize Oak Application

In the main.ts file add the following code:

import { Application } from "@oak/oak/application";
import { bookRouter } from "./book.routes.ts";

const app = new Application();

app.use(bookRouter.routes());
app.use(bookRouter.allowedMethods());

app.listen({ port: 3000 });
Enter fullscreen mode Exit fullscreen mode

Run App

We’ll need to make a small change to our deno.json to run our app.

{
  "tasks": {
    "dev": "deno run --watch --unstable-kv --allow-net main.ts"
  },
  "imports": {
    "@oak/oak": "jsr:@oak/oak@^17.1.2",
    "@std/assert": "jsr:@std/assert@1"
  }
}
Enter fullscreen mode Exit fullscreen mode

We’ve added the --stable-kv flag because DenoKV is still an unstable API.

Also, we’ve added the --allow-net flag to grant Deno net access.

With this in place, we can start our app by running deno run dev.

Conclusion

We’ve come to the end of the post.

Now you can create a REST API with Deno Oak and a DenoKV database.

Top comments (0)