Apigateway C - User Guide Intl en 2019 06 24
Apigateway C - User Guide Intl en 2019 06 24
Call an API
You can use API Gateway to call the API services enabled by other Alibaba Cloud users or third-party
service providers. API Gateway provides for you a series of management services and support.
Call example
Based on the SDKs provided by API Gateway, you can write codes to call an API. You can also edit an
HTTP request to call an API. The request structure of the API is as follows:
http://a13db7999e494a90819cce500130034d.com/web/cloudapi/mapping/service?a=name&b=12
//Requesting method.
//For more information about the methods of calculating and passing the encrypted signature, see
Portal and Protocol.
1
API Gateway User Guide for Consumers
//Body content.
Amount=11&InstanceId=ClientInstanceId&InstanceName=ClientInstanceName
An API request is constructed through the preceding content and the inputted parameters of the API.
At the public beta stage, you must obtain API documentation and details, such as the service address
and path, in the deprecation environment from the API service provider. The AppKey is the key for
the created app, which is used for identity verification. The app is your identity to call an API. For
more information, see subsequent content.
App
You must create an app as your identity to call an API. Each app has a key pair consisting of an
AppKey and AppSecret. These are used as the encrypted signature in your request and is verified by
the gateway verifies.
In API Gateway, create an app as your requester identity. During app creation, the system
automatically assigns an AppKey and AppSecret. The AppKey indicates your identity. The
AppSecret is the key used to encrypt the signature string and to verify the signature string
on the server. When calling an API, you must include the AppKey and AppSecret into the
request. API Gateway verifies your identity through symmetric encryption. For more
information about the methods of calculating and passing the encrypted signature, see
Portal and Protocol.
The AppKey and AppSecret have all of the permissions on the app, and therefore, must be
kept secure. If any of the keys are released, you must reset them on the API Gateway
console.
You can own multiple apps, to which different APIs are assigned based on your service
requirements. Note that the API authorization is specific to an app, but not the Alibaba
Cloud user account.
2
API Gateway User Guide for Consumers
On the API Gateway console, you can manage apps, view details, manage keys, and view
authorized apps.
Authorization
Authorization grants an app the permission to call an API. Your app needs authorization for an API
before calling it. At the public beta stage, the API service provider establishes the permission
relationship between an app and API.
At the public beta stage, the API service provider establishes the authorization. You must
provide the API service provider with your AppID or Alibaba Mail account to indicate that an
app is given for authorization. After authorization, you can use this app to call the API.
At the public beta stage, you do not have permission to establish or revoke authorization.
You can only view the authorized APIs under an app on the console. If you need to revoke
the authorization for an API, contact the API service provider.
Encrypted signature
When you call an API, API Gateway uses the AppKey and AppSecret to calculate the encrypted
signature for identity verification.
In API Gateway, you must use an app as your identity to call an API. During app creation, the
system automatically assigns an AppKey and AppSecret which is used for the server to verify
your identity.
Either the HTTP or HTTPS request must include signature information. The AppKey indicates
your identity. The AppSecret is used to encrypt and verify the signature string on the server.
For more information about the methods of calculating and passing the encrypted signature,
see Portal and Protocol.
3
API Gateway User Guide for Consumers
Limits
Domain name
- Each API belongs to an API group, and each API group has a unique domain name. These
independent domain names are bound by the service provider. API Gateway uses a domain
name to locate an API group.
- The domain name is in the format of www.[Independent domain
name].com/[Path]?[HTTPMethod]. At the public beta stage, the API user needs to obtain this
domain name offline from the API service provider.
- Alibaba Cloud API Gateway uses the domain name to locate a unique API group, and then
locate the unique API through Path+HTTPMethod.
- You must obtain API documentation in the deprecation environment from the API service
provider. This documentation must include necessary parameter information, such as the
4
API Gateway User Guide for Consumers
System headers
- [Required] X-Ca-Key: AppKey
- [Required] X-Ca-Signature: Signature string
- [Optional] X-Ca-Timestamp: The time stamp in milliseconds passed by the API caller, that is,
the milliseconds of the time from January 1, 1970 until now. By default, it is valid within 15
minutes.
- [Optional] X-Ca-Nonce: The UUID generated by the API caller. This header is used with the
time stamp to prevent replay.
- [Optional] Content-MD5: When the request body is not a Form, calculate the MD5 value of
the body and send that value to the cloud gateway for checking.
- [Optional] X-Ca-Stage: The stage where the requested API belongs. Only test and release are
supported, and the default value is release.
Signature verification
For more information about the demo (Java) of signature calculation, see here.
String stringToSign=
HTTPMethod + "\n" +
Accept + "\n" +
Content-MD5 + "\n"
Content-Type + "\n" +
Date + "\n" +
Headers +
Url
If Accept, Content-MD5, Content-Type, and Date are empty, add a linefeed (\n). If Headers is empty, a
linefeed (\n) is not required. The specified Headers includes a linefeed (\n). For more information, see
the headers organization method described as follows.
Content-MD5
Content-MD5 indicates the MD5 value of the body. MD5 is only calculated when the body is not a
Form. The calculation method is as follows:
5
API Gateway User Guide for Consumers
Headers
Headers indicates the keys and values of the headers involved in signature calculation. Note that X-
Ca-Signature and X-Ca-Signature-Headers are excluded in Headers signature calculation.
Rank the keys of all Headers involved in signature calculation in lexicographic order and then splice
them in the following method:
String headers =
HeaderKey1 + ":" + HeaderValue1 + "\n"\+
HeaderKey2 + ":" + HeaderValue2 + "\n"\+
...
HeaderKeyN + ":" + HeaderValueN + "\n"
URL
URL indicates the Form parameter in the Path+Query+Body. The organization method is as follows:
Rank the keys of Query+Form in lexicographic order and then splice them in the following method. If
Query or Form is empty, the URL is equal to Path, and a question mark (?) is not required to be
added.
String url =
Path +
"?" +
Key1 + "=" + Value1 +
"&" + Key2 + "=" + Value2 +
...
"&" + KeyN + "=" + ValueN
Note that Query or Form may have multiple values. If multiple values exist, use the first value for
signature calculation.
Put the calculated signature in the Header of the Request. The key is X-Ca-Signature.
6
API Gateway User Guide for Consumers
Separate the keys of all Headers involved in signature calculation by commas and put them in the
Header of the Request regardless of the order. The key is X-Ca-Signature-Headers.
For more information about the demo of signature calculation, click here.
1. Preface
Postman is a powerful HTTP client for testing Web services. Postman is available as a native
application for Windows, Mac, and Linux systems. You must sign HTTP requests to an API before you
can call the API. Simple HTTP client tools such as Curl cannot be used to sign the requests. However,
you can use the Pre-request Script feature of Postman to sign and debug API requests and
implement API calls.
You must sign incoming requests to API Gateway by using AppKeys and AppSecrets, which can be
obtained from the API Gateway console. You must also ensure that the requested APIs have been
published and specific applications are authorized to call the APIs.
7
API Gateway User Guide for Consumers
-Content-MD5: the MD5 value of the request body. This header is used to verify whether the request body is
tampered with when it is not a Form.
{HTTPMethod} + "\n" +
{Accept} + "\n" +
{Content-MD5} + "\n"
{Content-Type} + "\n" +
{Date} + "\n" +
{SignatureHeaders} +
{UrlToSign}
- Even if Accept, Content-MD5, Content-Type, and Date are not specified, line breaks “\n”
are required.
- Content-MD5 is calculated only when the message body is not a Form. The calculation
formula is as follows: base64Encode(md5(body.getBytes("UTF-8"))
- SignatureHeaders: Headers to be signed are added in ascending order in the form of
{HeaderName}:{HeaderValue} + "\n". Recommended signature headers are X-Ca-Key and X-
Ca-Nonce. You can choose other headers to add to the signature.
- UrlToSign: All Form and QueryString fields are placed together and sorted by Name. If
Content-Type is not application/x-www-form-urlencoded, all Form fields are treated as a
whole. Sorted key-value pairs are appended to Path to obtain UrlToSign. Assume that the
query string is /Demo? C = 1 & a = 2 and the form data is B = 3, then UrlToSign=/Demo?
a=2&b=3&c=1.
2.3. Calculate the signature and add the headers related to the
signature
We recommend that you use the HMAC-SHA256 algorithm to calculate the signature based on the
AppSecret. The calculation formula is as follows:signature =
base64(hmacSHA256(stringToSign.getBytes("UTF-8), appSecret)). You must add the following
headers after the calculation:
- X-Ca-Siguature:{signature}
- X-Ca-SignatureMethod:HmacSHA256
- X-Ca-SignatureHeaders:X-Ca-Key,X-Ca-Nonce
8
API Gateway User Guide for Consumers
Date:{{Date}}
Content-MD5:{{Md5}}
X-Ca-Nonce:{{Nonce}}
X-Ca-Key:{{AppKey}}
X-Ca-Signature:{{Signature}}
X-Ca-SignatureMethod:HmacSHA256
X-Ca-Signature-Headers:{{SignatureHeaders}}
The following figure shows the result after the string is pasted into the text box.
9
API Gateway User Guide for Consumers
Click the position circled in red to enter pre-request scripts. Copy and paste the following code into
the text box:
10
API Gateway User Guide for Consumers
pm.globals.set('AppKey', appKey);
pm.globals.set('Md5', md5);
pm.globals.set("Date", date);
pm.globals.set("Signature", signature);
pm.globals.set("SignatureHeaders", signatureHeaders);
pm.globals.set("Nonce", nonce);
function headersToSign() {
var headers = new Map();
for (var name in request.headers) {
name = name.toLowerCase();
if (! name.startsWith('x-ca-')) {
continue;
}
if (name === "x-ca-signature" || name === "x-ca-signature-headers" || name == "x-ca-key" || name === 'x-ca-
nonce') {
continue;
}
var value = request.headers[name];
headers.set(name, value);
}
headers.set('x-ca-key', appKey);
headers.set('x-ca-nonce', nonce);
return headers;
}
function urlToSign() {
var params = new Map();
var contentType = request.headers["content-type"];
if (contentType && contentType.startsWith('application/x-www-form-urlencoded')) {
const formParams = request.data.split("&");
formParams.forEach((p) => {
const ss = p.split('=');
params.set(ss[0], ss[1]);
})
}
const ss = request.url.split('?') ;
if (ss.length > 1 && ss[1]) {
const queryParams = ss[1].split('&');
queryParams.forEach((p) => {
const ss = p.split('=');
params.set(ss[0], ss[1]);
})
}
var l1 = ss[0].lastIndexOf('/');
var url = ss[0].substring(l1);
var first = true;
var qs
for (var k of sortedKeys) {
var s = k + "=" + params.get(k);
qs = qs ? qs + "&" + s : s;
11
API Gateway User Guide for Consumers
function calcMd5() {
var contentType = request.headers["content-type"];
if (request.data && ! contentType.startsWith('application/x-www-form-urlencoded')) {
var data = request.data;
var md5 = CryptoJS.MD5(data);
var md5String = md5.toString(CryptoJS.enc.Base64);
console.log("data:" + data + "\nmd5:" + md5String);
return md5String;
} else {
return "";
}
}
function createUuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
12