How to Build Efficient API Endpoints Using Bun.

How to Build Efficient API Endpoints Using Bun.

Creating APIs is a fundamental skill for modern web development. Whether you’re building a web or mobile app, having fast and efficient APIs can make a big difference. In this tutorial, we will walk you through how to build a simple API using Bun, a fast JavaScript runtime, and serve an HTML file as a response. This guide assumes you have basic knowledge of JavaScript, and we'll guide you through every step of the process.


What is Bun?

Bun is a modern JavaScript runtime built for speed. It’s designed to be fast and lightweight, offering a new, highly performant way to build JavaScript applications and APIs. Bun is compatible with many Node.js APIs, but what sets it apart is its speed. If you haven’t tried Bun yet, it’s worth checking out, especially if you're looking for better performance when running JavaScript and handling requests.


Step 1: Installing Bun

Before we start writing code, we need to install Bun. Here’s how you can do it:

Installing Bun via Terminal

  1. Open your terminal (Mac/Linux) or command prompt (Windows).

  2. Run the following command to install Bun:

     curl -fsSL https://bun.sh/install | bash
    
  3. After the installation, verify that Bun was successfully installed by running:

     bun --version
    

    If installed correctly, you should see the version of Bun printed on the screen.


Step 2: Initializing Your Bun Project

With Bun installed, it’s time to create a new project where we will build the API.

  1. Create a new directory for your project and navigate to it:

     mkdir my-bun-api
     cd my-bun-api
    
  2. Initialize the project using Bun:

     bun init
    

    This will generate the basic project structure with bunfig.toml and package.json.


Step 3: Create the HTML File to Serve

Before we dive into the server code, let’s create a separate HTML file that we will send as a response from our API.

  1. Create a folder named public to hold our static files, like HTML.

     mkdir public
    
  2. Inside the public folder, create an HTML file named index.html:

     touch public/index.html
    
  3. Open index.html and add some simple HTML content:

     <!-- public/index.html -->
    
     <html>
       <head>
         <title>Bun API</title>
       </head>
       <body>
         <h1>Welcome to the Bun API</h1>
         <p>This is an HTML response from your Bun API!</p>
       </body>
     </html>
    

Step 4: Writing the API Server Code

Now, let’s create the API server that will handle incoming requests and send back responses. We’ll use Bun’s built-in serve method to handle the HTTP requests.

  1. Create a file named server.js in the project folder:

     touch server.js
    
  2. Open server.js and add the following code:

     // server.js
    
     import { serve } from "bun";
     import fs from "fs";
     import path from "path";
    
     const server = serve({
       port: 3000,
       fetch(req) {
         const url = new URL(req.url);
    
         // Handle GET requests for /api/hello (JSON response)
         if (url.pathname === "/api/hello" && req.method === "GET") {
           return new Response(JSON.stringify({ message: "Hello from Bun API!" }), {
             headers: { "Content-Type": "application/json" },
           });
         }
    
         // Handle POST requests for /api/data (JSON response)
         if (url.pathname === "/api/data" && req.method === "POST") {
           const data = await req.json();
           return new Response(
             JSON.stringify({ received: data }),
             { headers: { "Content-Type": "application/json" } }
           );
         }
    
         // Handle GET requests for /api/html (Serve HTML file)
         if (url.pathname === "/api/html" && req.method === "GET") {
           const htmlFilePath = path.resolve("public", "index.html");
           const htmlContent = fs.readFileSync(htmlFilePath, "utf-8");
    
           return new Response(htmlContent, {
             headers: { "Content-Type": "text/html" },
           });
         }
    
         // Return 404 for unknown routes
         return new Response("Not Found", { status: 404 });
       },
     });
    
     console.log(`Server running on ${port}.`);
    

Explanation of the Code:

  1. Serving JSON Data:

    • The /api/hello endpoint returns a JSON response with a simple message.

    • The /api/data endpoint accepts POST requests, receives data, and sends it back as a JSON response.

  2. Serving HTML Content:

    • For the /api/html endpoint, we use the fs.readFileSync method to read the index.html file from the public folder.

    • The content of this HTML file is then sent back as the response with the Content-Type: text/html header.


Step 5: Running the Server

Now that we have written the server code, let’s run it!

  1. Open your terminal and execute the following command:

     bun run server.js
    
  2. You should see the following output:

     Server running on http://localhost:3000
    

This confirms that your server is up and running on http://localhost:3000.


Step 6: Testing the API Endpoints in Postman

Let’s now test our API using Postman.

Test the GET Request for JSON Response:

  1. Open Postman and create a new GET request.

  2. Set the URL to http://localhost:3000/api/hello.

  3. Click Send.

Expected Response:

{
  "message": "Hello from Bun API!"
}

Test the POST Request for JSON Response:

  1. In Postman, create a new POST request.

  2. Set the URL to http://localhost:3000/api/data.

  3. Change the HTTP method to POST.

  4. In the Body tab, select raw and JSON format.

  5. Enter the following JSON data:

     {
       "name": "John"
     }
    
  6. Click Send.

Expected Response:

{
  "received": {
    "name": "John"
  }
}

Test the GET Request for HTML Response:

  1. Create a new GET request in Postman.

  2. Set the URL to http://localhost:3000/api/html.

  3. Click Send.

Expected Response (HTML):

<html>
  <head><title>Bun API</title></head>
  <body>
    <h1>Welcome to the Bun API</h1>
    <p>This is an HTML response from your Bun API!</p>
  </body>
</html>

Step 7: Conclusion

You’ve successfully built a simple API using Bun that serves both JSON and HTML responses! Here’s a summary of what you’ve done:

  • Installed Bun and set up a new project.

  • Created an HTML file that is served by your API.

  • Built an API server that handles both GET and POST requests.

  • Tested the API using Postman.


Next Steps

  1. Add More Routes: You can expand your API by adding more routes and functionality, such as database integration.

  2. Authentication: Secure your API by adding authentication and authorization.

  3. Learn More About Bun: Explore Bun’s other features such as bundling and transpiling.

For more information, you can check out these resources:

Happy coding!