Home Web Front-end JS Tutorial Guide to Building a REST API with Deno and Oak Framework

Guide to Building a REST API with Deno and Oak Framework

Nov 03, 2024 am 10:34 AM

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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

For macOS: Using Shell

irm https://deno.land/install.ps1 | iex
Copy after login
Copy after login
Copy after login

For Windows: Using PowerShell

curl -fsSL https://deno.land/install.sh | sh
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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

Guide to Building a REST API with Deno and Oak Framework

Create new project

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

Guide to Building a REST API with Deno and Oak Framework

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
Guide to Building a REST API with Deno and Oak Framework

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.

Guide to Building a REST API with Deno and Oak Framework

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

Guide to Building a REST API with Deno and Oak Framework

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

curl -fsSL https://deno.land/install.sh | sh
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

And in the book.dto.ts file add this

irm https://deno.land/install.ps1 | iex
Copy after login
Copy after login
Copy after login

Request Validation

Add the following code to validation.ts

curl -fsSL https://deno.land/install.sh | sh
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Configure Book Router

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

export interface Book {
    id: string;
    title: string;
    author: string;
    description: string;
}
Copy after login
Copy after login

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

export interface CreateBookDTO {
    title: string;
    author: string;
    description: string;
}
Copy after login

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

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(),
});
Copy after login

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:

import { Router } from "@oak/oak/router";
import type { Book } from "./book.types.ts";
import { createBookSchema, updateBookSchema } from "./validation.ts";
Copy after login

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:

const kv = await Deno.openKv();
const bookRouter = new Router;
Copy after login

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

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

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

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:

curl -fsSL https://deno.land/install.sh | sh
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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:

irm https://deno.land/install.ps1 | iex
Copy after login
Copy after login
Copy after login

kv.delete deletes a given key-value pair.

Initialize Oak Application

In the main.ts file add the following code:

curl -fsSL https://deno.land/install.sh | sh
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Run App

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

export interface Book {
    id: string;
    title: string;
    author: string;
    description: string;
}
Copy after login
Copy after login

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.

The above is the detailed content of Guide to Building a REST API with Deno and Oak Framework. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles