How to build a REST API with Hono in 5 Minutes?
Tags: javascript, tutorial, programming, api
Published: 2024-01-26 10:51:03

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](https://hono.dev/) 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](https://project-static-assets.s3.amazonaws.com/APISpreadsheets/APIMemes/ServersCooksExample.jpeg)

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 🔥

```bash
npm create hono@latest hono-tutorial
```

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

```bash
? Which template do you want to use?
    aws-lambda
    bun
    cloudflare-pages
❯   cloudflare-workers
    deno
    fastly
    lagon
    nextjs
    nodejs
    vercel
```

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

```bash
cd hono-tutorial
npm i
```

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.

```bash
import { Hono } from 'hono'

const app = new Hono()

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

export default app
```

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

![API Route Defining rule](https://res.cloudinary.com/dtscloud/image/upload/v1706265692/Post%20Images/Group_1_r7vaqg.png)

**Create your first API route:**

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

```jsx
app.get("/name", (c) => {
  return c.json({
    name: "My name is Dhairya!",
  });
});
```

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

```bash
npm run dev
```

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](https://prod-files-secure.s3.us-west-2.amazonaws.com/66848847-6d9d-44c0-96be-3b7220096ccf/2c65bdc1-8cd4-4cca-9151-cd03968e1c8a/Screenshot_2024-01-26_at_3.36.41_PM.png)

```jsx
{"name":"My name is Dhairya!"}
```

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:

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

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:

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

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

```jsx
{
	"country": "I love Cricket!"
}
```

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:**
    
    ```tsx
    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](https://hono.dev/top).

Thanks for reading! [Follow me on X](https://twitter.com/dhairyashah_dev)