Table of contents
- What is Bun?
- Step 1: Installing Bun
- Installing Bun via Terminal
- Step 2: Initializing Your Bun Project
- Step 3: Create the HTML File to Serve
- Step 4: Writing the API Server Code
- Explanation of the Code:
- Step 5: Running the Server
- Step 6: Testing the API Endpoints in Postman
- Test the GET Request for JSON Response:
- Test the POST Request for JSON Response:
- Test the GET Request for HTML Response:
- Welcome to the Bun API
Creating APIs is an essential skill for today's web development. Whether you're making a web or mobile app, having quick and efficient APIs is important. In this tutorial, we'll show you how to build a simple API using Bun, a fast JavaScript runtime, and serve an HTML file as a response. This guide assumes you know the basics of JavaScript, and we'll take you through each step.
What is Bun?
Bun is a contemporary JavaScript runtime optimized for speed. It is engineered to be fast and lightweight, providing a highly efficient method for developing JavaScript applications and APIs. Bun is compatible with numerous Node.js APIs, but its distinguishing feature is its exceptional speed. If you have not yet explored Bun, it is highly recommended, particularly if you seek enhanced performance for running JavaScript and managing requests.
Step 1: Installing Bun
Before we start coding, 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 this command to install Bun:
curl -fsSL [https://bun.sh/install](https://bun.sh/install) | bash
After installing, check if Bun was installed successfully by running:
bun --version
If everything went well, you should see Bun's version number on the screen.
Step 2: Initializing Your Bun Project
With Bun installed, it's time to start a new project to build the API.
Create a new folder for your project and go into it:
mkdir my-bun-api cd my-bun-api
Set up the project using Bun:
bun init
This will create the basic project setup with
bunfig.toml
andpackage.json
.
Step 3: Create the HTML File to Serve
Before we start with the server code, let's make an HTML file that our API will send as a response.
Create a folder called
public
to store our static files, like HTML.mkdir public
Inside the
public
folder, make an HTML file namedindex.html
:touch public/index.html
Open
index.html
and add some simple HTML content:<h1>Welcome to the Bun API</h1> <p>This is an HTML response from your Bun API!</p>
Step 4: Writing the API Server Code
Now, let's set up the API server to handle requests and send back responses. We'll use Bun's built-in serve method for HTTP requests.
Create a file named server.js in the project folder:
touch server.js
Open server.js and add this 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 gives back a JSON message.
The /api/data endpoint takes POST requests, gets the data, and sends it back as JSON.
Serving HTML Content:
For the /api/html endpoint, we read the index.html file from the public folder using fs.readFileSync.
This HTML file's content is then sent as the response with a Content-Type: text/html header.
Step 5: Running the Server
Now that we've written the server code, let's run it!
Open your terminal and type this command:
bun run server.js
You should see this message:
http Server running on [http://localhost:3000](http://localhost:3000)
This means your server is now running at http://localhost:3000.
Step 6: Testing the API Endpoints in Postman
Let’s 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:
json { "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:
json { "name": "John" }
Click Send.
Expected Response:
json { "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):
Welcome to the Bun API
This is an HTML response fromyour Bun API!
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!