Creating an API Endpoint using Bun

Creating an API Endpoint using Bun

Ā·

3 min read

šŸŽÆWhat is Bun ?

Bun is a JavaScript runtime.It is an attemptā€‚to overcome the limitations of Node. js back-end development setup with a separateā€‚front-end using React, Vue, or Angular.

Unlike Node. js, Bun does notā€‚depend on npm and doesn't need any other dependencies to function. Instead, it features a built-in standard library containing support for various protocols and modules, such as environment variables, HTTP,ā€‚websocket, file system, etc.

šŸ› ļø Preparingā€‚Your Environment

āš™ļøStep 1: Install Bun

If you have not installedā€‚Bun yet then you can do it by running the following command in your terminal:

powershell -c "irm bun.sh/install.ps1 | iex"

āš™ļøStep 2: Create a New Project

Create a new folder for your project.

mkdir BarterX
cd BarterX

āš™ļøstep 3: Intialize your project

Run the following command to initialize your Bun project:

bun init

This command will set up the neccessary files for your project.

āœļø Creating API Endpoints :

Now the enviroment has been set up letā€™s create simple API endpoint.

now open vs code and create index.

Bun.serve({
  fetch(req) {
    const url = new URL(req.url);

    // Create a simple GET endpoint
    if (url.pathname === "/api/hello" && req.method === "GET") {
      return new Response(JSON.stringify({ message: "Hello, Bun!" }), {
        status: 200,
        headers: { "Content-Type": "application/json" },
      });
    }

    // Return 404 for other routes
    return new Response("Not Found", { status: 404 });
  },
});

// Log server information
console.log("Server is running at http://localhost:3000");

šŸ§ Explanation of the Code

  1. Port Customization:

    • Use process.argv to get the port number from the command line.

    • Defaults to 3000 if no port is specified.

  2. The serve Function:

    • Tells Bun to create an HTTP server.

    • Handles incoming requests using the fetch function.

  3. Request Handling:

    • Checks if the URL matches /api/hello with a GET request.

    • Sends back a greeting if matched.

    • Returns a 404 error for other routes.

šŸ–„ļø Running Your API

To run your API, execute the following command in your terminal:

bun run index

Test it by visiting http://localhost:3000/api/hello in your browser.

{
  "message": "Hello, Bun!"
}

If no port is specified, the server defaults to port 3000.

šŸ”—Why Use Bun for APIs?

  1. Blazing Performance:

    • Built for speed with Zig and an optimized runtime design.
  2. Simplicity:

    • Native HTTP server removes the need for additional libraries like Express.
  3. All-in-One Tool:

    • Combines a runtime, bundler, and package manager to streamline development.

šŸŽÆConclusion

Bun makes creating lightweight, high-performance APIs a breeze. From native routing to JSON parsing, Bun simplifies modern web development. Whether youā€™re building a simple app or a production-ready system, Bunā€™s features make it a top choice.

Ā