Building Lightweight APIs with Bun: A Step-by-Step Guide🚀

Building Lightweight APIs with Bun: A Step-by-Step Guide🚀

In today’s fast-paced web development landscape, speed and efficiency are key. Bun, a modern JavaScript runtime, is making waves for its lightning-fast performance and developer-friendly features. In this blog, we’ll explore how you can create simple yet powerful API endpoints using Bun.


Why Bun for APIs❓

Bun is designed for speed and simplicity. It combines the runtime, package manager, and bundler into one tool. With its high performance and native support for many Node.js APIs, Bun is an excellent choice for developers looking to build lightweight and efficient applications.


Step 1: Installing Bun 🛠️

Before we dive into coding, let’s set up Bun on your system.

  1. Create a Project Directory:

    First, create a new directory for your project. Open your terminal and run:

     bash mkdir my-bun-api
     cd my-bun-api
    
  2. Open your terminal and run this command to install Bun:

      powershell -c "irm bun.sh/install.ps1 | iex"
    
  3. Initialize a New Bun Project:

    After installing Bun, you’ll need to initialize a new Bun project in your directory. To do this, run:

     npm init
    
  4. Verify the installation by checking the version

     bun --version
    
  5. That’s it! Bun is now ready to use.


Step 2: Creating API Endpoints with Bun 🌐

Create a file named server.js and add the following code:

Bun.serve({
  port: 8050, // Set your port
  fetch(req) {
    const url = new URL(req.url);

    switch (url.pathname) {
      case "/":
        return new Response("Welcome to your API");

      case "/api/data":
        const data = [
          { id: 1, item: "Sample Item 1" },
          { id: 2, item: "Sample Item 2" },
        ];
        return new Response(JSON.stringify(data), {
          headers: { "Content-Type": "application/json" },
        });

      default:
        return new Response("404 Not Found", { status: 404 });
    }
  },
});

console.log(Server running at http://localhost:${server.port});

2. Run the Server ▶️

Once you've set up your server.js file, you can start the server with the following command:

bash run server.js

3. Customize Your API 🛠️

Want to add more functionality? Modify the switch statement to include new endpoints. For example:

case "/api/users":
  const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
  ];
  return new Response(JSON.stringify(users), {
    headers: { "Content-Type": "application/json" },
  });

4. Test Your Endpoints 🧪


Conclusion ✨

Bun is a game-changer for developers who want a fast and straightforward way to build APIs. With its minimal setup and robust features, you can create scalable and efficient applications in no time. Start experimenting with Bun today and unlock a new level of performance for your projects!