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
Open your terminal (Mac/Linux) or command prompt (Windows).
Run the following command to install Bun:
curl -fsSL https://bun.sh/install | bash
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.
Create a new directory for your project and navigate to it:
mkdir my-bun-api cd my-bun-api
Initialize the project using Bun:
bun init
This will generate the basic project structure with
bunfig.toml
andpackage.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.
Create a folder named
public
to hold our static files, like HTML.mkdir public
Inside the public folder, create an HTML file named
index.html
:touch public/index.html
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.
Create a file named
server.js
in the project folder:touch server.js
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:
Serving JSON Data:
The
/api/hello
endpoint returns a JSON response with a simple message.The
/api/data
endpoint acceptsPOST
requests, receives data, and sends it back as a JSON response.
Serving HTML Content:
For the
/api/html
endpoint, we use thefs.readFileSync
method to read theindex.html
file from thepublic
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!
Open your terminal and execute the following command:
bun run server.js
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:
Open Postman and create a new GET request.
Set the URL to
http://localhost:3000/api/hello
.Click Send.
Expected Response:
{
"message": "Hello from Bun API!"
}
Test the POST Request for JSON Response:
In Postman, create a new POST request.
Set the URL to
http://localhost:3000/api/data
.Change the HTTP method to POST.
In the Body tab, select raw and JSON format.
Enter the following JSON data:
{ "name": "John" }
Click Send.
Expected Response:
{
"received": {
"name": "John"
}
}
Test the GET Request for HTML Response:
Create a new GET request in Postman.
Set the URL to
http://localhost:3000/api/html
.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
Add More Routes: You can expand your API by adding more routes and functionality, such as database integration.
Authentication: Secure your API by adding authentication and authorization.
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!