[go: up one dir, main page]

Skip to main content
Deno 2 is finally here 🎉️
Learn more

Building API servers with Deno


Why Deno?

You can be productive immediately with Deno when you start building your API server:

Web servers

You can create a server with a single line of code. No dependencies or a dependency manifest files needed.

Deno.serve((req) => new Response("Hello world"));

Learn more about Deno.serve() in our manual.

Here’s a longer example that shows you how to inspect Request object and respond with a Response object.

Deno.serve(async (req) => {
  console.log("Method:", req.method);

  const url = new URL(req.url);
  console.log("Path:", url.pathname);
  console.log("Query parameters:", url.searchParams);

  console.log("Headers:", req.headers);

  if (req.body) {
    const body = await req.text();
    console.log("Body:", body);
  }

  return new Response("Hello, world", {
    status: 200,
    headers: {
      "content-type": "text/plain; charset=utf-8",
    },
  });
});
What about Node?
Note in Node.js, you cannot use the web standards `Request()` constructor. Instead, you have to import `node:http` or third-party modules to create HTTP requests. Learn how Node’s divergence from web standards leads to long build times, dependency bloat, and more.

Defining API routes

Oak, a middleware framework for handling HTTP inspired by Koa, makes it simple to create routes and route handlers for an HTTP server.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";

const books = new Map<string, any>();
books.set("1", {
  id: "1",
  title: "The Hound of the Baskervilles",
  author: "Conan Doyle, Arthur",
});

const router = new Router();
router
  .get("/", (context) => {
    context.response.body = "Hello world!";
  })
  .get("/book", (context) => {
    context.response.body = Array.from(books.values());
  })
  .get("/book/:id", (context) => {
    if (books.has(context?.params?.id)) {
      context.response.body = books.get(context.params.id);
    }
  });

const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({ port: 8000 });

Since Deno supports npm, you can also use Express, Koa, Fastify, and other npm modules to build your API routes.

Deploying to Production

Deno Deploy, our global serverless at edge platform, allows you to host and run your server globally across our network close to your users, offering high availability and minimal network latency.

Hosting your server on Deno Deploy is simple and free by connecting a GitHub account.

Learn why the edge is the future of web.

You can also host your Deno server on any platform that runs a VM or VPS with Docker. Here are some guides to help you get started.

Additional Resources

There are many frameworks out there to help you build HTTP and API servers:

Here are some examples, blog posts, and videos about building HTTP and API servers with Deno.