Node.js kullanarak basit bir CRUD API projesi hazırlayacağız. Bu proje, Node.js ve Express framework’ü kullanarak bir API oluşturacak ve MongoDB’yi veritabanı olarak kullanacak.

Gereksinimler:

  • Node.js
  • MongoDB (Yerel veya MongoDB Atlas kullanabilirsiniz)
  • Express ve Mongoose npm paketleri

Adımlar:

1. Proje dizinini oluştur

Yeni bir proje klasörü oluştur ve terminali bu klasörde aç.

2. Node.js projesi başlat

npm init -y

Bu komut, package.json dosyasını oluşturacaktır.

3. Gerekli paketleri yükle

Projemiz için gerekli olan Express ve Mongoose gibi paketleri yükleyelim:

npm install express mongoose

Ek olarak geliştirme sürecinde kullanışlı olan nodemon paketini kurabiliriz:

npm install --save-dev nodemon

4. package.json dosyasında scripts bölümünü güncelle

nodemon ile projemizi çalıştırabilmek için package.json dosyasındaki scripts bölümünü aşağıdaki gibi düzenleyin:

"scripts": {
"start": "nodemon index.js"
}

5. Proje dizin yapısı

Basit bir dizin yapısı oluşturalım:

node-crud-api
├── models
│ └── Product.js
├── routes
│ └── product.js
└── index.js

6. Veritabanı bağlantısı ve API’nin temel yapısı (index.js)

index.js dosyasını oluşturup aşağıdaki kodu ekleyin. Bu dosya, Express uygulamasını başlatacak ve MongoDB ile bağlantı kuracak.

const express = require('express');
const mongoose = require('mongoose');
const productRoutes = require('./routes/product');
require('dotenv').config();

// Uygulama ve port tanımları
const app = express();
const PORT = process.env.PORT || 3000;

// Veritabanı bağlantısı
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB bağlantısı başarılı'))
.catch(err => console.error('MongoDB bağlantı hatası:', err));

// JSON verilerini okumak için middleware
app.use(express.json());

// Route tanımları
app.use('/api/products', productRoutes);

// Sunucuyu başlat
app.listen(PORT, () => {
console.log(`Sunucu ${PORT} portunda çalışıyor`);
});

7. Ürün modeli (models/Product.js)

Bir ürün (product) için MongoDB’de kullanılacak modeli tanımlayalım.

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
description: String,
inStock: { type: Boolean, default: true }
});

module.exports = mongoose.model('Product', productSchema);

8. CRUD işlemleri için rotalar (routes/product.js)

CRUD işlemlerini içeren API rotalarını yazalım. Burada ürün ekleme, listeleme, güncelleme ve silme işlemleri yapılacak.

const express = require('express');
const router = express.Router();
const Product = require('../models/Product');

// Yeni ürün oluştur
router.post('/', async (req, res) => {
try {
const newProduct = new Product(req.body);
const savedProduct = await newProduct.save();
res.status(201).json(savedProduct);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Tüm ürünleri getir
router.get('/', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// Tek bir ürünü getir
router.get('/:id', async (req, res) => {
try {
const product = await Product.findById(req.params.id);
if (!product) return res.status(404).json({ message: 'Ürün bulunamadı' });
res.json(product);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// Ürünü güncelle
router.put('/:id', async (req, res) => {
try {
const updatedProduct = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!updatedProduct) return res.status(404).json({ message: 'Ürün bulunamadı' });
res.json(updatedProduct);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Ürünü sil
router.delete('/:id', async (req, res) => {
try {
const deletedProduct = await Product.findByIdAndDelete(req.params.id);
if (!deletedProduct) return res.status(404).json({ message: 'Ürün bulunamadı' });
res.json({ message: 'Ürün silindi' });
} catch (err) {
res.status(500).json({ message: err.message });
}
});

module.exports = router;

9. .env dosyası oluştur

Veritabanı bağlantı bilgilerimizi gizli tutmak için .env dosyası oluşturun ve MongoDB bağlantı URI’sini buraya ekleyin.

MONGO_URI=...
PORT=3000

10. MongoDB’yi başlat ve projeyi çalıştır

MongoDB’yi yerel olarak çalıştırıyorsanız, MongoDB sunucusunun çalıştığından emin olun (örneğin, mongod komutuyla). Ardından, projeyi şu şekilde başlatabilirsiniz:

npm start

API Testi

Postman veya benzeri bir araçla aşağıdaki CRUD işlemlerini test edebilirsiniz:

  • GET: /api/products (Tüm ürünleri listele)
  • POST: /api/products (Yeni ürün ekle)
  • GET: /api/products/:id (Belirli bir ürünü getir)
  • PUT: /api/products/:id (Ürünü güncelle)
  • DELETE: /api/products/:id (Ürünü sil)

Artık Node.js ve MongoDB kullanarak basit bir CRUD API projesini tamamladık!

Son Yazılar

Kategoriler:

Rehber,