Search⌘ K
AI Features

Handling Routes in an Oak Application

Explore how to define and register routes using Oak's Router class in a Deno application. Learn to handle GET requests, manage context objects, and improve code organization by migrating to Oak for scalable routing solutions.

Creating a router

In this lesson, we will implement the functionality that will list all the museums from our application.

Let’s add it and learn how can we create routes in an Oak application.

Oak provides another object, alongside the Application class, that allows us to define routes—the Router class. We’ll use this to reimplement the route we had before, which listed all the museums in the application.

Let’s create it by sending the prefix property to the constructor. Doing this means that all the routes defined there will be prefixed with that path:

TypeScript 3.3.4
import { Application, Router } from "../deps.ts";
...
const apiRouter = new Router ({ prefix: "/api" })

Now, let’s get back our functionality, which returns the list of museums via a GET request to /api/museums:

TypeScript 3.3.4
apiRouter.get("/museums", async (ctx) => {
ctx.response.body = {
museums: await museum.getAll()
}
});
...