In a previous post, I wrote about Swagger and how it can help you to model and build a RESTful API. In this post, I'll walk you through the steps required to create the API for the "Vardyger publishing platform".
The Object Model
The object model of our blogging platform is very simple. Each post
in the system represents a single transaction and is associated with an author
.
Model the URIs
We want to be able to create a post, obtain a list of our posts, retrieve an individual post, update a post, and delete a post. Given this, here is a list of URIs that we'll expose:
POST /posts
GET /posts
GET /posts/{id}
PUT /posts/{id}
DELETE /posts/{id}
Now, we'll use the Swagger CLI to create the scaffolding for a new API project:
cd ~/opt/WebStorm/projects/Vardyger/core
swagger project create server
The Swagger Editor
We can use the Swagger editor to model our API. From the project directory (e.g., /Vardyger/core/server), enter the following command:
swagger project edit
We'll start by modelling the POST /posts
URI, jump to the paths:
section of swagger.yaml
:
paths:
/posts:
x-swagger-router-controller: posts
post:
description: Adds a post to the posts collection.
operationId: addPost
First, we need to specify the path: /posts
and the operation: post
, followed by a description
and the operationId
.
Note: x-swagger-router-controller is a vendor extension (provided by the swagger-tools middleware) that specifies the name of the controller (posts.js) that will execute when this API operation is called. The operationId
must match the name of an exported function (e.g., addPost) in your controller:
module.exports = {
addPost: addPost,
findPosts: findPosts,
findPostById: findPostById,
updatePost: updatePost,
deletePost: deletePost
}
We also need to specify the parameters:
parameters:
- name: post
in: body
description: The posts contents
required: true
schema:
$ref: '#/definitions/Post'
And, the permissible responses:
responses:
201:
description: Created
schema:
$ref: '#/definitions/SuccessResponse'
400:
description: Bad Request
schema:
$ref: '#/definitions/ErrorResponse'
...
And, lastly the schema defintions:
definitions:
Post:
required:
- title
- markdown
- html
properties:
title:
type: string
description: The posts title -> My First Blog Post.
slug:
type: string
description: The posts slug -> my-first-blog-post.
markdown:
type: string
description: The posts Markdown content.
html:
type: string
description: The posts HTML content.
...
The addPost
operation, in the posts.js
controller:
function addPost(req, res) {
var model = new Post(req.body);
model.save(function(error) {
if (! error) {
returnId(res, status.CREATED, model._id);
} else {
returnError(res, status.INTERNAL_SERVER_ERROR);
}
});
}
...
Now, we can launch the API:
swagger project start
And, navigate to http://localhost:10010/docs
: