Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

OpenAPI (Swagger 2.0) YAML Generation Using API Connect

DZone's Guide to

OpenAPI (Swagger 2.0) YAML Generation Using API Connect

Learn how to model and generate an OpenAPI specification using API Connect on IBM Cloud, and publish an API that talks to a NoSQL database.

Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

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?

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.

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 the 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, e.g., 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 the ‘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:

  1. API Key

  2. Basic

  3. OAuth

  • By default, API Connect generated an API Key (clientIdHeader) with the 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 your Swagger 2.0 spec under the Source tab.

  • If you'll observe, definitions in the Swagger 2.0 is an empty object. A JSON schema definition is required here. There is a need for a 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 a simple CRUD operation.

Creating a Cloudant Service

  • Open the Bluemix catalog and within Data and Analytics select Cloudant NoSQL DB.
  • Provide a unique name and select the lite plan.
  • Click on Create to provision a new Cloudant Service.
  • Click on Launch, which will take you to the 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 need this while Assembling the API.

Adding Definition and Assembling Your API

  • Heading back to the 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 the ‘billing’ definition.

Create a Tag by selecting Tags on the left pane. The name should be the 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.
  • 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 the Host of your API with the copied URL’s Host value.
  • Replace the 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:

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

Video

Hope you enjoyed reading the post, coding your API, and generating your Swagger 2.0 specification that can be imported into any API tool out 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!

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

Topics:
api ,openapi ,swagger 2 ,security ,integration

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}