In this lab, you’ll gain a high level understanding of the architecture, features, and development concepts related to the IBM API Connect (APIC) solution. Throughout the lab, you’ll get a chance to use the APIC command line interface for creating LoopBack applications, the intuitive Web-based user interface, and explore the various aspects associated with solution’s configuration of RESTful based services as well as their operation.
In the following lab, you will learn:
- How to create a simple LoopBack application
- How to create a Representational State Transfer (REST) API definition
- How to test an API
- How to publish an API to Bluemix
- How to sucribe to an API previously published
- How to invoke an API from Mobile Application
-
Get a Bluemix IBM id
-
Install Node.js 4.4.x Node.js
-
Install (or Update) API Connect CLI API Connect Developer Toolkit
npm install apiconnect -g
You must have version 5.0.6 or above. check the version with the following command :
$apic -v
API Connect: v5.0.6.0 (apiconnect: v2.5.8)
Note: To check all available versions of API Connect:
npm view apiconnect version
To check the local version of API Connect:apic -v
- Provision API Connect in Bluemix
- Create a Cloudant service
- Create a LoopBack application
- Manage your API in API Designer
- Test your API
- Publish your API to Bluemix
- Consumer Experience
- Invoke the API
- Analytics
- Invoke your API from Mobile
From the Bluemix [Catalog] bmx_catalog_uk_url, provision an instance of the service API Connect.
In order to store our data used by our API, we will need a persistent storage. To do so, we will use a Cloudant NoSQL database, a JSON document oriented store, compatible with CouchDB.
You can use a existing Cloudant service or create an instance of the service Cloudant DB.
-
Go to the Bluemix Catalog, create an instance of the service Cloudant NoSQL DB.
-
Search for Cloudant in the catalog
-
Select the free Lite plan
-
Give it a name such as cloudant-db.
-
Launch the Cloudand Dashboard. A new tab should open automatically with the list of databases.
-
Create a new database with the button on top right corner. Call this dabase : test. Make sure to use this name as this is expected by the persistence layer of API Connect.
-
Go back to Bluemix console and click the tab Service Credentials.
{ "credentials": { "username": "XXXXXX", "password": "XXXXXX", "host": "f9246334-58d1-4a97-8bde-34c30121f063-bluemix.cloudant.com", "port": 443, "url": "https://USERNAME:PASSWORD@f9246334-58d1-4a97-8bde-34c30121f063-bluemix.cloudant.com" } }
-
Copy the url, username and password from the credentials into the your prefered editor. we will use these values later.
API Connect comes with a developer toolkit. This toolkit provides a offline graphical user interace named API Designer for creating APIs, the LoopBack framework for developing REST applications, a local unit test environment that includes a Micro Gateway for testing APIs, and a set of command line tools for augmenting the development toolset and assisting devops engineers with continuous integration and delivery.
-
Get help on the apic command set:
apic -h
The developer toolkit provides an integrated development environment for developing APIs and applications that use the LoopBack framework.
To create a new LoopBack project, use the command apic loopback; then use the apic edit command to edit the project in the API Designer.
-
Create an API Connect LoopBack application.
$ apic loopback
Next you will be asked to supply the name of the directory where the application will be created. Enter demo
What's the name of your application? demo
-
LoopBack will default the project directory name to the name of the application.
-
Press the Enter or Return key to accept the default value of inventory.
-
Next you will be asked to select the type of application. Use the arrow keys to select the empty-server option and press the Enter or Return key.
❯ empty-server (An empty LoopBack API, without any configured models or datasources)
-
At this point, the project builder will install the core dependencies for our Node.js application.
? Please review the license for API Connect available in /usr/local/lib/node_modules/apiconnect/LICENSE.txt and select yes to accept. yese arrow keys) ? What's the name of your application? demo ? Enter name of the directory to contain the project: demo ? What kind of application do you have in mind? empty-server (An empty LoopBack API, without any configured models or datasources)
-
Change directory to your application directory
cd demo
The datasource is what allows the API to communicate with the backend data repository. In this case we will be using Cloudant to store the data item information.
There are two parts to this. First is the definition of how to connect to the backend system. The second is downloading the actual loopback connector for Cloudant.
In your terminal ensure that you are in the demo directory.
cd demo
In your terminal, type:
apic create --type datasource
The terminal will bring up the configuration wizard for our new datasource for the item database. The configuration wizard will prompt you with a series of questions. Some questions require text input, others offer a selectable menu of pre-defined choices.
Answer the questions with the following data:
Note: For Connection String url paste the previous value you copied about Cloudant credential in Step 1
Option name | Values |
---|---|
? Enter the data-source name : | db |
? Select the connector for db : | IBM Cloudant DB |
? Connection String url to override other settings | YOUR Connection URL https://username:password@host |
? database : | test |
? username : | |
? password : | |
? modelIndex : | |
? Install loopback-connector-cloudant@^1.0.4 | Y |
Example :
? Enter the data-source name: db
? Select the connector for db: IBM Cloudant DB (supported by StrongLoop)
Connector-specific configuration:
? Connection String url to override other settings (eg: https://username:password@host): https:
//a836946d-92b5-41cc-b730-442b4235aae8-bluemix:7911bb5592e65f126903c59f6fa3d7f3b5bd4a1141951e31
938b6c6cb2efa852@a836946d-92b5-41cc-b730-442b4235aae8-bluemix.cloudant.com
? database: test
? username:
? password:
? modelIndex:
? Install loopback-connector-cloudant@^1.0.4 Yes
Note: By typing Y (Yes) to the question Install loopback-connector-cloudant, the Cloudant Connector will be downloaded and saved to your project automatically.
This will create a connection profile in the ~/demo/server/datasources.json file. It is effectively the same as running the following to install the connector:
npm install loopback-connector-cloudant --save
For more information on the LoopBack Connector for Cloudant, see: https://www.npmjs.com/package/loopback-connector-cloudant
Note : You can create an api directly from a existing web service from the wsdl. Create a SOAP API definition from a WSDL definition file, or a .zip file that contains the WSDL definition files for a service with the following command:
apic create --type api --wsdl filename
Note: You can create an API or Product from an OpenAPI (Swagger 2.0) template file by using the '--template template-name' option.
-
Launch API Connect Designer
apic edit
If the designer started correctly, a webpage will automatically opens and the terminal will show a message similar to this one:
Express server listening on http://127.0.0.1:9000
-
Click Sign in with Bluemix. If you're already sign in with Bluemix, you'll be automatically signed into the designer.
-
The designer opens into the APIs section showing the API definition we created from the command line.
In this section, you will define the item data model for our demo API and attach it to the Cloudant datasource. LoopBack is a data model driven framework. The properties of the data model will become the JSON elements of the API request and response payloads.
-
Click the Models tab.
-
Click the
+ Add
button. -
In the New LoopBack Model dialog, enter Customer as the model name, then click the New button.
-
When the Model edit page for the item model displays, select the db Data Source:
The Customer
table in the database has 6 columns that will need to mapped as well. To start creating properties for the item model:
-
Click the
+ button
in the Properties section. -
The
Customer
data model consists of six properties. Use the data below to add each of the properties:
Required | Property Name | Is Array | Type | ID | Index | Description |
---|---|---|---|---|---|---|
yes | name | no | String | no | no | Name |
yes | age | no | number | no | no | age |
-
Scroll to the top of the page and click the Save button to save the data model.
-
Click the All Models link to return to the main API Designer page.
-
Let's test the API in the Designer. First, start the server by clicking the play button in bottom left corner. Once the server is started, you should see the endpoint of the Local Micro Gateway.
-
On the server is started, Click on Explore in the top right corner.
-
Select the operation POST /Customers. Click on Generate hyperlink before the button Call operation in the right panel.
{ "name": "YOUR NAME", "id": -30239449.275000483 }
-
The first time you will most likely get a CORS error as follows:
No response received. Causes include a lack of CORS support on the target server, the server being unavailable, or an untrusted certificate being encountered. Clicking the link below will open the server in a new tab. If the browser displays a certificate issue, you may choose to accept it and return here to test again. https://$(catalog.host)/api/Customers
-
Open the url below in a new tab of your browser:
-
Click on Advanced. Accept the exception.
-
Go back to the Explore view in API Designer and click Call operation again. You should get a successful response code 200 OK.
-
If you have kept the Cloudant DB dahsboard open, you can select the database test and view the newly created record.
-
Congratulations you successfullly tested your API.
-
In the API Designer, select the tab APIs and click on your demo API. Switch from the Design view to Assemble. In the left hand side panel, switch from Micro Gateway policies to DataPower Gateway policies. Save the change.
-
Click on Publish in the top right corner. Select Add and Manage Targets.
-
Select Add IBM Bluemix Target. Select the Region such as United Kingdom where you created the API connect instance, then the Organization (Space). Finally, select the default catalog Sandbox and Next
-
In the page Select a Bluemix application, type a new application name such as demo-app. Click + to add your app in the list. Then Save.
-
Click again on Publish in the top right corner. Select the newly created target.
-
Check the box Publish Application and Stage or Publish products > Stage only. Click Publish.
Note: Here we have the opportunity to select what gets published. If we were working on multiple API products as part of this project, we could chose specific ones to publish.
Also, the option exists to only Stage the product. A Stage-only action implies that we’ll push the configuration to the Management server, but not actually make it available for consumption yet. The reason for doing this may be because your user permissions only allow staging, or that a different group is in charge of publishing Products.
-
The publishing operation generates messages in the terminal window where you started APIC. You can see that some properties are updated during publush process.
Deploying to Bluemix ...preparing project ...building package for deploy ...uploading package Runtime published successfully. Management URL: https://new-console.eu-gb.bluemix.net/apps/e48d87d6-6fbe-4be1-9795-958f0ef532bb API target urls: apiconnect-e48d87d6-6fbe-4be1-9795-958f0ef532bb.fredericdutheilfribmcom-fdulondonspace.apic.eu-gb.mybluemix.net API invoke tls-profile: client:Loopback-client Updated demo.yaml with tls-profile and target-url. Found 1 files to publish. Staged /Users/fred/Works/Sandbox/demo/definitions/demo-product.yaml to fredericdutheilfribmcom-fdulondonspace:sb [demo:1.0.0] Successfully published products
-
Go to the Bluemix [Dashboard] bmx_dashboard_url. You should see a new Cloud Foundry app called demo-app which is the Loopback app we just published.
At this time, your API is not avaible for consumer. First you need initialize the API Portal and publish your API on it.
-
Open the service instance api-connect. Launch API Manager.
-
In the main page, click the Sandbox catalog.
-
Click on the tab Settings, then select the sub menu Portal. In the Portal Configuration, select IBM Developper portal instead of None. and then click Save. It will automatically generate the portal URL and the portal as well.
A pop up screen will let you know that the process to create your portal has started.
Creating the developer portal for catalog 'Sandbox' may take a few minutes. You will receive an email when the portal is available.
It might take some time for your developer portal to get created, but usually the process is pretty quick. Once the portal is done creating, you will receive an email.
So now we are going to publish our API
-
In the API manager, on the product demo, click the ... next to the state and click on Publish in the menu. Use default value and then click Publish again
-
Your demo API is now visible in Developer Portal
Summary: In this lab, you will learn the consumer experience for APIs that have been exposed to your developer organization. Using the developer portal, you will first login in as the admin user to load a Think IBM custom theme. You will then login as a developer to register your application and then subscribe to an API and test that API.
-
Return to the Bluemix API Manager screen.
-
Navigate to the Dashboard section and click on the Sandbox catalog tile.
-
Choose the Settings tab, followed by the Portal option.
-
Click on the Portal URL link to launch the Developer Portal
-
Login into the developer portal as an administrator using admin as username and the password you set up in previous Lab.
-
Click on API Products to explore the available APIs
Let's now subscribe to the API. You will log into the portal as a user in the application developer role, then register an application that will be used to consume APIs.
If you have not created a developer account, you will need to use the Create an account link to do so now.
-
Enter in your account information for the developer account. This must be a different email address than your bluemix account. Click Create New Account once all the requisite data in the form has been filled out.
-
A validation email will be sent out to the email address used at sign up. Click on the validation link and then you will have completed the sign up process and will be authenticated into the page.
-
Login into the developer portal as an application developer using your developer credentials.
-
Click the Apps link, then click on the Create new App link.
-
Enter a title and description for the application and click the Submit button.
Title: Mobile App Consumer
Description: Test Application for demo APIs
OAuth Redirect URI: < leave blank >
We need to capture the Client Secret and Client ID in a text editor for later use by our test application.
- Select the Show Client Secret checkbox next to Client Secret at the top of the page and the Show checkbox next to Client ID.
![Register app](./images/apic-registerapp.png)
- Copy Client Secret and Client ID in a text editor
In this section, we will subscribe to a plan for the demo APIs using the Mobile App Consumer application.
- Click the ```API Products link.``
- Click the demo (v1.0.0) API product link.
You will be directed to the Product page which lists the available plans for subscription.
- Click on the Subscribe button under the Default plan.
- Select the Mobile App Consumer toggle and click the Subscribe button.
The MobileApp Consumer application is now subscribed to the Default plan for the think API product.
In this section, we will use the developer portal to test demo API. This is useful for application developers to try out the APIs before their application is fully developed or to simply see the expected response based on inputs they provide the API. We will test the demo API from the developer portal.
- Click the demo link on the left-hand navigation menu and then expand the GET /Customer path by clicking on the twisty next to the path.
- Scroll down to the Try this operation section for the GET /Customer path. Enter your Client ID and your Client secret and click the Call Operation button
- Scoll down below the Call operation button. You should see a 200 OK and a response body as shown below.
Now that you have browsed the API Portal and registered / tested the API’s that demo is providing, it’s time to test them out from a real application.
Sample code (snippets) are provided from developer portal for different language (cUrl, Ruby, Python, PHP, Javascript, Java, Go, Swift) .
- Login into the developer portal as an application developer using your developer credentials.
- Click the API Products link
- Click the demo (v1.0.0) API product link.
- Click on demo API in the left panel
- Now, you can discover all operations with their properties and on the right hand side sample code.
- On the right hand side you'll see the *cuRL expression
- Copy it into your text editor window replacing REPLACE_WITH_CLIENT_ID and REPLACE_WITH_CLIENT_SECRET with your client id and your client secret saved from the prior step
- Remove "filter" parameter in the url the result is like this :
curl --request GET \
--url 'https://api.eu.apiconnect.ibmcloud.com/BLUEMIXID-BLUEMIXSPACE/sb/api/Customers' \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header 'x-ibm-client-id: REPLACE_WITH_CLIENT_ID' \
--header 'x-ibm-client-secret: REPLACE_WITH_CLIENT_SECRET'
- Copy and try it into your terminal windows
If all is OK, you should see a list of cutomers in JSON format with items name and age.
- Return to the Bluemix API Manager screen.
- Navigate to the Dashboard section and click on the Sandbox catalog tile.
- Click on your demo API and you can see number of subscriptions to you API.
-
Now you can navigate to the Analytic dasbord to show analytic informations for your API
-
You can show
-
Click on the
Sandbox
catalog tile -
From the
Sandbox
catalog configuration screen, click on theAnalytics
tab. -
The default dashboard gives some general information like the 5 most active Products and 5 most active APIs. This information is interesting, but we can see much more information by customizing the dashboard. Add a new visualization by clicking on the
+ Add Visualization icon.
- This will bring a list of some of the standard visualizations. You can then type in a string to filter through visualizations or use the arrows to page through the list.
- Add the API Calls visualization to the dashboard by simply clicking on it. The new visualization will be added to the bottom of our dashboard.
- Scroll down to find the new visualization. You can adjust the size by clicking and dragging the border from the lower right. Additionally, you can adjust its position by clicking and dragging the box to where you want it.
- Feel free to play around with the other visualizations by adding them to the Dashboard. You can also save the dashboard by clicking on the Save Dashboard button:
In this lab, you will learn how to consume an API from a Mobile Application.
In this case, we will use a very simple sample of a Mobile Hybrid Application with the framework Ionic 1.7.
- Retrieve the sample from this url
Mobile App Sample https://github.com/fdut/bluemix-labs/raw/master/Lab%20API%20-%20Manage%20your%20APIs%20with%20API%20Connect/mobileapp.zip
- Unzip file and enter in the mobileapp folder
- Install cordova and ionic 1.7 framework
npm install -g [email protected] [email protected]
- Test installation
cordova -v
6.2
ionic -v
1.7.6
- Update your application with the url and the credential of your API (Remember the subscription step).
Update (with your preferred editor) the file mobileapp/www/js/controllers.js with your value for urlBase and headersBase
var urlBase = 'https://api.eu.apiconnect.ibmcloud.com/fredericdutheilfribmcom-fdulondonspace/sb/api/Customers'; //MUST REPLACE WITH API URL
var headersBase =
{
'X-IBM-Client-Id': '262fc263-3776-422b-bdcb-f2c1649a8d3d', //MUST REPLACE WITH CLIENT ID
'X-IBM-Client-Secret': 'vJ0aE1wI4kI6aT5fO8pD8uI2sS7sN4pD0cW6kJ6nQ8mY4qS5rH', //MUST REPLACE WITH CLIENT SECRET
'content-type': 'application/json',
'accept': 'application/json'
}
- Save and go back to the root directory of you app : mobileapp
- Enter the following command :
ionic serve
Note : if asked, use localhost for address to use.
This command simulate your app in a browser.
If all values are correct, you should see something as the screenshot below. A list with all the entries you are "POSTed" in Cloudant
Note : You can activate developer tools in the browser to show the result of your API request.
Now if you want, you can emulate you app in a emulator. In this sample we are going to use Android Emulator.
If Android SDK is not installed, use the following steps to install it (Example for linux)
wget http://dl.google.com/android/android-sdk_r24.4.1-linux.tgz
tar -xzvf android-sdk_r24.4.1-linux.tgz
cd android-sdk-linux
cd tools
echo y | ./android update sdk -u -a -t "tools","platform-tools","build-tools-23.0.3","android-23","sys-img-x86_64-android-23","sys-img-x86_64-google_apis-23"
Add android-sdk-linux/tools/android in the PATH of your operating system
For linux only :
sudo apt-get install -y lib32gcc1 libc6-i386 lib32z1 lib32stdc++6
sudo apt-get install -y lib32ncurses5 lib32gomp1 lib32z1-dev
- Configure virtual device with the following command :
android avd
Click Create Use the following value :
avd name = avd1
Device = nexus 5
Target = Android 6.0
cpu = intel atom x86_64
skin = noskin
Front camera = none
Back Camera = none
RAM 512 vm 64
- And click OK
- In the mobileapp folder, enter the following command :
cordova platform add android
and
ionic emulate android
Please wait a few time.
Note : If the launch is too long. Don't close the emulator, Stop the command with Ctrl+C and launch the command again.
Congratulations. You have completed this Lab!
For additional resources pay close attention to the following: