REST API with Bun.js
×


REST API with Bun.js

1180

🌐 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 tutorial, 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 users
  • GET http://localhost:3000/users/1 – Get user by ID
  • POST 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!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat