Easy and Fast API Development with Bun and Hono: A Simple Project in 5 Minutes
koshirok096
Posted on October 25, 2024
Introduction
I recently wrote simple articles about Hono and Bun, and this article is a related follow-up. In this article, I will introduce how to create a simple API in a short time using the combination of Bun and Hono, to learn how to setup a basic environment of these. While there is some overlap with the previous content, I had not clearly specified the combination of Bun and Hono, so this article aims to complement that, focusing on using both Bun and Hono. Actually, the content is written to be simple and targeted at beginners.
First, let’s recap the overview of Bun and Hono:
- Bun: JavaScript runtime that allows for faster builds and execution compared to Node.js. It’s lightweight and equipped with hot-reload functionality, making for a very smooth development experience.
- Hono: Lightweight web framework based on TypeScript, ideal for building simple APIs. It features strong TypeScript support and intuitive routing.
Why combine Bun and Hono?
The reason I became interested in Bun and Hono is that I believe they could be a better option for developers currently using Node.js and Express.
Bun is developed as a JavaScript runtime aimed at faster performance than Node.js, while Hono can be described as the next generation of Express.js, being a lightweight and fast web framework. Both come with advantages suitable for modern development environments, such as built-in tools, excellent TypeScript support, and optimization for cloud and edge environments.
Of course, Bun and Hono each have their strengths and weaknesses, and you may need to choose based on your use case. Additionally, even if you use Bun, there may be situations where you combine it with Node.js. However, I believe that learning and understanding these tools will never be a waste. By incorporating new technologies, you open up the possibility of developing more efficient and high-performance applications.
In this article, I will introduce how to quickly build a simple API using Bun and Hono, targeting beginners. Although there is much more that can be done with Bun and Hono, this article will not cover everything. However, through the steps in this article, I hope you can gain a basic understanding of setting up and building with Bun and Hono, which will be useful for further learning.
Setup
First, let’s set up the development environment. I have already written articles on setting up Hono and Bun individually, so in this article, I will summarize the steps concisely.
First, let’s install Bun with the following command:
curl https://bun.sh/install | bash
Once the installation is complete, check the version:
bun --version
Create the project directory with the following command:
mkdir bun-hono-api
cd bun-hono-api
Then, set up the Bun environment with the following command:
bun init
Next, install Hono:
bun add hono
Creating a Simple API
Now, let's get into the main topic. We will create an index.ts
file, instantiate Hono, and define simple endpoints.
import { Hono } from 'hono';
const app = new Hono();
// Simple API Endpoint
app.get('/', (c) => c.text('Hello, World!'));
app.get('/greet/:name', (c) => {
const name = c.req.param('name');
return c.text(`Hello, ${name}!`);
});
// Bun Server
Bun.serve({
fetch(req) {
// Hono API
return app.fetch(req);
},
port: 3000,
});
console.log('Server running on http://localhost:3000');
In this code, the /
endpoint will return "Hello, World!"
and the /greet/:name
endpoint will display a greeting message using the user's name.
Next, let's start the server using Bun by running the following command:
bun run index.ts
If the terminal shows Server running on http://localhost:3000
, it means the server has started successfully.
Finally, let's check if the server is working properly. Use a browser or the curl command to access the following two endpoints:
- /: Returns "Hello, World!"
- /greet/:name: Returns "Hello, {name}!"
- These endpoints generate dynamic responses using named parameters. When you access the URL path /greet/{name}, it will generate a greeting message based on the specified name.
—
Try running curl http://localhost:3000/greet/
and curl http://localhost:3000/greet/terry
from the terminal to see the output. In this case, we're using the terminal, but you can also use API testing tools like Postman to check the functionality of the endpoints.
By the way, when writing this part using Express, the code would look quite similar, but Hono uses a context object (c) instead of separate request/response objects, making the code cleaner and easier to understand. Personally, I find it more intuitive, which is why I like it.
Bonus: Creating an Endpoint to Return JSON Responses
As a bonus, let's create an endpoint that returns a JSON response. Add the following code to your index.ts file:
app.get('/users', (c) => {
return c.json([
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
{ id: 3, name: 'Alice Johnson' },
{ id: 4, name: 'Bob Brown' },
{ id: 5, name: 'Charlie Davis' },
{ id: 6, name: 'Eve Wilson' },
{ id: 7, name: 'Frank Thompson' },
{ id: 8, name: 'Grace Lee' },
{ id: 9, name: 'Henry White' },
{ id: 10, name: 'Ivy Green' }
]);
});
This endpoint returns user information in JSON format when you access /users
. By using the c.json()
method, you can return an object as a JSON response.
You can easily test this JSON response using the following command:
curl http://localhost:3000/users
When you run this command, you should see a JSON response like the following:
[
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
{ id: 3, name: 'Alice Johnson' },
{ id: 4, name: 'Bob Brown' },
{ id: 5, name: 'Charlie Davis' },
{ id: 6, name: 'Eve Wilson' },
{ id: 7, name: 'Frank Thompson' },
{ id: 8, name: 'Grace Lee' },
{ id: 9, name: 'Henry White' },
{ id: 10, name: 'Ivy Green' }
]
You can also check this in Postman or your browser. Feel free to experiment by changing the content of the response to see different outputs.
Additionally, you can play around by combining external APIs with your code, like this example:
// Endpoints to obtain user information from external APIs
app.get('/external-users', async (c) => {
// JSONPlaceholder API
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
// Return data acquired from external APIs to the client in JSON format
return c.json(users);
});
Conclusion
For those who are currently developing with Node.js and Express, as you can see from the content of this article, the way code is written and structured in Hono and Express is very similar. However, Hono offers notable features such as optimization for cloud and edge environments, excellent support for TypeScript, and a wealth of built-in tools, which make it particularly attractive.
Additionally, regarding Bun, it is gaining attention as an alternative runtime to Node.js, offering incredibly fast and lightweight performance. Like Hono, Bun also has excellent support for TypeScript, and it stands out for its integrated build tools and package manager. Since most Node.js code runs almost as-is, using Bun can provide a smoother and more efficient development experience.
Although we couldn’t cover everything in detail in this article, the combination of Hono and Bun could become a very powerful option for future web development. I encourage you all to explore Hono and Bun and give them a try.
Thank you for reading!
Posted on October 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024