Write a post

Creating a Simple Movie Store API with Swagger

Published Jan 03, 2017Last updated Jan 18, 2017
Creating a Simple Movie Store API with Swagger

This tutorial will help you understand what Swagger is and how to specify your APIs with it. You'll learn to create a specification file for your API, which will act as a base for documentation, spec sheet for developers, and will generate code for you to work on in your choice of language.

Prerequisites

You should know what REST APIs are and how they work. It'll also be helpful if you know how to write YAML.

What are The OpenAPI Initiative and Swagger?

The goal of The OpenAPI Specification (as indicated here) is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the service without access to source code, documentation, or through network traffic inspection.

Swagger is a project, based on the OpenAPI Initiative, used to describe and document RESTful APIs. The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages.

Preparing to write our First Specification

File Format

We can write the Swagger Specification file in two formats, JSON and YAML. For this tutorial, we'll be using YAML to write our specification file. The Specification file gets big as we add endpoints in our API. YAML is quite clean and readable for humans for such big file sizes in comparison to JSON.

Editor

We can use any text editor for creating our specification file. But for this tutorial, we'll be using a built-in tool called the Swagger Editor. It has a number of features like Instant visualization of API, Autocompletion, and others that'll help us conveniently design our API.

For this tutorial, we'll be using the online Swagger editor to design our API. Head over to the Online Editor to get started.

Creating a Basic API

We'll start with a bare minimum file that is valid Swagger specification.

swagger: "2.0"            # Swagger version

info:                     # This object provides metadata about the API.
  version: 1.0.0            
  title: Movie Store
  description: A simple Movie Store API

basePath: /api            # Path relative to which all API calls will be made 

paths: {}                 # This Object defines the paths/endpoints of your API

We have three required root properties, swagger, info, and paths.

  • We need to provide the version of Swagger we're working with.
  • The info object is used to define metadata like version, title, description, and other information about the API.
  • The paths object is used to define our API endpoints.

Adding operations

In order to understand Swagger better, let's create a simple specification for a Movie Store API. Let's add some operations to our API.

GET

We'll begin by adding an operation to get the list of all Movies the store has. remove the curly braces after the paths object and add an endpoint called /movies. We also need to add an operation to this path (an HTTP method). After adding an endpoint and an operation on it, your specification file will look like:

# The header we defined before will come here

paths:
  /movies:
    get:
      description: Returns all movies from the system
      operationId: findMovies
      parameters:
      - name: tags
        in: query
        description: Tags used to filter the result
        required: false
        type: array
        items:
          type: string
        collectionFormat: csv
      - name: limit
        in: query
        description: maximum number of results to return
        required: false
        type: integer
        format: int32
      responses:
        '200':
          description: A list of movies
          schema:
            type: array
            items:
              $ref: '#/definitions/Movie'

definitions:
  Movie:
    type: object
    properties:
      movie_id:
        type: string
        description: Unique identifier representing a specific Movie.
      title:
        type: string
        description: Title of the movie.
      description:
        type: string
        description: Description of the movie.
      rating:
        type: number
        description: Rating of the movie.
      price:
        type: number
        description: Price of the Movie at the store.
      image:
        type: string
        description: Image URL containing the movie poster.

Lets dissect this operation to understand whats going on here.

The paths object:

  • /movies is the endpoint.
  • get is the HTTP method.
  • operationId is a unique identifier for this operation.
  • parameters object is a list of parameters for the endpoint. We have two optional parameters here, name and limit.
  • responses object lists the responses this operation can produce.
  • $ref is used to refer to another part of your file.

The definitions object

We use this object to define different models our API will receive from the clients as well as those it'll send in responses. We've defined a Movie object with parameters like title, description, etc., and the type they're gonna be. Swagger puts constraints according to the data types of these objects when building the code. The descriptions here will automatically be included in our API documentation.

That is all we need to define an operation for our API. This operation will be available on the route: /api/movies. This is because we set our basePath property to /api in the header. Swagger automatically generates the documentation for this path for us.

So this operation gets us the list of all movies. What if we want to get a movie by its ID? We'll create another operation for this endpoint which will accept a parameter (movie_id) and will return the movie associated with it.

  /movies/{movie_id}:
    get:
      description: Returns a single movie by its movie_id
      parameters:
        - name: movie_id
          in: path
          required: true
          description: The movie's movie_id
          type: string
      responses:
        200:
          description: A Movie
          schema:
            $ref: '#/definitions/Movie'
        404:
          description: The Person does not exists.

We are accepting the movie_id parameter as the last value on our path. This will return the movie whose ID matches, else, it'll give us a 404 error.

POST

We have created 2 GET operations. Now we'll create a POST operation. This operation requires that we send a body with our request. Note that this wasn't possible with the GET operation. Add the following operation under your /movies endpoint.

/movies:
  post:
    description: Add a new movie to the collection
    operationId: addMovie
    parameters: 
    - name: movie
      in: body
      description: The Movie JSON you want to post
      schema: 
        $ref: '#/definitions/Movie'
    responses:
      '201':
        description: Movie created successfully
        schema:
          $ref: '#/definitions/Movie'

We earlier put the parameter movie_id in the GET operation in our path. Now we require the Movie in the body of the request. Swagger supports many more HTTP verbs that you can use for a route.

Generating code

Once you have created your API spec, you can get the server code by selecting Generate Server > <your-programming-language>. You'll get a copy of the API code. Install the dependencies of the code and run the server.

Your API will be available on the /<basePath>/. The docs will be available on /docs. You can use the docs to test out the API. There are a plethora of options available to tinker with your API in the docs.

Now you can customize the code to suit your requirements.

Conclusion

Swagger is an amazing tool for designing and documenting APIs. There are a lot of features of Swagger we haven't talked about in this short tutorial. You can learn more about swagger from the examples on the online editor.

Discover and read more posts from Ayush Gupta
get started
Enjoy this post?

Leave a like and comment for Ayush

RESTful CRUD Operations in Meteor.js
How to Use json-server to Create Mock APIs
How to Build a Simple Blog Using Node.js