REST API with Bun.js
0 119
๐ REST API with Bun.js: Build Blazing-Fast Backends
If you've been working with Node.js for building REST APIs, you're going to love what Bun.js brings to the table. Bun is a modern, ultra-fast JavaScript runtime with a built-in HTTP server, package manager, and bundler. In this blog, we'll walk through how to build a simple REST API with Bun.js โ fast, clean, and minimal.
๐ Why Use Bun.js for REST APIs?
Hereโs why Bun.js is quickly becoming a go-to choice for backend development:
- Blazing fast startup and response times
- Built-in HTTP server (no need for Express or Fastify)
- First-class TypeScript support
- Lightweight, no extra dependencies required
Now, letโs jump into building a real REST API using Bun.
๐ ๏ธ Setting Up the Project
First, make sure Bun is installed. If not, install it via:
curl -fsSL https://bun.sh/install | bash
Next, create your project folder:
mkdir bun-rest-api
cd bun-rest-api
bun init
This will set up a basic package.json
and lockfile for your Bun project.
๐ Project Structure
bun-rest-api/
โโโ index.ts
โโโ package.json
โโโ bun.lockb
We'll keep it minimal for now, with just one file โ index.ts
.
๐ Creating the HTTP Server
Bun comes with a native serve()
function that makes spinning up a server effortless.
// index.ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!", {
headers: { "Content-Type": "text/plain" },
});
},
});
Run the server with:
bun index.ts
Open your browser at http://localhost:3000
and youโll see โHello from Bun!โ
๐ฆ Building a REST API
Now let's build a basic REST API with CRUD (Create, Read, Update, Delete) functionality for managing users.
๐ Sample In-Memory Data
let users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
๐ฅ Handling Routes with Bun
// index.ts
Bun.serve({
port: 3000,
async fetch(req) {
const url = new URL(req.url);
// GET /users
if (req.method === "GET" && url.pathname === "/users") {
return Response.json(users);
}
// GET /users/:id
if (req.method === "GET" && url.pathname.startsWith("/users/")) {
const id = Number(url.pathname.split("/")[2]);
const user = users.find(u => u.id === id);
return user
? Response.json(user)
: new Response("User not found", { status: 404 });
}
// POST /users
if (req.method === "POST" && url.pathname === "/users") {
const body = await req.json();
const newUser = { id: users.length + 1, ...body };
users.push(newUser);
return Response.json(newUser, { status: 201 });
}
// Fallback route
return new Response("Not found", { status: 404 });
}
});
๐จ Test the API
Use curl
or Postman to test endpoints:
GET http://localhost:3000/users
โ Get all usersGET http://localhost:3000/users/1
โ Get user by IDPOST http://localhost:3000/users
โ Add a user (send JSON body)
๐ Sample POST Request
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name": "Charlie"}'
๐ Bonus: Add JSON Content-Type Header
Always send the correct response type for API calls:
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
๐ง Limitations & Considerations
While Bun.js is powerful and fast, there are some things to keep in mind:
- Bun is still in early development โ expect some bugs or missing APIs
- No middleware support like Express (yet)
- Youโll need to manually handle routing, parsing, etc.
Still, it's a great choice for small services, MVPs, and learning modern backend concepts.
โ Conclusion
Building a REST API with Bun.js is quick, efficient, and surprisingly fun. With built-in HTTP handling and no dependency overhead, you can get started in minutes. As Bun matures, we can expect even more powerful features โ but even today, itโs production-worthy for many use cases.
So next time youโre spinning up an API โ give Bun.js a shot. It might just become your new favorite backend tool.
๐ก Pro Tip: Use Bun for Serverless APIs
Bunโs lightweight nature makes it ideal for serverless functions. Pair it with edge runtimes like Vercel or Netlify to deploy your API at the speed of light.
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments