Create new completely populated Service

Update specific property of all Endpoints for a given Service

Sample Code (Python):
import requests, json
from requests.auth import HTTPBasicAuth
apiHost = 'https://api.mashery.com'
tokenEndpoint = '/v3/token'
resourceEndpoint = '/v3/rest'
apikey = '<Insert V3 API Key>'
secret = '<Insert V3 API Secret>'
username = '<Insert Mashery Portal username>'
password = '<Insert Mashery Portal password'
areaUuid = '<Insert Mashery Area UUID>'
serviceId = '<Insert Mashery API Definition UUID>'
def authenticate(apikey, secret, username, password, areaUuid):
payload = {'grant_type': 'password', 'username' : username, 'password' : password, 'scope' : areaUuid}
response = requests.post(apiHost + tokenEndpoint, auth=HTTPBasicAuth(apikey, secret), data=payload)
return response.json()['access_token']
def callApi(token, resource, params, payload):
headers = {"Content-type": "application/json", "Authorization": 'Bearer ' + token}
if payload is None:
response = requests.get(apiHost + resourceEndpoint + resource + '?' + params, headers=headers)
else:
response = requests.put(apiHost + resourceEndpoint + resource + '?' + params, headers=headers, data=json.dumps(payload))
return response.json()
# authenticate (get oauth 2 token)
token = authenticate(apikey, secret, username, password, areaUuid)
# get service with specific fields of endpoints
service = callApi(token, '/services/' + serviceId, 'fields=endpoints.id,endpoints.requestAuthenticationType', None)
# update the data object, setting specific property, 'requestAuthenticationType', to a new value
for endpoint in service['endpoints']:
endpoint['requestAuthenticationType'] = 'apiKeyAndSecret_MD5'
# put the service back with the updated data
service = callApi(token, '/services/' + serviceId, 'fields=endpoints.id,endpoints.requestAuthenticationType', service)
Clone a Service

Sample Code (Java):
package com.mashery.pm.example.utilities;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
public class CloneApi {
private static String apikey = "<Insert API key here>";
private static String secret = "<Insert API secret here>";
private static String apiHost = "https://api.mashery.com";
private static String tokenEndpoint = "/v3/token";
private static String resourceEndpoint = "/v3/rest";
private static String areaUuid = "<Insert Area UUID here>";
private static String username = "<Insert username>";
private static String password = "<Insert password>";
private static String serviceId = "<Insert Service UUID>";
/**
* @param args
*/
public static void main(String[] args) {
try {
// authenticate
String token = authenticate(apikey, secret, username, password, areaUuid);
// GET an existing API
String service = callApi(token, "GET", "/services/" + serviceId,
"fields=name,robotsPolicy,crossdomainPolicy,description,errorSets," +
"qpsLimitOverall,rfc3986Encode,securityProfile,version,endpoints.inboundSslRequired," +
"endpoints.jsonpCallbackParameter,endpoints.jsonpCallbackParameterValue," +
"endpoints.scheduledMaintenanceEvent,endpoints.forwardedHeaders,endpoints.returnedHeaders," +
"endpoints.methods.name,endpoints.methods.sampleXmlResponse,endpoints.methods.sampleJsonResponse," +
"endpoints.methods.responseFilters,endpoints.name,endpoints.numberOfHttpRedirectsToFollow," +
"endpoints.outboundRequestTargetPath,endpoints.outboundRequestTargetQueryParameters," +
"endpoints.outboundTransportProtocol,endpoints.processor,endpoints.publicDomains," +
"endpoints.requestAuthenticationType,endpoints.requestPathAlias,endpoints.requestProtocol," +
"endpoints.oauthGrantTypes,endpoints.stringsToTrimFromApiKey,endpoints.supportedHttpMethods," +
"endpoints.systemDomainAuthentication,endpoints.systemDomains,endpoints.trafficManagerDomain," +
"endpoints.updated,endpoints.useSystemDomainCredentials,endpoints.systemDomainCredentialKey," +
"endpoints.systemDomainCredentialSecret", null);
// Update API to make endpoint paths unique; system requires a unique combination of hostname+requestPath+HTTP Method
// The below is a simple search and replace. More robust JSON processing should be used.
service = service.replaceAll("v1","v2");
// Call to API to POST the service data
service = callApi(token, "POST", "/services", null, service);
System.out.println(service); // Created API from existing API definition
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String callApi(String token, String method, String resource, String parameters, String body) throws IOException, Exception {
URL urlObj = new URL(apiHost + resourceEndpoint + resource + ( parameters != null && parameters.length() > 0 ? "?" + parameters : ""));
HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
con.setRequestMethod(method);
con.setRequestProperty("Authorization", "Bearer " + token);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
if (method.equals("POST") || method.equals("PUT"))
{
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
InputStream is;
if (responseCode >= 400) {
is = con.getErrorStream();
} else {
is = con.getInputStream();
}
if (is != null) {
BufferedReader in = new BufferedReader(
new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
return null;
}
private static String authenticate(String apikey, String secret, String username, String password, String areaUuid) throws IOException, Exception {
URL urlObj = new URL(apiHost + tokenEndpoint);
HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
String userpass = apikey + ":" + secret;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
String body = "grant_type=password&username="+username+"&password="+password+"&scope=" + areaUuid;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
InputStream is;
if (responseCode >= 400) {
is = con.getErrorStream();
} else {
is = con.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if (response != null) {
response.toString().substring(0, response.length() - 1);
String[] cells = response.substring(0, response.length() - 1).split(",");
for (int i = 0; i < cells.length; i++) {
if (cells[i].contains("access_token")) {
return cells[i].replaceAll("\"", "").split(":")[1];
}
}
}
return response.toString();
}
}
Add a newly created Endpoint to a Package Plan
TO-DO