Looking to build a super fast API? Meet Bun—a sleek, high-performance JavaScript runtime that’s making waves in the dev community. In this blog post, I’m going to show you how to create a simple API using Bun that’s fast and easy to set up.🎉
What’s Bun? 🤔
Bun is a super-fast JavaScript runtime that’s optimized for speed. It comes with built-in features like a bundler, transpiler, and web server. Basically, it’s everything you need in one package—no more juggling multiple tools! ⚡
If you're tired of slow build times, Bun’s got you covered. Let’s dive in! 😎
Step 1: Install Bun 📥
First things first—let’s get Bun installed on your machine. Just pop open your terminal and run:
powershell -c "irm bun.sh/install.ps1 | iex"
Once it's done, verify everything is working by running:
bun --version
You should see the Bun version pop up, and you're good to go! 🎉
Step 2: Set Up Your Project 💻
Now, let’s set up your project folder. Create a new directory and jump in:
mkdir bun-api
cd bun-api
bun init
That’s it! You’re all set up with a fresh Bun project. 😄
Step 3: Build Your API with Bun â›…
Now that your project is ready, let’s write a simple API using Bun. In this example, we will create several endpoints like /products
, /login
, /cart
, and more, along with a logging feature to track requests made to the server.
Here’s the code:
Bun.serve({
fetch(req) {
return new Response("Bun!");
},
});
const server = Bun.serve({
port: 8050,
fetch(req) {
const url = new URL(req.url);
const method = req.method;
const timestamp = new Date().toISOString();
const logMessage = `[${timestamp}] ${method} ${url.pathname}\n`;
// Log request to the file 'log.txt'
fs.appendFileSync("log.txt", logMessage);
switch (url.pathname) {
case "/":
return new Response("Welcome to BarterX");
case "/products":
return new Response("Here are the products up for sale in BarterX");
case "/login":
return new Response("Login to BarterX");
case "/signup":
return new Response("Sign up to BarterX");
case "/profile":
return new Response("Trader Profile");
case "/cart":
return new Response("Your Shopping Cart is here");
case "/checkout":
return new Response("Let's start shipping");
case "/orders":
return new Response("Your Orders are here");
case "/api/products":
const apiData = [
{ id: 1, name: "Used Laptop", price: 300 },
{ id: 2, name: "Second-hand Bicycle", price: 50 },
];
return new Response(JSON.stringify(apiData), {
headers: { "Content-Type": "application/json" },
});
case "/categories":
return new Response("Browse Categories");
case "/chat":
return new Response("Your Chat with fellow Traders");
case "/contact":
return new Response("Contact Us at");
case "/about":
return new Response(Bun.file("./public/about.html"), {
headers: { "Content-Type": "text/html" },
});
case "/styles":
return new Response(Bun.file("./public/style.css"), {
headers: { "Content-Type": "text/css" },
});
default:
return Response.json(
{ error: "Page not found", statusCode: 404 },
{
status: 404,
headers: { "Content-Type": "application/json" },
}
);
}
},
});
// Server running message
console.log(`Server is running at http://localhost:${server.port}`);
Explanation of the Code:
Logging: Every request made to the server is logged to a
log.txt
file, capturing the timestamp, HTTP method, and URL pathname.API Routes: The API serves various endpoints:
GET requests for paths like
/products
,/cart
,/login
, etc.API Data: The
/api/products
route returns a list of products in JSON format.Static Files: Routes like
/about
and/styles
serve HTML and CSS files.
Error Handling: If a route isn’t defined, the server returns a
404
response with a JSON error message.
Step 4: Run Your API 🔥
Once your code is ready, run the server using:
bun index.js
Your API will be running on http://localhost:8050
. 🎉
Step 5: Test It Out 🚀
To test your new API, you can use Postman, cURL, or just open a browser.
GET Request: Access
http://localhost:8050/api/products
and get a list of products in JSON format.Static File Serving: Access
http://localhost:8050/about
to see the HTML file you served.
Use the following cURL command to check if your /api/products
endpoint is working:
curl http://localhost:8050/api/products
It will return:
[
{ "id": 1, "name": "Used Laptop", "price": 300 },
{ "id": 2, "name": "Second-hand Bicycle", "price": 50 }
]
Step 6: Wrap Up ✨
You’ve just created a powerful and fast API using Bun! 🥳
To recap:
Installed Bun: ✅
Set up the project: 🎉
Built the API: Including dynamic routes and static file serving 🚀
Tested the API: 🧪
Bun makes it incredibly easy and fast to build APIs, and you can scale it up as needed. If you're building a small project or a large-scale application, Bun is a great choice!
Next Steps 🚀
Explore more: Check out Bun’s docs for advanced features like WebSockets and database integration! 📚
Scale it up: Add user authentication, persistent storage, and more! 📈
Thanks for reading, and happy coding! Feel free to ask any questions or leave comments below! 💬