DEV Community

Dhairya Shah
Dhairya Shah

Posted on • Originally published at dhairyashah.dev

How to build a REST API with Hono in 5 Minutes?

Today, the REST APIs have become the backbone of modern applications, enabling the seamless connection between the front end and the back end. There are lots of technologies and methods available in the market to build a REST API. In this article, we are going to learn about the Hono which is a fast, simple, and lightweight web framework that runs on Edge.

If you are unfamiliar with the REST APIs, then let me share about them in brief.

What is a REST API?

Imagine you’re at a restaurant, and you want to order some food. You don’t go into the kitchen and cook yourself; instead, you ask the waiter to bring you the dishes you want.

Similarly, in the world of computer networks, REST (Representational State Transfer) is like a waiter, and APIs (Application Programming Interfaces) are like a menu. So, REST API is a set of rules that lets different software applications communicate with each over across the internet (or network).

Here is a popular meme about REST APIs,

API MEME

As always, our first step is to create an application. In our case, it's an Hono web application, to create run the following command:

Let’s Begin with Hono 🔥

npm create hono@latest hono-tutorial
Enter fullscreen mode Exit fullscreen mode

Now, you will see a bunch of template choices you would like to use. Let’s select Cloudflare Workers, for this tutorial:

? Which template do you want to use?
    aws-lambda
    bun
    cloudflare-pages
❯   cloudflare-workers
    deno
    fastly
    lagon
    nextjs
    nodejs
    vercel
Enter fullscreen mode Exit fullscreen mode

The Hono application is created inside hono-tutorial folder. So open the folder in the terminal and install the required dependencies.

cd hono-tutorial
npm i
Enter fullscreen mode Exit fullscreen mode

After the installation, you can open the project in your favourite IDE.

Creating the API Routes

Open src/index.ts, and there will be a boilerplate code.

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

export default app
Enter fullscreen mode Exit fullscreen mode

In Hono, a route can be defined in the following manner:

API Route Defining rule

Create your first API route:

Inside, src/index.ts write the following code:

app.get("/name", (c) => {
  return c.json({
    name: "My name is Dhairya!",
  });
});
Enter fullscreen mode Exit fullscreen mode

Now, run the Hono application by running the following command in the terminal.

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open the application in the Postman / Insomnia. In this tutorial, I will be using Insomnia.

Screenshot 2024-01-26 at 3.36.41 PM.png

{"name":"My name is Dhairya!"}
Enter fullscreen mode Exit fullscreen mode

Tada! You've successfully developed your REST API using Hono; wasn't that simple?

Creating the POST Route:

Similar to the GET method, we can create a POST method API route following the same manner. Here’s how to do that:

app.post("/sports", async (c) => {
  const body = await c.req.parseBody();
  const sports = body["sports"];
  return c.json({
    country: `I love ${sports}!`,
  })
})
Enter fullscreen mode Exit fullscreen mode

In this code, body["sports"] returns the key value of “sports” passed in the form body.

Here’s the curl request for the /sports API route:

curl --request POST \
  --url http://localhost:8787/sports \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data sports=Cricket
Enter fullscreen mode Exit fullscreen mode

After calling this api route, the output will look like following:

{
    "country": "I love Cricket!"
}
Enter fullscreen mode Exit fullscreen mode

Similarly, you can create API routes for the different methods i.e. PUT, PATCH, DELETE, OPTIONS.

Conclusion:

Congratulations! You've successfully learned how to build a REST API using Hono in just a few minutes. Here's a quick recap of the key steps:

  • Complete Source Code:

    app.get("/", (c) => {
      return c.text("Hello Hono!");
    });
    
    app.get("/name", (c) => {
      return c.json({
        name: "My name is Dhairya!",
      });
    });
    
    app.post("/sports", async (c) => {
      const body = await c.req.parseBody();
      const sports = body["sports"];
      return c.json({
        country: `I love ${sports}!`,
      });
    });
    
    

With these simple steps, you've successfully built a REST API with Hono. Feel free to explore additional features and customization options offered by Hono for more advanced use cases. Happy coding!

For your further reference, you can check out official Hono Docs.

Thanks for reading! Follow me on X

Top comments (0)