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:

    x-swagger-router-controller: posts
      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:

        - name: post
          in: body
          description: The posts contents
          required: true
            $ref: '#/definitions/Post'

And, the permissible responses:

          description: Created
            $ref: '#/definitions/SuccessResponse'
          description: Bad Request
            $ref: '#/definitions/ErrorResponse'

And, lastly the schema defintions:

      - title
      - markdown
      - html
        type: string
        description: The posts title -> My First Blog Post.
        type: string
        description: The posts slug -> my-first-blog-post.
        type: string
        description: The posts Markdown content.
        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); {
    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: