Skip to content

Instantly share code, notes, and snippets.

@nachoesmite
Last active February 17, 2017 21:09
Show Gist options
  • Save nachoesmite/e42cd9397d53a8311ba7a5db4b25b892 to your computer and use it in GitHub Desktop.
Save nachoesmite/e42cd9397d53a8311ba7a5db4b25b892 to your computer and use it in GitHub Desktop.
Anypoint Platform - One click Examples - Create a Proxy for weather
site apiNotebookVersion title
1.1.70
Anypoint Platform - One click Examples - Create a Proxy for weather

Manage an existing API, one endpoint at a time

Create an Access Management API Client and authenticate it hitting the public RAML.

  • Create the Client with the notebook and the public RAML url
API.createClient('anypointCS', 'https://anypoint.mulesoft.com/apiplatform/repository/v2/organizations/68ef9520-24e9-4cf2-b2f5-620025690913/public/apis/11270/versions/11646/files/root');
  • Authenticate using oauth2 implicit flow and the clientId used by the UI apiportal
API.authenticate(anypointCS,'oauth_2_0',{clientId:'apiportal'});
  • Store the bearer token, organization ID and organization name to use in the next API calls.
var meJSON = anypointCS.api.me.get().body;
var bearerToken = "Bearer " + meJSON.access_token.access_token;
var authHeaders = {"headers": {"Authorization": bearerToken }};
var organizationId = meJSON.user.memberOfOrganizations[0].id;
var orgname = meJSON.user.organization.name;
$2 = meJSON;

Create an API Platform Client to consume APIs

API.createClient('anypointAPI', 'https://anypoint.mulesoft.com/apiplatform/repository/v2/organizations/68ef9520-24e9-4cf2-b2f5-620025690913/public/apis/11197/versions/126378/files/root');

Create a new API

  • The API name will be random with the format: w-api-RAND
  • The version will be 1.0.0
  • The cloudhub domain that will be used later is the same as the api name
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}
var apiName = "w-api-" + guid();
var apiVersion = "1.0.0";
var cloudhubDomain = apiName;

var apiCreationJSON = anypointAPI.organizations.organizationId(organizationId).apis.post({"name":apiName,"version":{"name":apiVersion}} , authHeaders).body;
  • store apiID and apiVersionID to use it later.
var apiId = apiCreationJSON.version.apiId;
var apiVersionId = apiCreationJSON.version.id;
$5 = {'apiId': apiId, 'apiVersionId': apiVersionId}

Create Root RAML

  • Call the addRootRaml endpoint to create the root raml for the created API. As we are creating a proxy for openweathermap API the baseUri is http://api.openweathermap.org/data/2.5/
  • Store the rootRamlId in order to be able to easily update later
var raml = anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId).addRootRaml.post(
{"apiId":apiId,"apiVersionId":apiVersionId,"isDirectory":false,"name":"api.raml","data":"#%RAML 1.0\ntitle: OpenWeather\nversion: 2.5\nbaseUri: http://api.openweathermap.org/data/2.5/\n\ntraits:\n   isSearchableByCity:\n      queryParameters:\n        q:\n          description: city name\n          type: string\n          required: true\n          \n   isMetric:\n      queryParameters:\n       units:\n        description: Metric or Imperial\n        enum: [metric,imperial]\n        example: metric  \n  \n   isAPIKey:\n      queryParameters:\n       APPID: \n        description: API Key\n        example: 938ffc1ccc85558966b89eaa29a2ddc0\n      \n/weather:\n   displayName: Weather\n   is: [isSearchableByCity,isMetric,isAPIKey]\n   get:\n     description: |\n      Search weather by city name      \n     responses:\n      200:\n       body:\n        application/json: \n\n/forecast:\n  displayName: Forecast\n  is: [isSearchableByCity,isMetric,isAPIKey]\n  get:\n    description: |\n      seach weather forecast for 5 days with data every 3 hours by city name. \n    responses:\n     200:\n      body:\n        application/json: \n\n        \n/station:\n  displayName: Station\n  description: |\n    Get the most recent measurements from weather station.\n"}, authHeaders).body;

var rootRamlId = raml.rootFileId;

Create the portal

  • Call the portal endpoint to create the portal
  • Store portalId, homePageId and apiReferenceId
  • Add a widget to the home Page containing the text indicating that was autogenerated
var portal = anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId).portal.post({}, authHeaders).body;

var homePageId = portal.pages[0].id;
var apiReferenceId = portal.pages[1].id;
var portalId = portal.id;

anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId)
  .portal.pages.pageId(homePageId).widgets.patch([{"type":"markdown","data":"**Autogenerated Portal**","masterData":"","isBeingEdited":false,"order":0}], authHeaders);

Create the endpoint as a cloudhub endpoint

var endpoint = anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId).endpoint.post(
  {"type":"raml",                                                                                                                                                 
   "uri":"http://api.openweathermap.org/data/2.5/",
   "isCloudHub":true,
   "proxyUri":"http://0.0.0.0:8081/",
   "referencesUserDomain":false,
   "responseTimeout":null,
   "apiVersionId":apiVersionId}
, authHeaders).body;

Get the environmentID for the production environment

  • store the endpointId
var environments = anypointAPI.organizations.organizationId(organizationId).environments.get(null, authHeaders).body;
var environmentId;
for (var i = 0; i < environments.length; i++) {
  if (environments[i].isProduction) {
    environmentId = environments[i].id;
  }
}
$9 = environmentId; 

Apply Rate Limiting Policy

  • Configuration: 10 reqs per minute
anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId).policies.post(
  {"apiVersionId":apiVersionId,"policyTemplateId":"rate-limiting","configurationData":{"rateLimits":[{"maximumRequests":10,"timePeriodInMilliseconds":60000}]},"id":null}, authHeaders);

Trigger Deployment of the proxy in Cloudhub

anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId)
  .proxy.deployment.post({"type":"CH","overwrite":false,"applicationName": cloudhubDomain,"environmentId":environmentId,
                          "environmentName":"Production","gatewayVersion":"3.8.0"}, authHeaders);

Update the RAML file to point to the Proxy API

var raml2 = anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId)
  .files.apiVersionFileId(rootRamlId).put(
{"id": rootRamlId, "apiId":apiId,"apiVersionId":apiVersionId,"isDirectory":false,"name":"api.raml","data":"#%RAML 1.0\ntitle: OpenWeather\nversion: 2.5\nbaseUri: http://" + cloudhubDomain + ".cloudhub.io\n#baseUri: http://mocksvc.mulesoft.com/mocks/f675f079-c874-4c01-87fc-e04534cca70b/data/2.5/\n\ntraits:\n   isSearchableByCity:\n      queryParameters:\n        q:\n          description: city name\n          type: string\n          required: true\n          \n   isMetric:\n      queryParameters:\n       units:\n        description: Metric or Imperial\n        enum: [metric,imperial]\n        example: metric  \n  \n   isAPIKey:\n      queryParameters:\n       APPID: \n        description: API Key\n        example: 938ffc1ccc85558966b89eaa29a2ddc0\n      \n/weather:\n   displayName: Weather\n   is: [isSearchableByCity,isMetric,isAPIKey]\n   get:\n     description: |\n      Search weather by city name      \n     responses:\n      200:\n       body:\n        application/json: \n\n/forecast:\n  displayName: Forecast\n  is: [isSearchableByCity,isMetric,isAPIKey]\n  get:\n    description: |\n      seach weather forecast for 5 days with data every 3 hours by city name. \n    responses:\n     200:\n      body:\n        application/json: \n\n        \n/station:\n  displayName: Station\n  description: |\n    Get the most recent measurements from weather station.\n"}, authHeaders).body;

Make all content of the portal public

var portalJSON = anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId).versions.apiVersionId(apiVersionId).portal.get(null, authHeaders).body;

var pages = portalJSON.pages;

for (var i=0; i < pages.length; i++) {
   pages[i].visible = true;
   anypointAPI.organizations.organizationId(organizationId).apis.apiId(apiId)
     .versions.apiVersionId(apiVersionId).portal.pages.pageId(pages[i].id).put(pages[i], authHeaders);
}

Open the New API in the platform

setTimeout(function(){ 
  var win = window.open('https://anypoint.mulesoft.com/apiplatform/' + orgname + '/admin/#/organizations/' + organizationId + 
                      '/dashboard/apis/' + apiId + '/versions/' + apiVersionId + '/policies', '_blank');
  if (win) {
      win.focus();
  } else {
      alert('Please allow popups for anypoint platform');
  }
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment