Introduction
Bun is an incredibly fast JavaScript runtime that is gaining traction for its speed and simplicity. With built-in support for various features like HTTP servers, file watching, and transpilation, Bun makes building APIs a breeze. In this blog, we'll go through the steps to create a simple API endpoint using Bun.
What is Bun?
Bun is a modern JavaScript runtime built from the ground up to be fast. It includes a bundler, a task runner, and a test runner, making it a one-stop solution for JavaScript and TypeScript development.
Why Use Bun for APIs?
Speed: Bun is built in Zig, which gives it lightning-fast performance.
Built-in HTTP support: No need to install extra libraries like Express.
Developer-friendly: Built-in TypeScript and JSX support out of the box.
Step 1: Install Bun
Before we start, you need to have Bun installed. If you don’t have it yet, you can install it by running:
bashCopyEditcurl -fsSL https://bun.sh/install | bash
Verify the installation:
bashCopyEditbun --version
Step 2: Create a New Bun Project
Run the following command to initialize a new Bun project:
bashCopyEditbun create my-api
Navigate to the project directory:
bashCopyEditcd my-api
Step 3: Set Up Your API Server
Bun provides a built-in HTTP server, so there's no need for additional dependencies. Let's create a simple API endpoint. Open index.
js (or create one if it doesn't exist) and add the following code:
typescriptCopyEditimport { serve } from "bun";
const server = serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api") {
return new Response(
JSON.stringify({ message: "Hello from Bun API!" }),
{
headers: { "Content-Type": "application/json" },
}
);
}
return new Response("Not Found", { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);
Step 4: Run Your Server
Start the server by running:
bashCopyEditbun index.ts
Visit http://localhost:3000/api
in your browser or use a tool like Postman. You should see the JSON response:
jsonCopyEdit{
"message": "Hello from Bun API!"
}
Step 5: Extend Your API
You can easily add more endpoints. For example:
typescriptCopyEditif (url.pathname === "/api/greet") {
const name = url.searchParams.get("name") || "Guest";
return new Response(
JSON.stringify({ message: `Hello, ${name}!` }),
{ headers: { "Content-Type": "application/json" } }
);
}
Conclusion
In just a few steps, you can create and run a blazing-fast API using Bun. Whether you’re building a small project or scaling up, Bun’s speed and simplicity make it a great choice for modern development.
What do you think about Bun for API development? Share your thoughts in the comments below!