Generating SDKs for an API Resource
Find out how to generate an SDK for an API from an API description with the API Gateway service to give developers programmatic access to back-end services.
When using the API Gateway service, you have the option to generate SDKs (Software Development Kits) for an API resource. If you use the API resource to deploy an API on an API gateway, the SDKs you generate give developers programmatic access to the API. To make it easy to integrate with the API, you can generate SDKs for a number of languages and platforms including:
- Android
- Java
- JavaScript
- Swift
- TypeScript
Having generated an SDK, you can download a zip file containing the SDK resources (API client libraries, configurations, and documentation) and distribute it to developers writing code accessing the API.
To generate an SDK for an API resource, you must have created an API description for the API resource. You create an API description by uploading an API description file (sometimes called an 'API specification', or 'API spec') written in a supported language. Currently, OpenAPI Specification version 2.0 (formerly Swagger Specification 2.0) and version 3.0 are supported. For more information about API resources and API descriptions, see Creating an API Resource with an API Description.
Generating an SDK using the API Gateway service is optional. You can deploy an API on an API gateway without generating an SDK. Likewise, you can provide programmatic access to an API you've deployed on an API gateway with an SDK you've created in a different tool. You can also use the API Gateway service simply to generate an SDK from an API description file, without using the associated API resource to deploy an API on an API gateway.
Note the following:
- An API resource can have:
- zero SDKs
- one or more SDKs for the same language or platform
- one or more SDKs for different languages or platforms
- You can only ever generate a completely new SDK. Every generated SDK has a unique identifier (OCID). You cannot "re-generate" an existing SDK that has already been generated (although you can change the display name of an existing SDK).
- It is your responsibility to manage generated SDKs. If you upload an updated version of an API description file from which you previously generated an SDK, a new SDK is not generated automatically. You have to decide whether to generate a new SDK, or not. If you do generate a new SDK, you have to decide whether to delete the existing SDK, or retain it.
- You can only generate an SDK if an uploaded API description file has not failed validation checks. Note that you can generate an SDK if the uploaded API description file passed validation checks with warnings. However, we recommend you resolve any warnings before generating the SDK.
To generate an SDK for an API resource from an uploaded API description file, using the Console:
- In the Console, open the navigation menu and click Developer Services. Under API Management, click Gateways.
- Choose a Compartment you have permission to work in.
- If you haven't already uploaded an API description file, follow the instructions in Creating an API Resource with an API Description to create an API resource and specify an API description file to upload.
- On the APIs page, select the API resource for which you want to generate an SDK.
- On the API Details page, select SDKs from the Resources list, and then click Create SDK.
- In the Create SDK dialog:
- Specify:
- Name: The name of the new SDK. Avoid entering confidential information.
- Programming Language: The programming language or platform for which you want to generate an SDK from the uploaded API description file.
- <Language> Properties: Depending on the programming language or platform you choose, specify values for language-specific or platform-specific properties. Required properties are always shown. Click Show Optional Properties to see and enter values for additional, optional properties.
- (Optional) Click Show Advanced Options and optionally specify:
- Tags: If you have permissions to create a resource, then you also have permissions to apply free-form tags to that resource. To apply a defined tag, you must have permissions to use the tag namespace. For more information about tagging, see Resource Tags. If you're not sure whether to apply tags, skip this option or ask an administrator. You can apply tags later.
- Click Create to generate the new SDK.
The SDK is generated. Note that it can take a few minutes to generate the SDK.
When the SDK has been generated successfully, the SDK Details page shows the programming language or platform that you specified for the SDK (and the values of any required and optional properties).
- Specify:
- Click Download SDK to obtain a zip file containing the SDK resources (API client libraries, configurations, and documentation) that have been generated from the API description file for the API resource.
Having successfully generated the SDK for the API resource, you can distribute the zip file to developers who are writing code accessing the API.
To generate an SDK for an API resource from an uploaded API description file, using the CLI:
- Configure your client environment to use the CLI (Configuring Your Client Environment to use the CLI for API Gateway Development).
-
Open a command prompt and run
oci api-gateway sdk-language-type
to find out the programming languages and platforms for which you can generate an SDK:oci api-gateway sdk-language-type list --compartment-id <ocid>
You see the supported programming languages and platforms, and the required and optional parameters to use with each.
- Run
oci api-gateway sdk create
to generate the SDK:oci api-gateway sdk create --target-language "<language>" --api-id <api-ocid> --parameters '{"<first-parameter-name>": "<first-parameter-value>", "<second-parameter-name>": "<second-parameter-value>"}'
where:
<language>
is the programming language or platform for which you want to generate an SDK from the uploaded API description file.<api-ocid>
is the OCID of the API resource for which you want to generate the new SDK.--parameters '{"<first-parameter-name>": "<first-parameter-value>", "<second-parameter-name>": "<second-parameter-value>"}'
are the name and value of any required and/or optional parameters to set for the programming language or platform you've chosen.
For example:
-
oci api-gateway sdk create --target-language "JAVASCRIPT" --api-id ocid1.apigatewayapi.oc1..aaaaaaa3______psq
-
oci api-gateway sdk create --target-language "SWIFT" --api-id ocid1.apigatewayapi.oc1..aaaaaaa3______psq --parameters '{"projectName": "Hello World", "apiNamePrefix": "hello"}'
The response to the command includes:
- The SDK's OCID.
- The lifecycle state (for example, SUCCEEDED, FAILED).
- The id of the work request to create the SDK (details of work requests are available for seven days after completion, cancellation, or failure).
If you want the command to wait to return control until the SDK has been created (or the request has failed), include either or both the following parameters:
--wait-for-state SUCCEEDED
--wait-for-state FAILED
For example:
oci api-gateway sdk create --target-language javascript --api-id ocid1.apigatewayapi.oc1..aaaaaaa3______psq --wait-for-state SUCCEEDED
Note that you cannot use the SDK until the work request has successfully created it.
-
(Optional) To see the status of the work request that is creating the SDK, enter:
oci api-gateway work-request get --work-request-id <work-request-ocid>
-
(Optional) To view the logs of the work request that is creating the SDK, enter:
oci api-gateway work-request-log list --work-request-id <work-request-ocid>
-
(Optional) If the work request that is creating the SDK fails and you want to review the error logs, enter:
oci api-gateway work-request-error --work-request-id <work-request-ocid>
For more information about using the CLI, see Command Line Interface (CLI). For a complete list of flags and options available for CLI commands, see CLI Help.
Run the:
- CreateSdk operation to create an SDK for an API resource from an uploaded API description file.
- ListSdks operation to list SDKs that have already been generated.
- GetSdk operation to see details of an existing SDK.
- UpdateSdk operation to change the display name of an existing SDK.
- DeleteSdk operation to delete an SDK.
- ListSdkLanguageTypes operation to list the programming languages and platforms for which you can generate an SDK, along with any required and optional parameters.
Examples of Using Generated SDKs
Having used API Gateway to generate an SDK from an API resource's API description file, you can download and install the SDK, and then use it to call the API deployed on an API gateway.
The steps to download, install, and use a generated SDK depend on the SDK's language and the functionality of the API.
The examples in this section assume an SDK has been generated for a blog API in each of the different languages. Use the examples as guides, which you can extend and adapt to meet your own requirements.
Example 1: Using an Android SDK Generated for an API Resource
Tools and versions used in this example:
- Gradle 6.5
- Maven 3.6.3
- Android Studio 4.1.2
To use an Android SDK that API Gateway generated from an API resource's API description file:
- Download the zip file containing the Android SDK that API Gateway generated, and extract its contents.
- In the root directory extracted from the zip file, install the generated SDK into
the local Maven repository by
running:
mvn clean install
-
Decide which Android project will use the generated Android SDK. Either open an existing Android project that has Gradle as the package manager, or create a new Android project as follows:
- Open Android Studio. Under File, go to New and click New Project.
- Select No Activity, and click Next.
- For Language, select Java and click Finish.
- Update the module's build.gradle file to add the generated SDK as a dependency. For
example:
plugins { id 'com.android.application' } android { compileSdkVersion 29 buildToolsVersion "30.0.3" defaultConfig { applicationId "com.example.myapplication" minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" // 2) Connect JUnit 5 to the runner testInstrumentationRunnerArgument "runnerBuilder", "de.mannodermaus.junit5.AndroidJUnit5Builder" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } apply plugin: "de.mannodermaus.android-junit5" dependencies { implementation 'com.android.support:multidex:1.0.3' implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'com.google.android.material:material:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation("com.mock:test-project:1.0.1") }
Note that
test-project
has been added underdependencies
. - Run the project build on Android Studio.
- When the build has completed, import the generated SDK classes and use them in one
or more of the Android project's Java classes. For example:
package com.example.myapplication; import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import com.mock.testproject.api.UserV1; import com.mock.testproject.api.UsersApi; public class NetworkTask extends AsyncTask<String,String,String> { @SuppressLint("StaticFieldLeak") private final Context context; public NetworkTask(Context context) { this.context = context; } @Override protected String doInBackground(String... strings) { try{ UsersApi usersApi = new UsersApi(); usersApi.setBasePath("https://0eff7c6c85cc.ngrok.io"); UserV1 a = usersApi.getUsersUsername("a"); return a.toString(); }catch (Exception e){ e.printStackTrace(); return e.getMessage(); } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Toast.makeText(context, s, Toast.LENGTH_LONG).show(); } }
Use the above example as a guide, which you can extend and adapt to meet your own requirements.
Example 2: Using a Java SDK Generated for an API Resource
Tools and versions used in this example:
- Maven 3.6.3
- Java 1.8.0
To use a Java SDK that API Gateway generated from an API resource's API description file:
- Download the zip file containing the Java SDK that API Gateway generated, and extract its contents.
- In the root directory extracted from the zip file, install the generated SDK into
the local Maven repository by
running:
mvn clean install
- Decide which Maven project will use the generated Java SDK. Either update an
existing Maven project, or create a new Maven project by
running:
mvn -B archetype:generate -DarchetypeGroupdId=org.apache.maven.archetypes -DgroupId=examples.com.testApp -DartifactId=test-maven-project
- Update the Maven project's pom.xml file to add the generated SDK as a dependency.
For
example:
<dependency> <groupId>com.mock.test</groupId> <artifactId>integration-java</artifactId> <version>1.0.0</version> <scope>compile</scope> </dependency>
- In the Maven project's root directory,
run:
mvn clean install
- When the Maven installation is complete, import the generated SDK classes and use
them in the Maven project. For
example:
import com.mock.test.integration.ApiClient; import com.mock.test.integration.ApiException; import com.mock.test.integration.api.UsersApi; import com.mock.test.integration.model.UserV1; public class SdkTest { private String basePath; private UsersApi usersApi; private UsersApi loggedInUsersApi; public void setUpAndListUsers(){ ApiClient loggedInClient = new ApiClient(); loggedInClient.setPassword("password"); loggedInClient.setUsername("username"); loggedInUsersApi = new UsersApi(loggedInClient); List<UserV1> users = loggedInUsersApi.getUsers(); } }
Use the above example as a guide, which you can extend and adapt to meet your own requirements.
Example 3: Using a JavaScript SDK Generated for an API Resource
Tools and versions used in this example:
- Npm 6.14.0
To use a JavaScript SDK that API Gateway generated from an API resource's API description file:
- Download the zip file containing the JavaScript SDK that API Gateway generated, and extract its contents.
- In the root directory extracted from the zip file,
run:
npm install
npm link
- In the root directory of an existing npm project,
run:
For example:npm link <path_to_javascript_client_dir>
npm link "/Users/ajay.d.dubey/Downloads/Simple API overview_JAVASCRIPT_v26544725374050339058"
- In the .js file from which to call the services, import and use the generated SDK.
For example:
const Blog = require("blog"); const apiClient = new Blog.ApiClient(); apiClient.defaultHeaders = { authorization: "audio/basic" }; apiInstance = new Blog.UsersApi(apiClient); //get user apiInstance.getUsersUsername( "046b6c7f-0b8a-43b9-b35d-6489e6daee91", (error, data, response) => { if (error) throw error; console.log(response.statusCode); console.log(response) } ); //put user let opts = { userV1: new Blog.UserV1( "Test", "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", "password", "a@b.com" ), }; apiInstance.putUsersUsername( "046b6c7f-0b8a-43b9-b35d-6489e6daee91", opts, (error, data, response) => { if (error) throw error; console.log(response.statusCode); console.log(response) } );
In this example, the name of the generated SDK is
blog
. Look in the extracted package.json file to find the name of the generated SDK.
Use the above example as a guide, which you can extend and adapt to meet your own requirements.
Example 4: Using a Swift SDK Generated for an API Resource
Tools and versions used in this example:
- XCode 12.4
- Swift 5.3.1
- CocoaPods 1.10.1
To use a Swift SDK that API Gateway generated from an API resource's API description file:
- Download the zip file containing the Swift SDK that API Gateway generated, and extract its contents.
- Decide which XCode project will use the generated Swift SDK. Either update an
existing XCode project, or create a new XCode project as follows:
- Open XCode. Under File, go to New and click Project.
- Select App, and click Next.
- For Language, select Swift and click Next.
- Specify a location for the project and click Create to create the XCode project.
- If the root directory of the XCode project does not already contain a Podfile,
create a Podfile by running:
pod init
- Update the Podfile to add a reference to the generated SDK. For
example:
target 'test-project-3' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # Pods for test-project-3 pod 'mysdk', :path => '/Users/ajay.d.dubey/workspace-2/swift/Blog_SWIFT_1.0.01209182890182739216' end
- In the XCode project's root directory,
run:
pod install
Example output:
~/workspace-2/swift/test-project-3 on main ?1 ❯ pod install took 1m 4s at 09:50:31 Analyzing dependencies Downloading dependencies Installing mysdk (1.0.0) Generating Pods project Integrating client project [!] Please close any current Xcode sessions and use `test-project-3.xcworkspace` for this project from now on. Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed. [!] Automatically assigning platform `iOS` with version `14.4` on target `test-project-3` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
- Close any open instances of XCode.
- In the XCode project's root directory, open the .xcworkspace file to see the pod.
- Update any swift file to import the pod and start using the generated SDK. For
example, update the ViewController.swift file to import the mysdk pod as
follows:
import UIKit import mysdk class ViewController: UIViewController { override func viewDidLoad() { mysdkAPI.credential = URLCredential.init(user: "username", password: "password", persistence: .permanent) mysdkAPI.customHeaders = ["Content-Type":"application/json","Authorization":"Basic 1234"] mysdk.UsersAPI.getUsers(completion: getUsers) mysdk.UsersAPI.getUsersUsername(username: "046B6C7F-0B8A-43B9-B35D-6489E6DAEE91", completion: responseUserUsername) } func getUsers(users :[mysdk.UserV1]?, error:Error?) -> Void{ print("Attempting fetching user details:") print(users) } func responseUserUsername(user :mysdk.UserV1?, error:Error?){ print("Attempting fetching user with username:") print("Successful Request") print (user) }
Use the above example as a guide, which you can extend and adapt to meet your own requirements.
Example 5: Using a TypeScript SDK Generated for an API Resource
Tools and versions used in this example:
- yarn 1.22.10
This example shows how to build and consume a generated TypeScript SDK using yarn. If you want to consume a generated TypeScript SDK using NPM, follow the steps to consume a generated JavaScript SDK using NPM that are shown in Example 3: Using a JavaScript SDK Generated for an API Resource.
To use a TypeScript SDK that API Gateway generated from an API resource's API description file:
- Download the zip file containing the TypeScript SDK that API Gateway generated, and extract its contents.
- In the root directory extracted from the zip file,
run:
yarn install
yarn run build
yarn link
- In the root directory of the project that you want to use the generated SDK:
- Run:
yarn link <project-name>
where
<project name>
is the name of the generated SDK. Look in the extracted package.json file to find the name of the generated SDK. For example:yarn link test-project
- Run:
yarn install
- Run:
- Update the ts file of the project that you want to use the generated SDK. For
example:
const Blog = require("blog"); const expect = require("chai").expect; let apiInstance; let apiInstanceWithoutHeader; before(function () { const apiClient = new Blog.ApiClient(); apiClient.defaultHeaders = { authorization: "audio/basic" }; apiInstance = new Blog.UsersApi(apiClient); apiInstanceWithoutHeader = new Blog.UsersApi(); }); describe("UsersApi", function () { it("should call add delete username successfully", function (done) { apiInstance.deleteUsersUsername( "046b6c7f-0b8a-43b9-b35d-6489e6daee91", (error, data, response) => { if (error) throw error; console.log(response.statusCode); console.log(response) expect(response.statusCode).to.equal(204); expect(data).to.equal(null); done(); } ); }); it("should update user details successfully", function (done) { let opts = { userV1: new Blog.UserV1( "Test", "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", "password", "a@b.com" ), }; apiInstance.putUsersUsername( "046b6c7f-0b8a-43b9-b35d-6489e6daee91", opts, (error, data, response) => { if (error) throw error; expect(response.statusCode).to.equal(202); expect(data).to.not.null; done(); } ); }); });
Use the above example as a guide, which you can extend and adapt to meet your own requirements.