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
For macOS: Using Shell
irm https://deno.land/install.ps1 | iex
For Windows: Using PowerShell
curl -fsSL https://deno.land/install.sh | sh
For Linux: Using Shell
To test your installation run deno -version.
Create new project
Run the command deno init deno-oak-demo to create a new project called deno-oak-demo, then cd into it
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
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.
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
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
And in the book.dto.ts file add this
irm https://deno.land/install.ps1 | iex
Request Validation
Add the following code to validation.ts
curl -fsSL https://deno.land/install.sh | sh
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; }
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; }
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(), });
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";
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;
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; }
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
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
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
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; }
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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
