Press "Enter" to skip to content

Express Rest Api

Selahaddin Erdoğan 0

İlk olarak  npm init –y komutu ile package.json oluşturulur. Oluşan dosyada scripts altında test ve start konfigürasyonları yapılır. Bu sayede proje terminalden npm start komutu ile kısayoldan çalıştırabilir.

“start”: “node src/index.js” –scripts altına yazılır.

Sıradaki adımda Express kurulumu yapılır. npm install express terminalden çalıştırılarak kurulum tamamlanır.

Artık geliştirmeye başlanabilir. İlk olarak src dizini altına index.js oluşturabiliriz. Daha sonra endpointe istek atabilmek için .http uzantılı dosya oluşturularak vs code içerisinde REST CLİENT eklentisi kurulur.

//express frameworkprojeye dahil edilir.

const express = require("express");

//app oluşturulur ve uygulama yapılandırmaları bu app üzerindne ilerler.

const app = express();

app.use(express.json());

const PORT = 3000;

const API_KEY = "denemekey";

//middleware configlerini yapıyoruz.


function middlewareConfig(req, res, next) {

//Api Key kontrolü

const key = req.header('x-api-key');

if (!key) {


const response = errorResponse("Api key boş olamaz");

return res.status(401).json(response);

}


if (key !== API_KEY) {

const response = errorResponse("Geçersiz Api Key");

return res.status(403).json(response)


}

next();

}

//middlewareconfig fonksiyonu uygulamaya eklenir

app.use(middlewareConfig);


//db yerine localde tanımlı bir liste tutuyoruz

let id = 1;

const orders = [];


//response tanımları yapılır

//genel olarak response yapısı API designe bağlı kalarak yapıldı.

function succesResponse(message, data) {

return {

success: true, error: null, data: data, meta:


{ version: 1, message: message, timestamp: new Date().toISOString(), size: data ? data.length : 0 }

};



}

function errorResponse(message) {

return {


success: false, error: { message: message }, data: null, meta:

{ version: 1, timestamp: new Date().toISOString() }

};

}


//listeye default olarak 1 eleman ekliyoruz.

const orderDefault = { customer: "Serdoğan", orderName: "burger", id: id++ };

orders.push(orderDefault);


// routing işlemi app üzerinden yapılabilirdi. Bu yazıda express Router kullanıldı
const router = express.Router();

// rest metodlarını yazıyoruz //Select işlemlerinde response code 200 , güncellemede ve silmede 204, insert de 201 //204 dönende response olmaz. Güncelleme için 204 dışında 200 yada 201 de kullanılabilir //tüm siparişleri listeleme

router.get("/", (req, res) => {


return res.status(200).json(succesResponse("All orders listed", orders));


});


//tüm siparişleri listeleme



//id bazlı listeleme

router.get("/:id", (req, res) => {


//id requestte params üzerinde taşınır

const id = Number(req.params.id);

if (isNaN(id)) {

return res.status(400).json(errorResponse("invalid id format"));

}


const orderIndex = orders.findIndex(a => a.id === id);


const order = orders[orderIndex];

if (orderIndex !== -1) {


return res.status(200).json(succesResponse(null, order));


}


return res.status(404).json(errorResponse("order not found"));


});

//ekleme

router.post("/", (req, res) => {

const body = req.body;

if (body) {


const error = validateBody(body);


if (!error) {


const { orderName, customer } = body;

const orderTemp = { orderName: orderName, customer: customer, id: id++ }

orders.push(orderTemp);


return res.status(201).json(succesResponse("order was created was succesfuly", orderTemp));

}

console.log(error.error.message);

return res.status(400).json(errorResponse(error.error.message));


}


return res.status(404).json(errorResponse("Request must not empty"));


});




//request body validasyonu

function validateBody(body) {


const { customer, orderName } = body;


if (!customer) {


return { error: { message: "customer must not empty" } };

}

if (!orderName) {

return { error: { message: "orderName must not empty" } };

}


return null;


}

//silme

router.delete("/:id", (req, res) => {

const idParams = Number(req.params.id);

if (isNaN(idParams)) {

return res.status(400).json(errorResponse("Invalid id format"));


}


const orderIndex = orders.findIndex(a => a.id == idParams);


if (orderIndex == -1) {

return res.status(404).json(errorResponse("Order Not found"));

}

orders.splice(orderIndex, 1);

return res.status(204).json(succesResponse("", orders));



});


//güncelleme

router.put("/:id", (req, res) => {

const idParams = Number(req.params.id);


if (isNaN(idParams)) {

return res.status(400).json(errorResponse("Invalid İd format"));

}

const body = req.body;

if (body) {

const error = validateBody(req.body);

if (error) {


return res.status(400).json(errorResponse(error.error.message));

}

const orderIndex = orders.findIndex(a => a.id === idParams);

if (orderIndex == -1) {


return res.status(404).json(errorResponse("order not found"));

}

const { customer, orderName } = req.body;

const newOrder = { customer: customer, orderName: orderName ,id:idParams };


orders[orderIndex] = newOrder;

return res.status(200).json(succesResponse("Updated order succesfuly"));

}


return res.status(400).json(errorResponse("Request body must not empty"));

});


app.use("/api/v1/orders", router);


app.get("/", (req, res) => {


return res.status(200).json(succesResponse("Api was running 3000 port. /api/v1/orders default path", null));


});


app.listen(PORT, () => {


console.log("SErver is running on " + PORT + " port");


});

 

 

 

.http uzantılı test requestlerini barındıran dosya

 

 

 

### ROOT (API çalışıyor mu?)

GET http://localhost:3000/

x-api-key: denemekey




### GET ALL orderS

GET http://localhost:3000/api/v1/orders

x-api-key: denemekey



### GET order BY ID (başarılı)

GET http://localhost:3000/api/v1/orders/1

x-api-key: denemekey

### GET order BY ID (geçersiz id)

GET http://localhost:3000/api/v1/orders/abc

x-api-key: denemekey

### CREATE order

POST http://localhost:3000/api/v1/orders

Content-Type: application/json

x-api-key: denemekey

{

"orderName": "orderfield",

"customer": "testcustomer"

}


### UPDATE order

PUT http://localhost:3000/api/v1/orders/1

Content-Type: application/json

x-api-key: denemekey

{

"orderName": "OrderNameupdate",

"customer": "José Mauro"

}

### UPDATE order (bulunamaz)

PUT http://localhost:3000/api/v1/orders/999

Content-Type: application/json

x-api-key: denemekey

{

"orderName": "Test",

"customer": "Test"

}


### UPDATE order (bulunamaz)

DELETE  http://localhost:3000/api/v1/orders/3

Content-Type: application/json

x-api-key: denemekey


### DELETE order (bulunamaz)

DELETE http://localhost:3000/api/v1/orders/999

x-api-key: denemekey


### API KEY YOK (401)

GET http://localhost:3000/api/v1/orders

### API KEY HATALI (401)

GET http://localhost:3000/api/v1/orders

x-api-key: yanlışkey



### CREATE order (Eksik Alan - 400)

POST http://localhost:3000/api/v1/orders

Content-Type: application/json

x-api-key: denemekey


{

"orderName": "Eksik Alan"

}

Comments are closed.