August 23, 2017 By Vidyasagar Machupalli 6 min read

Modelling OpenAPI – Swagger 2.0 Specification using API Connect

In this post, you will learn how to model and generate an OpenAPI (swagger 2.0) specification using API Connect on IBM Cloud. Also, you will be drafting, securing and publishing an API talking to a NoSQL database in this case Cloudant.

Note: The OpenAPI – Swagger 2.0 specification generated (in YAML) through this post is used for IBM Mobile Foundation Adapter generation, which will be discussed in a later post.

The OpenAPI specification (formerly known as the Swagger Specification) is a powerful definition format to describe RESTful APIs. The specification creates a RESTful interface for easily developing and consuming an API by effectively mapping all the resources and operations associated with it. It’s easy-to-learn, language agnostic, and both human and machine readable.

For this post, you will create an API for a telecom provider to GET billing details. Before jumping into the details, let’s step back and understand what is API Connect and what does it offer?

IBM API Connect is a modern API management solution for creating, running, managing and securing APIs for external and internal consumers to accelerate an organization’s API Program and capture new revenue through compelling new customer experiences.

API lifecycle

Creating API Connect Service

Creating and publishing an API

Once API Connect service is successfully created

  • Navigate to your dashboard. Under Services, click on APIs to open dashboard.

  • Select the API Connect service which we created earlier.

Let’s draft the API. On the API Connect Dashboard,  navigate to “Drafts” and then click on APIs -> Add

  • Navigate to “Drafts” and then click on APIs -> Add New API

  • Provide a name to your API eg., mobile or telecom or telecon as this API is for a telecom provider.
  • Add the API to a product (Products provide a method by which you can group APIs into a package that is intended for a particular use.)

  • Publish the API to a Sandbox.

Designing an API leads to Swagger 2.0 (yaml) specification

You will be designing the API under ‘Design’ tab.

  • Set the schema to ‘https’

  • Verify the Base Path 

  • Produces should be ‘application/json’

  • To secure your API, you will be creating a Security definition and API Connect provides you with three options

    • API Key

    • Basic

    • OAuth

  • By default, API Connect generated an API Key (clientIdHeader) with parameter name X-IBM-Client-Id

  • The next step is to create a path – /billing which automatically provides a GET Operation. Save the API by clicking on the “Save” Icon on the Top ribbon.

  • Before adding Definitions and Tags, let’s see you Swagger 2.0 spec under Source tab

  • If you observe, definitions in the Swagger 2.0 is an empty object. A JSON schema definition is required here. There is a need for JSON data store. For this, you will create a Cloudant NoSQL DB with dummy documents.

Note: You can use any database of your choice. Good to have a provision to play with the data via simple CRUD operation. 

Creating a Cloudant Service

  • Open the Bluemix catalog https://new-console.ng.bluemix.net/catalog/?category=data  and within Data & Analytics select Cloudant NoSQL DB.

  • Provide a unique name and select lite plan.

  • Click on Create to provision a new Cloudant Service.

  • Click on Launch which will take you to Cloudant Dashboard.

  • Create a new database and add a new document. Copy and  the below JSON under _id field of the document

    {
    "_id" :"", -- skip this as it's already part of the document
    "provider": "telco", 
    "generated_date": "2017-08-04", 
    "bill_amount": "568", 
    "plan": "Corporate",
    "mobile": "998XXXX0000"
     }
  • Create multiple documents.

  • To read the JSON via your API, create a Cloudant View named “findall” with a Map Function shown below. The view retrieves all the documents.

  • Click on JSON on the Top ribbon to see the complete JSON.

  • Copy the JSON and the URL. Save it in a text editor for future reference.

  • On the Cloudant Dashboard, Click on Permissions.

  • Click on “Generate API Key” to create a new API key with _reader permission. Save the username and password – you will require this while Assembling the API.

Adding definition and Assemble your API

  • Heading back to API Connect dashboard, you will now create an API definition and use the Cloudant generated JSON saved in the earlier step to generate a schema. Save the API.

  • Select /billing under Paths -> RESPONSES -> Schema point to ‘billing’ definition.

  • Create a Tag by selecting Tags on the left pane. The name should be same as your API name; for consistency.

  • Click on Assemble and select “DataPower Gateway policies” on the left pane.

  • Click on Invoke.

  • On the right pane, paste the URL, username, and password (saved in the earlier step) into the respective fields provided.

  • Select GET as your HTTP method.

  • Save the API.

  • Time to test the API – Click on the “Run” icon on the top ribbon.

  • Select the product from the drop-down to which the API is mapped to.

  • Click on ‘Republish Product’ to make sure that the product is up-to-date with the changes.

  • Select GET /billing and Invoke to see the JSON read from Cloudant database after a security handshake.

Generate swagger 2.0 spec as YAML.

It’s time to update the Host of your API which currently points to $(catalog.host) and Base Path.

  • Click on Explore on the top ribbon and select Sandbox.

  • Select your API and copy the URL

Note: Use this URL with X-IBM-Client-Id value in the header for testing via Postman or any other REST Client.

  • Replace Host of your API with the copied URL’s Host value as shown in the image below.

  • Replace Base Path of your API with the Base Path value of Sandbox.

  • Save the API.

  • Let’s generate and download the YAML (Swagger 2.0)

The final Open API Specification should look like this

---<br>
swagger: "2.0"<br>
info:<br>
  x-ibm-name: "telecon"<br>
  title: "telecon"<br>
  version: "1.0.0"<br>
schemes:<br>
- "https"<br>
host: "api.us.apiconnect.ibmcloud.com"<br>
basePath: "/dev-advocates-demos/sb/telecon"<br>
consumes:<br>
- "application/json"<br>
produces:<br>
- "application/json"<br>
securityDefinitions:<br>
  clientIdHeader:<br>
    type: "apiKey"<br>
    in: "header"<br>
    name: "X-IBM-Client-Id"<br>
security:<br>
- clientIdHeader: []<br>
x-ibm-configuration:<br>
  testable: true<br>
  enforced: true<br>
  cors:<br>
    enabled: true<br>
  assembly:<br>
    execute:<br>
    - invoke:<br>
        target-url: "https://81d93988-7deb-4ea2-b8b1-66866595824e-bluemix.cloudant.com/apicmobile/_design/findall/_view/findall"<br>
        username: ""<br>
        password: ""<br>
        verb: "GET"<br>
  phase: "realized"<br>
paths:<br>
  /billing:<br>
    get:<br>
      responses:<br>
        200:<br>
          description: "200 OK"<br>
          schema:<br>
            $ref: "#/definitions/billing"<br>
definitions:<br>
  billing:<br>
    description: ""<br>
    type: "object"<br>
    properties:<br>
      total_rows:<br>
        type: "number"<br>
      offset:<br>
        type: "number"<br>
      rows:<br>
        type: "array"<br>
        items:<br>
          properties:<br>
            id:<br>
              type: "string"<br>
            key:<br>
              type: "string"<br>
            value:<br>
              type: "object"<br>
              properties:<br>
                _id:<br>
                  type: "string"<br>
                _rev:<br>
                  type: "string"<br>
                provider:<br>
                  type: "string"<br>
                generated_date:<br>
                  type: "string"<br>
                bill_amount:<br>
                  type: "string"<br>
                plan:<br>
                  type: "string"<br>
                mobile:<br>
                  type: "string"<br>
          type: "object"<br>
    example: "{\"total_rows\":3,\"offset\":0,\"rows\":[\n{\"id\":\"32d8bd5cb6c6d396ad09c834279376ac\"\<br>
      ,\"key\":\"32d8bd5cb6c6d396ad09c834279376ac\",\"value\":{\"_id\":\"32d8bd5cb6c6d396ad09c834279376ac\"\<br>
      ,\"_rev\":\"1-7ed3320337058908b934fa289c056d64\",\"provider\":\"telco\",\"generated_date\"\<br>
      :\"2017-08-04\",\"bill_amount\":\"67888\",\"plan\":\"Corporate\",\"mobile\"\<br>
      :\"97766444467\"}},\n{\"id\":\"4cb2214f43fcaee25765c7fd99f54fbd\",\"key\":\"\<br>
      4cb2214f43fcaee25765c7fd99f54fbd\",\"value\":{\"_id\":\"4cb2214f43fcaee25765c7fd99f54fbd\"\<br>
      ,\"_rev\":\"1-15900d05f4af192aeab26e00b3cba8f9\",\"provider\":\"telco\",\"generated_date\"\<br>
      :\"2017-08-04\",\"bill_amount\":\"568\",\"plan\":\"Corporate\"}},\n{\"id\":\"\<br>
      90bdaea300a87325e74fa6b9a9a6d5b3\",\"key\":\"90bdaea300a87325e74fa6b9a9a6d5b3\"\<br>
      ,\"value\":{\"_id\":\"90bdaea300a87325e74fa6b9a9a6d5b3\",\"_rev\":\"1-e1d329eee9b304c69d9253b4a5f0e83c\"\<br>
      ,\"provider\":\"telecon\",\"generated_date\":\"2017-08-04\",\"bill_amount\"\<br>
      :\"568\",\"plan\":\"Corporate\"}}\n]}"<br>
tags:<br>
- name: "telecon"<br>

Hope you enjoyed reading the post, coding your API and generating your Swagger 2.0 specification that can be imported into any API tool our there.

In the next post, you will see how to generate an IBM Mobile Foundation adapter from the OpenAPI specification generated above.

Feel free to reach out to me @VidyasagarMSC  for any queries or suggestion.

Thanks for reading.

Was this article helpful?
YesNo

More from Open source

Cultivating Careers, Communities and Companies with Open Source

6 min read - The soft skills you need to succeed in open source. I've had the privilege of working in open source for the last 20+ years. I started off as a volunteer, as most do in open source, attempting to learn something new. Even though I didn't fully understand what open source was at the time, I really involved myself in the community and got so much in return. While running small projects, I learned an incredible amount about the skills needed…

How to Use an Ansible Playbook to Manage Secrets for Infrastructure Provisioned on IBM Cloud

6 min read - Instructions and code that show you how to use Ansible playbooks to manage the lifecycle of a secret in IBM Secret Manager. IBM Cloud Secrets Manager is built on open-source HashiCorp Vault, and it allows you to dynamically create and manage secrets. For infrastructure or services provisioned from IBM Cloud, you need to rotate the secrets on a timely basis. What is an Ansible playbook? Many IT teams have a common requirement to manage the configuration for systems in an…

Kubernetes Audit Logs: Answering the Who, When and What

3 min read - Learn how to set up log forwarding and collect audit logs that are passed through the Kubernetes API server to IBM Log Analysis to check who initiated a request and when they did so. As a cluster administrator, by following the simple steps in this blog post, you should be able to answer questions about Kubernetes audit logs, like who initiated a request to delete a Kubernetes resource? When did it happen? On what did it happen? What are audit…

IBM Newsletters

Get our newsletters and topic updates that deliver the latest thought leadership and insights on emerging trends.
Subscribe now More newsletters