apim
2017/03/08
8 Mar, 2017

[Article] Introducing SDK Support with WSO2 API Manager

  • Chamin Dias
  • Associate Lead - Marketing - WSO2


Introduction

In the recent past, APIs have become one of the main revenue generators for most service providers in many fields. Hence, the demand for productive API management solutions has seen a rapid increase. WSO2 API Manager is a free and fully open source API management solution that has the capability of managing all stages of the API lifecycle in a massively scalable production environment. It not only supports creating and managing APIs, but also consuming APIs in a user-friendly manner. With the support for SDKs, API consumers can now develop software applications to consume APIs hosted in WSO2 API Manager. They can choose a preferred programming language from a wide range of programming languages to write software applications. As a result, API consumers can now consume the subscribed APIs in their software applications/platforms easily.



Overview of SDKs and its usability

Providing a SDK is one of the most effective mechanisms to expose a particular service across various software platforms. It will enable support for a wide range of software and applications. Software application developers can use the provided SDK as a toolbox and write code to consume the service by just calling the methods with the respective parameters.

SDKs are advantageous not only for service providers but also for consumers. When it comes to service providers, they can only focus on developing and improving the service in the best possible way (secure the service, use best practices, etc). Once they are done, they will have a well-defined and well-structured service in place for their customers. Most of today’s enterprise IT services are exposed using APIs. In the API management context, API providers can use the advanced features of WSO2 API Manager, such as throttling, custom handlers, mediation and extensions to design and publish APIs. API developers do not need to think about how they can expose their APIs to different software environments. The SDK of the API will handle this sort of requirement.

APIs are mainly exposed to the consumer community via the API Store. With SDK support, consumers can also use software applications based on the provided SDK. API consumers can write software applications easily to consume the subscribed APIs. They are given the opportunity to select a programming language of their choice from a widely used list of programming languages. API consumers do not need to worry about creating complex solutions to consume the APIs. The SDK provides all the required functions to invoke the subscribed APIs. Therefore, consumers can develop a simple software application and import the SDK module to the project (importing modules in the SDK to the software application is language dependant) and call the required functions and get a response from the API. With this mechanism, a wide range of consumers can use APIs with ease. It will be advantageous to API providers to spread their services across multiple software applications and platforms as well.

SDK generation in WSO2 API Manager is powered by swagger codegen. It is an open source project that provides many useful tools to define APIs in a structured manner. These tools include swagger UI, swagger editor and code generators. The swagger codegen project allows the generation of API client libraries, server stubs, and documentation is automatically given an OpenAPI specification.



SDK support in WSO2 API Manager

There are a few simple tasks to be carried out to enable SDK generation in the API Store.

Step 1: Stop API Manager server if it’s already running

Step 2: Locate the api-manager.xml file in <APIManager_Home>/repository/conf directory

Step 3: Include the following xml code snippet at the end of api-manager.xml file if it is not included. (before the closing tag)

    <SwaggerCodegen>
        <ClientGeneration>
            <GroupId>org.wso2</GroupId>
            <ArtifactId>org.wso2.client.</ArtifactId>
            <ModelPackage>org.wso2.client.model.</ModelPackage>
            <ApiPackage>org.wso2.client.api.</ApiPackage>
            <!-- Configure supported languages/Frameworks as comma separated values,
             Supported Languages/Frameworks : android, java, scala, csharp, cpp, dart, flash, go, groovy, javascript, jmeter,
             nodejs, perl, php, python, ruby, swift, clojure, aspNet5, asyncScala, spring, csharpDotNet2, haskell-->
            <SupportedLanguages>java,android</SupportedLanguages>
        </ClientGeneration>
    </SwaggerCodegen>

Users can specify the list of programming languages for SDK generation in the <SupportedLanguages> tag, as a comma separated list. By default, WSO2 API Manager has enabled SDK generation support for Java and Android. In addition, WSO2 API Manager can support SDK generation for scala, csharp, cpp, dart, flash, go, groovy, javascript, jmeter, nodejs, perl, php, python, ruby, swift, clojure, aspNet5, asyncScala, spring, csharpDotNet2 and haskell.

Step 4: Restart API Manager server

Once api-manager.xml file is configured properly, SDK generation will be enabled in the API Store. A new tab named “SDKs” will appear on the page where the API is displayed.

Figure 1: GUI in API Store for SDK generation

The “SDKs” tab will contain buttons to generate SDKs for the programming languages specified in api-manager.xml file under <SupportedLanguages> tag.

API consumers can now download the required SDKs for each programming language.

Important note: SDK for a particular API can be downloaded with or without a subscription, but in order to invoke the API using a software application, it is required to have an access token (an API created using WSO2 API Manager is secured using OAuth-based access tokens). Hence, it’s strongly recommended to have a valid subscription for the API before downloading the SDK.

API consumers can use the self-signup feature in the API Store (if it is enabled) to create a user account. They can log into the API Store using the created account, create an application, generate keys for the application, and subscribe to the API.



How to use SDK generation in WSO2 API Manager


Example scenario

Here’s an example of SDK generation (with step-by-step instructions) in the API Store and a guide on how to write a client application using the generated SDK to consume the API via a software application.

In this example, we will use the sample API in WSO2 API Manager as a demonstration. To deploy the sample API, login to API Publisher and click “Deploy Sample API” button. Note that the “Deploy Sample API” button will appear if no APIs are created in the given tenant space.

Note: If another API is used, the SDK will contain functions to invoke the API based on the specifications in that API.

Figure 2: Deploying sample API in API Publisher

Figure 3: Sample API (after publishing)

Once the API is deployed, it will be published to the API Store. Log in to API Store as a subscriber and you will notice that the newly created API is available there.

Figure 4: API Store showing the published API

Click the “Applications” tab and create an application.

Figure 5: Create an application in API Store

Locate the newly created API and subscribe to that API using the newly created application.

Figure 6: Subscribing to an API using a given application

Go to the “Applications” tab and locate the application. Click on the “Production Keys” tab and generate keys.

Figure 7: SDK download page

Figure 8: Generating access token for the application in API Store

Once the keys are generated, note down the “Access token” for subscription. This is needed in the software application that’s used to invoke the API.

Locate the API details page in the API Store and download the SDK for Java. In this example, it is a zip file named “PizzaShackAPI_1.0.0_java.zip”. This file name indicates API name, API version, and language of the SDK. Unzip the zip file. It should have a directory structure as follows:

Figure 9: Directory structure of Java SDK for the sample API

In this example, we are going to use this in a maven project (since we are using Java SDK). Therefore, build this SDK using maven. When it’s done, developers can include this SDK as a dependency in their software project. Details of this maven dependency are included in the README.md file.

Figure 10: README file of the SDK showing the package details

After creating a Java project, we need to import the following with respect to the SDK. These classes will be accessible from the code once the SDK is built using maven and included as maven dependencies in the project.

import org.wso2.client.api.ApiClient;
import org.wso2.client.api.PizzaShackAPI.DefaultApi;
import org.wso2.client.model.PizzaShackAPI.Menu;

We need to create an instance of the DefaultApi object in the java code.

DefaultApi defaultApi = new DefaultApi();

The API client of the instance of the DefaultApi object is used to set HTTP request headers with required data. Note that these HTTP request headers might differ from one API to another, depending on the implementation of the API.

ApiClient apiClient = defaultApi.getApiClient();
apiClient.addDefaultHeader("Accept", "application/json");

Access token for the API is needed to invoke the API. Hence, we need to include the access token as a header in the API client object. This is why it is important to have a valid subscription to the API before using the SDK.

String accessToken = "19574071-0928-3ea5-91e2-765b1bc2aa88";
apiClient.addDefaultHeader("Authorization", "Bearer " + accessToken);

The base path for the client application is the production (or sandbox) URL of the API. This can be found at the “Overview” tab of the API in the API Store.

Figure 11: Production and sandbox URLs for the API

apiClient.setBasePath("https://localhost:8243/pizzashack/1.0.0");

Once the ApiClient object has all the required data, then we can set the ApiClient for the instance of the DefaultApi object.

defaultApi.setApiClient(apiClient);

Finally, we can call the available function in the SDK to get the response from the API.

Menu result = defaultApi.menuGet();

Note that a class named Menu exists in the “src” directory of the SDK. If you follow these steps for another API, it will have the relevant Java classes based on the design of the API.



Generating SDKs using the Store REST API

In addition to the GUI in API Store, consumers can use the Store REST API to generate SDKs for a given API. Here also, it’s mandatory to have a subscription to the API if they need to write a software application using the SDK.

Therefore, we’re going to explore how we can use the Store REST API for SDK generation.

First, we need a user account that has API subscription privilege. Refer to the official documentation of WSO2 API Manager Store REST API for more information. Use the credentials of the user account and register a client app.

curl -X POST -H "Authorization: Basic a2FzdW46YWJjMTIz" -H "Content-Type: application/json" -d @sample_payload.json https://localhost:9763/client-registration/v0.10/register

In the above cURL command, we have set the base64 encoded credentials of the user. Sample response for the dynamic client registration request is shown below.

{"clientId":"Pb83PqgaB5EFYY837_Iy_Pgsuwka","clientName":null,"callBackURL":"www.google.lk","clientSecret":"huw1ssRSzxm1OS1LZN4MIpRgaIUa","isSaasApplication":true,"appOwner":null,"jsonString":"{\"username\":\"kasun\",\"redirect_uris\":\"www.google.lk\",\"client_name\":\"kasun_rest_api_store_client3\",\"grant_types\":\"urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm implicit refresh_token client_credentials authorization_code password\"}"}

Concat “clientId” and “clientSecret” by placing a colon in the middle. Encode it with base64 encoding algorithm. After that’s done, send a request to the token endpoint with a header that contains the base64 encoded value. Make sure to specify the scope as “apim:subscribe” when requesting a token, because we need a token with “apim:subscribe” scope to use the store REST API for SDK generation.

Sample cURL command:

curl -k -d "grant_type=password&username=kasun&password=abc123&scope=apim:subscribe" -H "Authorization: Basic UGI4M1BxZ2FCNUVGWVk4MzdfSXlfUGdzdXdrYTpodXcxc3NSU3p4bTFPUzFMWk40TUlwUmdhSVVh" https://localhost:8243/token

Sample response:

{"scope":"apim:subscribe","token_type":"Bearer","expires_in":3600,"refresh_token":"2924d136-6136-3a35-9e41-9a3d94748b2d","access_token":"f5af33b6-c876-31c5-9870-190b2427b1ad"}

Note down the access token in the response. Here the access token is "f5af33b6-c876-31c5-9870-190b2427b1ad"

To use the store REST API for SDK generation, the user should need to know the provider name and UUID of the API. These details can be found by sending a request to the store REST API for API retrieval. No scope is needed to retrieve the API list.

For example, if the user needs to get the API list in the super tenant’s API Store, the sample cURL command would be as follows:

curl -k -H "X-WSO2-Tenant: carbon.super" https://localhost:9443/api/am/store/v0.10/apis

Sample response contains the UUID and provider of the required API.

{"count":1,"next":"","previous":"","list":[{"id":"c1af903b-fe31-45c2-9baf-348856812392","name":"PizzaShackAPI","description":"This is a simple API for Pizza Shack online pizza delivery store.","context":"/pizzashack/1.0.0","version":"1.0.0","provider":"admin","status":"PUBLISHED"}]}

In the super tenant space, there is an API named “PizzaShackAPI”. UUID of the "PizzaShackAPI" is "c1af903b-fe31-45c2-9baf-348856812392". Provider of that API is "admin".

Use the data (i.e. UUID and provider) in the response along with the access token to generate and download the SDK for the API in super tenant space.

curl -X POST -H 'X-WSO2-Tenant: carbon.super' -H 'Authorization: Bearer f5af33b6-c876-31c5-9870-190b2427b1ad' 'https://localhost:9443/api/am/store/v0.10/apis/generate-sdk?apiId=c1af903b-fe31-45c2-9baf-348856812392&language=java' -k > PizzaAPI_Java_SDK.zip

In a multi-tenant environment, if the user needs to get the API list in a tenant’s API Store, the sample cURL command would be as follows:

curl -k -H "X-WSO2-Tenant: hr.com" https://localhost:9443/api/am/store/v0.10/apis

Sample response contains the UUID and provider of the APIs in the tenant space.

{"count":1,"next":"","previous":"","list":[{"id":"f848cfe7-2b75-4fb4-bb8e-23e8a2ed41a8","name":"HRAPI","description":null,"context":"/t/hr.com/TestContext/2.0.0","version":"2.0.0","provider":"[email protected]","status":"PUBLISHED"}]}

UUID of the "HRAPI" is "f848cfe7-2b75-4fb4-bb8e-23e8a2ed41a8". Provider of that API is "[email protected]"

Use the data (i.e. UUID and provider) in the response along with the access token to generate and download the SDK for the API in the tenant space.

curl -X POST -H 'X-WSO2-Tenant: hr.com' -H 'Authorization: Bearer f5af33b6-c876-31c5-9870-190b2427b1ad' 'https://localhost:9443/api/am/store/v0.10/apis/generate-sdk?apiId=f848cfe7-2b75-4fb4-bb8e-23e8a2ed41a8&language=java' -k > HRAPI_Java_SDK.zip

The store REST API facilitates the use of third-party tools, such as cURL, advanced REST client of postman. Therefore, API consumers can now generate SDKs for their APIs using a third-party tool as well.

Once the SDK is downloaded, the API consumer can write a software application to invoke the API. They can follow the same steps mentioned in the previous section of this article.



Conclusion

This article introduced SDK support with WSO2 API Manager and explained how it can be used by API consumers to write software applications to consume APIs. Since WSO2 API Manager is a complete, enterprise-ready solution for managing APIs and exposing APIs to the community, users are given the option to invoke APIs within their software applications using the generated SDKs.

Moreover, this article depicted how you can configure SDK generation in WSO2 API Manager, how to generate SDKs (using GUI and REST API), and how to write a sample software application to use the SDK with the related concepts.

 

About Author

  • Chamin Dias
  • Associate Lead - Marketing
  • WSO2