Intro to REST API
REST ( REpresentational State Transfer )
개발을 할 때 Server 와의 Communication 이 필요할 때는 Server 에 Request 를 하게되고, 오늘날 가장 권유되는 형태는 REST 이다.
REST는 Architectural Style 이라고 할 수 있는데, 이러한 Style 을 작업자 모두가 지키면 서로서로 편하게 작업할 수 있다. (API 의 형태가 어떻게 생길 지 쉽게 알 수 있기 때문에. )
REST 에서는 5가지의 Request Verb 가 사용되고, 종류는 다음과 같다.
- GET
- POST
- PUT
- PATCH
- DELETE
이제 하나하나 더 알아보도록 하자.
GET 은 CRUD 에서의 Read 와 같은 역할을 한다. 즉, 데이터를 가져온다.
POST 는 Create 와 같이 데이터를 생성할 때 쓰인다.
PUT, PATCH 는 Update 와 대응한다.
둘의 차이로는 PUT 의 경우 데이터 하나의 entity 내의 모든 properties 를 업데이트 할 때 사용,
PATCh 의 경우 entity 내에서 수정할 property (들) 만 업데이트 할 때 사용한다.
DELETE 는 당연히 Delete 와 대응하고, 데이터를 제거할 때 쓰인다.
각 Request Verb 의 간단한 사용 방법을 표기하면 아래와 같다. (NodeJS)
app.get(function(req, res) { } )
app.post(function(req, res) { } )
app.put(function(req, res) { } )
app.patch(function(req, res) { } )
app.delete(function(req, res) { } )
각 API 의 EndPoint 도 Request Verb 와 같이 일종의 규약이 있다.
만약 Google 에 있는 Database 자료 중 books, 또는 그 중의 refactoring 이라는 book 의 data 를 다룬다고 할 때 각 Verb 는 다음의 역할을 수행할 것으로 기대된다.
HTTP Verbs | /books | /books/refactoring |
GET | 모든 books 의 데이터 가져오기 | books 에서 refactoring 이라는 data 가져오기 |
POST | 새로운 book 생성 | |
PUT | refactoring 수정 | |
PATCH | refactoring 수정 | |
DELETE | 모든 books 제거 | refactoring 제거 |
아래는 위를 토대로 간단하게 만든 API 일부의 예시다.
app.route("/books")
.get(function(req, res){
Book.find(function(err, foundbooks){
if (!err) {
res.send(foundbooks)
} else {
res.send(err)
}
})
})
.post(function(req, res){
const newBook = new Book({
title: req.body.title,
content: req.body.content
})
newBook.save(function(err){
if (!err){
res.send("Successfully added a new book.")
} else {
res.send(err)
}
})
})
.delete(function(req, res){
Book.deleteMany(function(err){
if (!err){
res.send("Successfully deleted all books.")
} else {
res.send(err)
}
})
})
////////////////////////////////Requests Targetting A Specific Book////////////////////////
app.route("/books/:bookTitle")
.get(function(req, res){
Book.findOne({title: req.params.bookTitle}, function(err, foundBook){
if (foundBook) {
res.send(foundBook)
} else {
res.send("No books matching that title was found.")
}
})
})
.put(function(req, res){
Book.update(
{title: req.params.bookTitle},
{title: req.body.title, content: req.body.content},
{overwrite: true},
function(err){
if(!err){
res.send("Successfully updated the selected book.")
}
}
)
})
.patch(function(req, res){
Book.update(
{title: req.params.bookTitle},
{$set: req.body},
function(err){
if(!err){
res.send("Successfully updated book.")
} else {
res.send(err)
}
}
)
})
.delete(function(req, res){
Book.deleteOne(
{title: req.params.bookTitle},
function(err){
if (!err){
res.send("Successfully deleted the corresponding book.")
} else {
res.send(err)
}
}
)
})