on
Italy
- Get link
- X
- Other Apps
01
02
03
04
05
06
07
08
09
10
11
| { "title": "How to Design RESTful API", "content": "RESTful API design is a very important case in the software development world.", "author": "huseyinbabal", "tags": [ "technology", "nodejs", "node-restify" ] "category": "NodeJS"} |
01
02
03
04
05
06
07
08
09
10
| POST /articles HTTP/1.1Host: localhost:3000Content-Type: application/json{ "title": "RESTful API Design with Restify", "slug": "restful-api-design-with-restify", "content": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", "author": "huseyinbabal"} |
1
2
3
| GET /articles/123456789012 HTTP/1.1Host: localhost:3000Content-Type: application/json |
I can make another POST request to /articles/update/123456789012 with the payload.Maybe preferable, but the URI is becoming more complex. As we said earlier, operations can refer to HTTP methods. This means, state the update operation in the HTTP method instead of putting that in the URI. For example:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
| PUT /articles/123456789012 HTTP/1.1Host: localhost:3000Content-Type: application/json{ "title": "Updated How to Design RESTful API", "content": "Updated RESTful API design is a very important case in the software development world.", "author": "huseyinbabal", "tags": [ "technology", "nodejs", "restify", "one more tag" ] "category": "NodeJS"} |
1
2
3
4
5
6
7
| POST /articles/123456789012/comments HTTP/1.1Host: localhost:3000Content-Type: application/json{ "text": "Wow! this is a good tutorial", "author": "john doe"} |
1
2
3
| GET /articles/123456789012/comments/123 HTTP/1.1Host: localhost:3000Content-Type: application/json |
1
2
3
| GET /comments/123456789012 HTTP/1.1Host: localhost:3000Content-Type: application/json |
/v1.1/articles/123456789012.
1
2
3
| GET /articles/123456789012 HTTP/1.1Host: localhost:3000Accept-Version: 1.0 |
| Resource Name | HTTP Verbs | HTTP Methods |
|---|---|---|
| Article | create Article update Article delete Article view Article |
POST /articles with Payload PUT /articles/123 with Payload DELETE /articles/123 GET /article/123 |
| Comment | create Comment update Coment delete Comment view Comment |
POST /articles/123/comments with Payload PUT /comments/123 with Payload DELETE /comments/123 GET /comments/123 |
| User | create User update User delete User view User |
POST /users with Payload PUT /users/123 with Payload DELETE /users/123 GET /users/123 |
01
02
03
04
05
06
07
08
09
10
11
12
13
| var mongoose = require("mongoose");var Schema = mongoose.Schema;var ArticleSchema = new Schema({ title: String, slug: String, content: String, author: { type: String, ref: "User" }});mongoose.model('Article', ArticleSchema); |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
| var mongoose = require("mongoose");var Schema = mongoose.Schema;var CommentSchema = new Schema({ text: String, article: { type: String, ref: "Article" }, author: { type: String, ref: "User" }});mongoose.model('Comment', CommentSchema); |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| var restify = require('restify') , fs = require('fs')var controllers = {} , controllers_path = process.cwd() + '/app/controllers'fs.readdirSync(controllers_path).forEach(function (file) { if (file.indexOf('.js') != -1) { controllers[file.split('.')[0]] = require(controllers_path + '/' + file) }})var server = restify.createServer();server .use(restify.fullResponse()) .use(restify.bodyParser())// Article Startserver.post("/articles", controllers.article.createArticle)server.put("/articles/:id", controllers.article.updateArticle)server.del("/articles/:id", controllers.article.deleteArticle)server.get({path: "/articles/:id", version: "1.0.0"}, controllers.article.viewArticle)server.get({path: "/articles/:id", version: "2.0.0"}, controllers.article.viewArticle_v2)// Article End// Comment Startserver.post("/comments", controllers.comment.createComment)server.put("/comments/:id", controllers.comment.viewComment)server.del("/comments/:id", controllers.comment.deleteComment)server.get("/comments/:id", controllers.comment.viewComment)// Comment Endvar port = process.env.PORT || 3000;server.listen(port, function (err) { if (err) console.error(err) else console.log('App is ready at : ' + port)})if (process.env.environment == 'production') process.on('uncaughtException', function (err) { console.error(JSON.parse(JSON.stringify(err, ['stack', 'message', 'inner'], 2))) }) |
2 in Accept-Version header, viewArticle_v2 will be executed. viewArticle and viewArticle_v2 both do the same job, showing the resource, but they show Article resource in a different format, as you can see in the title
field below. Finally, the server is started on a specific port, and
some error reporting checks are applied. We can proceed with controller
methods for HTTP operations on resources.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
| var mongoose = require('mongoose'), Article = mongoose.model("Article"), ObjectId = mongoose.Types.ObjectIdexports.createArticle = function(req, res, next) { var articleModel = new Article(req.body); articleModel.save(function(err, article) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { res.json({ type: true, data: article }) } })}exports.viewArticle = function(req, res, next) { Article.findById(new ObjectId(req.params.id), function(err, article) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { if (article) { res.json({ type: true, data: article }) } else { res.json({ type: false, data: "Article: " + req.params.id + " not found" }) } } })}exports.viewArticle_v2 = function(req, res, next) { Article.findById(new ObjectId(req.params.id), function(err, article) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { if (article) { article.title = article.title + " v2" res.json({ type: true, data: article }) } else { res.json({ type: false, data: "Article: " + req.params.id + " not found" }) } } })}exports.updateArticle = function(req, res, next) { var updatedArticleModel = new Article(req.body); Article.findByIdAndUpdate(new ObjectId(req.params.id), updatedArticleModel, function(err, article) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { if (article) { res.json({ type: true, data: article }) } else { res.json({ type: false, data: "Article: " + req.params.id + " not found" }) } } })}exports.deleteArticle = function(req, res, next) { Article.findByIdAndRemove(new Object(req.params.id), function(err, article) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { res.json({ type: true, data: "Article: " + req.params.id + " deleted successfully" }) } })} |
articleModel sent from the request body. A new model can be created by passing the request body as a constructor to a model like var articleModel = new Article(req.body). findOne with an ID parameter is enough to return article detail.save command.findByIdAndRemove is the best way to delete an article by providing the article ID.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
| var mongoose = require('mongoose'), Comment = mongoose.model("Comment"), Article = mongoose.model("Article"), ObjectId = mongoose.Types.ObjectIdexports.viewComment = function(req, res) { Article.findOne({"comments._id": new ObjectId(req.params.id)}, {"comments.$": 1}, function(err, comment) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { if (comment) { res.json({ type: true, data: new Comment(comment.comments[0]) }) } else { res.json({ type: false, data: "Comment: " + req.params.id + " not found" }) } } })}exports.updateComment = function(req, res, next) { var updatedCommentModel = new Comment(req.body); console.log(updatedCommentModel) Article.update( {"comments._id": new ObjectId(req.params.id)}, {"$set": {"comments.$.text": updatedCommentModel.text, "comments.$.author": updatedCommentModel.author}}, function(err) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { res.json({ type: true, data: "Comment: " + req.params.id + " updated" }) } })}exports.deleteComment = function(req, res, next) { Article.findOneAndUpdate({"comments._id": new ObjectId(req.params.id)}, {"$pull": {"comments": {"_id": new ObjectId(req.params.id)}}}, function(err, article) { if (err) { res.status(500); res.json({ type: false, data: "Error occured: " + err }) } else { if (article) { res.json({ type: true, data: article }) } else { res.json({ type: false, data: "Comment: " + req.params.id + " not found" }) } } })} |
/articles/123 (Good), /articles?id=123 (Bad).
Comments
Post a Comment