Creating APIs is an integral part of modern web development. Whether you're building a simple backend for a single-page app or designing a robust service for a large-scale application, you need tools that make the process efficient. Enter Bun ๐, a modern JavaScript runtime that simplifies the process with its built-in HTTP server. In this guide, weโll explore how to create API endpoints in Bun and why itโs an excellent choice for developers.
What is Bun? ๐ค
Bun is a high-performance JavaScript runtime designed to be blazing fast โก๏ธ. It combines a JavaScript runtime, a bundler, and a package manager into one cohesive tool. One of Bunโs standout features is its native HTTP server, which eliminates the need for external libraries like Express to create simple APIs. ๐จ
Getting Started ๐
To follow along, make sure you have Bun installed. If you havenโt installed it yet, you can do so by following the instructions on Bunโs official website. ๐ ๏ธ
Once installed, weโre ready to create a basic API endpoint in Bun. Letโs dive in! ๐
๐ How to Create Your First API Endpoint in Bun
In this section, weโll guide you step-by-step on how to create a simple API endpoint in Bun, with an easy way to change the port number. Bun makes it simple to build fast APIs, and weโll show you how to set up a basic server that you can customize.
โ๏ธ Setting Up the Server with a Custom Port
Letโs start by creating a simple API server in Bun. The port number can be set using a command when you run the server, making it flexible depending on your needs:
import { serve } from "bun";
// Get the port from the command line, default to 3000 if not provided
const port = process.argv[2] || 3000;
serve({
port: Number(port), // Convert the port to a number
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 });
},
});
๐ How It Works
Port Customization: We use
process.argv
to get the port number from the command you use to start the server. If you donโt specify a port, it will default to3000
. This gives you flexibility when running the server. ๐The
serve
Function: This is the main function that tells Bun to create an HTTP server. The server listens for requests and handles them using thefetch
function. ๐Request Handling: The
fetch
function checks the URL to see if it matches/api/hello
with aGET
request. If it does, it sends back a simple greeting. If not, it returns a404 Not Found
error. ๐ซ
๐ฅ๏ธ Running the Server
To start the server, save the file (for example, server.js
) and run this command in your terminal:
run server.js 5000
This will start the server on port 5000
. To test it, visit http://localhost:5000/api/hello
in your browser. You should see the following message:
{
"message": "Hello, Bun!"
}
If you donโt specify a port, the server will default to port 3000
. ๐
Adding Dynamic and Advanced Routing ๐ ๏ธ
To build more versatile APIs, letโs implement dynamic routing and support for different HTTP methods:
import { serve } from "bun";
serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
// Handle POST requests with a JSON body
if (url.pathname === "/api/greet" && req.method === "POST") {
return req.json().then((body) => {
const name = body.name || "Guest";
return new Response(
JSON.stringify({ message: `Hello, ${name}!` }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
});
}
// Dynamic route example: /api/user/:id
if (url.pathname.startsWith("/api/user/") && req.method === "GET") {
const userId = url.pathname.split("/").pop();
return new Response(
JSON.stringify({ userId, message: `User ID is ${userId}` }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
}
return new Response("Not Found", { status: 404 });
},
});
Features in This Example ๐
Dynamic Parameters: Extract dynamic segments like
userId
from the URL usingurl.pathname
. ๐JSON Parsing: Use Bunโs
req.json()
to parse incoming JSON payloads in POST requests. ๐ฆError Handling: Return a 404 response for undefined routes. ๐ซ
Testing the Endpoints ๐ป
GET Request to /api/user/:id
Run this command:
curl http://localhost:3000/api/user/123
Response:
{
"userId": "123",
"message": "User ID is 123"
}
POST Request to /api/greet
Send a POST request with JSON data:
curl -X POST http://localhost:3000/api/greet \
-H "Content-Type: application/json" \
-d '{"name": "Alice"}'
Response:
{
"message": "Hello, Alice!"
}
Why Use Bun for APIs? ๐
Blazing Performance: Bun is built for speed, leveraging Zig and optimized runtime design to outpace traditional JavaScript runtimes. โก๏ธ
Simplicity: Its built-in HTTP server removes the need for additional libraries like Express, simplifying your development process. ๐
All-in-One Tool: With a runtime, bundler, and package manager rolled into one, Bun streamlines your workflow. ๐
Conclusion ๐ฏ
Bun makes creating lightweight, high-performance APIs a breeze. Whether youโre developing a simple app or a production-ready system, Bunโs features like native routing and JSON parsing make it a top choice for modern web development. ๐
Try out Bun today and see how it can supercharge your API development! ๐