Building API servers with Deno
Why Deno?
You can be productive immediately with Deno when you start building your API server:
- No configuring your toolchain, project, and TypeScript, since Deno ships with a modern development toolchain with native TypeScript support
- Use Web Platform APIs
you’re familiar with, like
fetch()
, compression streams,BroadcastChannel
, web workers,WebSocket
, and more - Mitigate supply chain attacks with Deno’s opt-in permission system
- Add state in a a few lines of code with Deno KV, built right into the runtime
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",
},
});
});
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.
- Deploy to Digital Ocean
- Deploy to Amazon Lightsail
- Deploy to Google Cloud Run
- Deploy to Cloudflare Workers
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.