REST API with Bun.js
×

REST API with Bun.js

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 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

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat