AI Insights
Generate a summary and suggested tags for this post.
Bikin REST API tanpa server, tanpa VPS, tanpa Docker? Bisa banget pakai Cloudflare Workers. Cukup file JavaScript, deploy, selesai — endpoint aktif di 300+ kota.

Setup Awal
npm create cloudflare@latest my-api
cd my-apiPilih Hello World Worker → TypeScript.
API Minimal (Manual Routing)
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/api/users" && request.method === "GET") {
return Response.json([
{ id: 1, name: "Faiz" },
{ id: 2, name: "Budi" }
]);
}
if (url.pathname === "/api/users" && request.method === "POST") {
const body = await request.json();
return Response.json({ ok: true, data: body }, { status: 201 });
}
return new Response("Not Found", { status: 404 });
}
};Pakai Hono (Recommended)
Hono adalah web framework super ringan yang cocok banget untuk Workers.
npm install honoimport { Hono } from "hono";
const app = new Hono();
app.get("/api/users", (c) => c.json([{ id: 1, name: "Faiz" }]));
app.post("/api/users", async (c) => {
const body = await c.req.json();
return c.json({ ok: true, data: body }, 201);
});
app.get("/api/users/:id", (c) => {
const id = c.req.param("id");
return c.json({ id, name: "User " + id });
});
app.put("/api/users/:id", async (c) => {
const id = c.req.param("id");
const body = await c.req.json();
return c.json({ id, ...body });
});
app.delete("/api/users/:id", (c) => {
const id = c.req.param("id");
return c.json({ deleted: id });
});
export default app;Integrasi KV Storage
Bikin KV namespace:
npx wrangler kv namespace create USERSUpdate wrangler.toml:
[[kv_namespaces]]
binding = "USERS"
id = "xxxxxxxxxxxx"Simpan & baca data:
app.post("/api/users", async (c) => {
const body = await c.req.json();
const id = crypto.randomUUID();
await c.env.USERS.put(id, JSON.stringify(body));
return c.json({ id, ...body }, 201);
});
app.get("/api/users/:id", async (c) => {
const data = await c.env.USERS.get(c.req.param("id"), "json");
if (!data) return c.json({ error: "Not found" }, 404);
return c.json(data);
});CORS Handling
import { cors } from "hono/cors";
app.use("/api/*", cors({ origin: "*" }));Deploy
npx wrangler deployEndpoint aktif di https://my-api.<user>.workers.dev.
HTTP Methods di REST API
| Method | Fungsi | Status Success |
|---|---|---|
| GET | Baca data | 200 |
| POST | Buat data baru | 201 Created |
| PUT | Update lengkap | 200 |
| PATCH | Update sebagian | 200 |
| DELETE | Hapus data | 204 No Content |
Kesimpulan
REST API di Cloudflare Workers = cepat, murah, global. Kombinasi Hono + KV cukup untuk kebanyakan API kecil-menengah. Kalau butuh SQL, upgrade ke D1. Kalau butuh file storage, pakai R2.
