Cara Membuat REST API Sederhana dengan Node.js & Express
Cara Membuat REST API Sederhana dengan Node.js & Express”**.
---
# Cara Membuat REST API Sederhana dengan Node.js & Express
REST API (Representational State Transfer – Application Programming Interface) adalah cara standar untuk menghubungkan aplikasi frontend (seperti website atau mobile app) dengan backend (server). Dalam artikel ini kita akan membuat API sederhana menggunakan **Node.js** dan **Express.js**.
---
## Persiapan
1. Pastikan Node.js sudah terinstal di komputer (cek dengan `node -v`).
2. Buat folder baru untuk project, misalnya:
```bash
mkdir rest-api-express
cd rest-api-express
```
3. Inisialisasi project Node.js:
```bash
npm init -y
```
4. Install Express:
```bash
npm install express
```
---
## Membuat Server Dasar
Buat file `index.js` lalu isi dengan kode berikut:
```javascript
const express = require('express');
const app = express();
const port = 3000;
// Middleware untuk parsing JSON
app.use(express.json());
// Route sederhana
app.get('/', (req, res) => {
res.send('Hello World! REST API dengan Express');
});
// Menjalankan server
app.listen(port, () => {
console.log(`Server berjalan di http://localhost:${port}`);
});
```
Jalankan dengan:
```bash
node index.js
```
---
## Membuat Endpoint CRUD
Misalkan kita ingin membuat API untuk **data buku**. Tambahkan kode berikut:
```javascript
let books = [
{ id: 1, title: 'Belajar Node.js', author: 'Enomco' },
{ id: 2, title: 'Belajar Express', author: 'Developer' }
];
// GET semua buku
app.get('/books', (req, res) => {
res.json(books);
});
// GET detail buku berdasarkan ID
app.get('/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
book ? res.json(book) : res.status(404).json({ message: 'Buku tidak ditemukan' });
});
// POST tambah buku baru
app.post('/books', (req, res) => {
const newBook = {
id: books.length + 1,
title: req.body.title,
author: req.body.author
};
books.push(newBook);
res.status(201).json(newBook);
});
// PUT update buku
app.put('/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (book) {
book.title = req.body.title || book.title;
book.author = req.body.author || book.author;
res.json(book);
} else {
res.status(404).json({ message: 'Buku tidak ditemukan' });
}
});
// DELETE hapus buku
app.delete('/books/:id', (req, res) => {
books = books.filter(b => b.id !== parseInt(req.params.id));
res.json({ message: 'Buku berhasil dihapus' });
});
```
---
## Menguji API
Gunakan **Postman** atau **cURL** untuk mencoba endpoint:
* `GET http://localhost:3000/books` → lihat semua buku
* `POST http://localhost:3000/books` (dengan body JSON) → tambah buku baru
* `PUT http://localhost:3000/books/1` → update buku dengan id=1
* `DELETE http://localhost:3000/books/1` → hapus buku
---
## Kesimpulan
Kita baru saja membuat **REST API sederhana** menggunakan Node.js dan Express. Dengan dasar ini, kamu bisa mengembangkan lebih jauh: menambahkan database (MySQL/MongoDB), autentikasi user (JWT), hingga deployment ke server.
---
Comments
Post a Comment