Skip to content

How to develop REST API with Deno

Last updated on November 24, 2022

In this tutorial, we gonna use Attain web framework to create REST API with Deno.

Attain is a middleware web framework for Deno which is using HTTP standard library inspired by express and Oak. and it is Fast and stable with proper memory usage.

import { App, logger, parser, security, staticServe } from "https://deno.land/x/attain/mod.ts";

const app = new App();

// Set Extra Security setting
app.use(security());

// Logging response method status path time
app.use(logger);

// Parsing the request body and save it to request.params
// Also, updated to parse the queries from search params
app.use(parser);

// Serve static files
// This path must be started from your command line path.
app.use(staticServe("./public", {maxAge: 1000}));

app.use("/", (req, res) => {
  res.status(200).send("hello");
});

app.use("/google", (req, res) => {
  res.redirect("https://www.google.ca");
})

app.use("/:id", (req, res) => {
  // This data has parsed by the embedded URL parser.
  console.log(req.params);
  res.status(200).send(`id: ${req.params.id}`);
})

app.post("/submit", (req, res) => {
  // By the parser middleware, the body and search query get parsed and saved.
  console.log(req.params);
  console.log(req.query);
  res.status(200).send({ data: "has received" });
});

app.listen({ port: 3000 });
console.log("Start listening on http://localhost:3000");

Let’s try to run our server! Now, with Deno, we are going to need network access in order for this to work. So, we are going to run our server like this

deno run --allow-net server.js

Once the server is up, you can access the application at https://localhost:3000

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments