Download OpenAPI specification:Download
MyInfo REST APIs for retrieving Person data.
Note - this specification is subject to changes based on evolution of the APIs.
3.1.0 (16 September 2019)
cpfemployers
partialuinfin
housingtype
& hdbtype
3.0.2 (10 May 2019)
serialno
from pdl
and qdl
under drivinglicence
as it is not in use.3.0.0 (31 Mar 2019)
IMPORTANT NOTE: response format for person
API has substantial changes from the previous version. Please refer to Understanding the Data Structure for details.
2.2.1 (28 Dec 2018)
login_type
parameter must be provided in the authorise API call.2.2.0 (05 Dec 2018)
Base URL changes:
myinfosg.api.gov.sg
to api.myinfo.gov.sg
myinfosgstg.api.gov.sg/test
to test.api.myinfo.gov.sg
myinfosgstg.api.gov.sg/dev
to sandbox.api.myinfo.gov.sg
Security header (.e.
no longer needed in basestring)
.e.
is required in the domain name: e.g. myinfosgstg.api.gov.sg
-> myinfosgstg.e.api.gov.sg
.
api.myinfo.gov.sg
Data items deprecated:
New data items available:
Added link to MyInfo demo app under Support section for easy reference.
2.1.1 (21 September 2018)
token
and person
APIs for better clarity when troubleshooting.2.1.0 (01 July 2018)
2.0.0 (20 April 2018)
The RESTful API adopts Semantic Versioning 2.0.0 for releases, and every new release of the API increments the version numbers in the following format:
{MAJOR}.{MINOR}.{PATCH}
{MAJOR}
number introduces incompatible API changes with previous {MAJOR}
number also resets {MINOR}
to 0
,{MINOR}
number introduces new functionalities or information that are backward compatible also resets {PATCH}
to 0
, and{PATCH}
number introduces bug fixes and remains backward compatible.Pre-release or draft versions, when provided, are denoted by appended hypen -
with a series of separate identifiers {LABEL}-{VERSION}
following the {PATCH}
number. Such releases are unstable and may not provide the intended compatibility with the specification in draft status.
Serving as notice, the RESTful API in version 2.X.X
are incompatible with version 1.X.X
releases.
Despite backward compatibility in {MINOR}
or {PATCH}
releases, API consumers are best to evaluate and determine their implementation does not disrupt use-case requirements.
The following diagram illustrates how the integration with MyInfo APIs work:
As shown above, your application will be interfacing with our API Gateway to integrate successfully with MyInfo.
The RESTful APIs are provided in both testing and live environments, and are accessible over the Internet via HTTPS.
Consumers are to ensure firewall clearance on their edge network nodes for connecting to the APIs.
The convention used by API endpoints' URLs is in the following format:
https://{ENV_DOMAIN_NAME}/{CONTEXT}/{VERSION}/{RESOURCE}
{ENV_DOMAIN_NAME}
indicates MyInfo's API domain names - respectively:
sandbox.api.myinfo.gov.sg
, ortest.api.myinfo.gov.sg
, orapi.myinfo.gov.sg
, following/{CONTEXT}
, indicates the context of the API call = /com
/{VERSION}
indicates the endpoint's release {MAJOR}
version number path - for this release = /v3
/{RESOURCE}
indicates the API resource path name.
Any additional query string parameters are appended as needed.
The sandbox environment is used for your testing when developing your prototype. The Person-Sample and Person API will return test data described in https://api.singpass.gov.sg/library/myinfo/developers/resources-personas.
sandbox.api.myinfo.gov.sg
The test enviroment is used for testing your application with the full security measures required in production. The Person API will return test data described in https://api.singpass.gov.sg/library/myinfo/developers/resources-personas.
test.api.myinfo.gov.sg
The production enviroment is the actual live environment with full security measures and live data.
api.myinfo.gov.sg
The following are the scheduled downtimes for the various environments:
MyInfo's API gateway supports accessing of APIs via the following interfaces:
HTTP version 1.1 connection over TLS (Transport Layer Security) version 1.1 or 1.2 standards, and ciphersuites:
Below is the list of recommended cipher suites that you may use:
IMPORTANT: ensure your server supports TLS 1.1 or 1.2 and supports a cipher suite in the list above.
Accessing the RESTful APIs using prior versions of TLS and/or unsupported ciphersuites will result in connectivity errors. MyInfo's API gateway does not support 2-way TLS client nor mutual authentication.
API HTTP interface features:
Content-Type
header application/json
, alsoContent-Length
header is omitted by having Transfer-Encoding
header chunked
emitted for streaming data, andAccept-Encoding: gzip
and indicated in Content-Encoding
header gzip
.MyInfo APIs use OAuth2.0 authorisation code flow to perform authentication & authorisation.
The sequence diagram below illustrates the steps involved in integrating your application with our APIs:
The flow consists of 3 APIs:
Authorise
Token
Protected Resource (Person)
Access to all server-to-server APIs will be authenticated by MyInfo's API gateway. Prior to calling the APIs, respective consumers are required to have:
Authentication methods provided by MyInfo's API gateway on internet:
RS256
digital signature (see "Request Signing" section below)NOTE: Test and Production Environments only
All server-to-server API requests are to be digitally signed, by including the following parameters and values in the Authorization
header:
PKI_SIGN app_id="{app_id}",
nonce="{random_nonce}",
signature_method="RS256",
signature="{base64_url_percent_encoded_signature}",
timestamp="{unix_epoch_in_milliseconds}"
Note: Above sample is separated by lines for ease-of-reading, and new-line denotations are to be omitted in the actual request.
{app_id}
is the APP ID credential supplied upon onboarding,
{random_nonce}
is an unique randomly generated text used for replay prevention,
{signature_method}
is the signature algorithm of the authenticating gateway.
RS256
{base64_url_percent_encoded_signature}
is the binary of the generated signature encoded in Base64 URL-safe format,
{unix_epoch_in_milliseconds}
is the UNIX epoch time in milliseconds
Below is an example of an Authorization header for the sample application. Make sure you list the parameters in the sequence shown below.
Authorization: PKI_SIGN
app_id="STG2-MYINFO-SELF-TEST",
nonce="150590021034800",
signature_method="RS256",
signature="EEm+HEcNQajb5FkVd82zjojk+daYZXxSGPCOR2GHZeoyjZY1PK+aFMzHfWu7eJZYMa5WaEwWxdOdq5hjNbl8kHD7bMaOks7FgEPdjE++TNomfv7SMktDnIvZmPYAxhjb/C9POU2KT6tSlZT/Si/qMgD1cryaPwSeMoM59UZa1GzYmqlkveba7rma58uGwb3wZFH0n57UnouR6LYXDOOLkqi8uMZBuvRUvSJRXETAj2N0hT+4QJiN96Ct6IEQh/woZh0o74K5Ol9PpDSM08qC7Lj6N/k694J+hbBQVVviGn7/6mDkfbwdMDuoKs4t7NpqmAnwT+xaQSIZcexfrAVQYA==",
timestamp="1505900210349"
NodeJS
// generates the security headers for calling API gateway
function generateAuthorizationHeader(url, params, method, strContentType, authType, appId, keyCertContent, passphrase) {
if (authType == "L2") {
return generateRS256Header(url, params, method, strContentType, appId, keyCertContent, passphrase);
} else {
return "";
}
};
// Signing Your Requests
function generateRS256Header(url, params, method, strContentType, appId, keyCertContent, keyCertPassphrase) {
var nonceValue = nonce();
var timestamp = (new Date).getTime();
// A) Construct the Authorisation Token Parameters
var defaultAuthHeaders = {
"app_id": appId, // App ID assigned to your application
"nonce": nonceValue, // secure random number
"signature_method": "RS256",
"timestamp": timestamp // Unix epoch time
};
// B) Forming the Base String
// Base String is a representation of the entire request (ensures message integrity)
// i) Normalize request parameters
var baseParams = sortJSON(_.merge(defaultAuthHeaders, params));
var baseParamsStr = qs.stringify(baseParams);
baseParamsStr = qs.unescape(baseParamsStr); // url safe
// ii) concatenate request elements (HTTP method + url + base string parameters)
var baseString = method.toUpperCase() + "&" + url + "&" + baseParamsStr;
// C) Signing Base String to get Digital Signature
var signWith = {
key: fs.readFileSync(keyCertContent, 'utf8')
}; // Provides private key
// Load pem file containing the x509 cert & private key & sign the base string with it to produce the Digital Signature
var signature = crypto.createSign('RSA-SHA256')
.update(baseString)
.sign(signWith, 'base64');
// D) Assembling the Authorization Header
var strAuthHeader = "PKI_SIGN app_id=\"" + appId + // Defaults to 1st part of incoming request hostname
"\",timestamp=\"" + timestamp +
"\",nonce=\"" + nonceValue +
"\",signature_method=\"RS256\"" +
",signature=\"" + signature +
"\"";
return strAuthHeader;
};
NOTE: Person APIs only
Access Tokens are in JWT format. This JWT complies to the standard 'JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants' (https://tools.ietf.org/html/rfc7523). You will need to verify the token with our public cert (provided during application onboarding).
NodeJS
// Sample Code for Verifying & Decoding JWS or JWT
function verifyJWS(jws, publicCert) {
// verify token
// ignore notbefore check because it gives errors sometimes if the call is too fast.
try {
var jwspayload = jwt.verify(jws, fs.readFileSync(publicCert, 'utf8'), {
algorithms: ['RS256'],
ignoreNotBefore: true
});
return jwspayload;
}
catch(error) {
throw("Error with verifying and decoding JWS");
}
}
NOTE: Person APIs in Test and Production environments only
The response payload for the Person API (for test and production environments) is first signed, then encrypted:
Encryption protects the data at rest while a signed payload means, if necessary, you will be able to pass this signed payload to a 3rd party where they can verify the payload's integrity with our public certificate.
In order to read the payload, you have to perform the following steps in order:
After doing the above steps, your application will be able to extract the payload in JSON format.
NodeJS
// Sample Code for decrypting JWE
// Decrypt JWE using private key
function decryptJWE(header, encryptedKey, iv, cipherText, tag, privateKey) {
return new Promise((resolve, reject) => {
var keystore = jose.JWK.createKeyStore();
var data = {
"type": "compact",
"ciphertext": cipherText,
"protected": header,
"encrypted_key": encryptedKey,
"tag": tag,
"iv": iv,
"header": JSON.parse(jose.util.base64url.decode(header).toString())
};
keystore.add(fs.readFileSync(privateKey, 'utf8'), "pem")
.then(function(jweKey) {
// {result} is a jose.JWK.Key
jose.JWE.createDecrypt(jweKey)
.decrypt(data)
.then(function(result) {
resolve(JSON.parse(result.payload.toString()));
})
.catch(function(error) {
reject(error);
});
});
})
.catch (error => {
throw "Error with decrypting JWE";
})
}
The decrypted payload is signed according to JWS (JSON Web Signature) format, similar to the access token.
RS256
.NodeJS
// Sample Code for Verifying & Decoding JWS or JWT
function verifyJWS(jws, publicCert) {
// verify payload
// ignore notbefore check because it gives errors sometimes if the call is too fast.
try {
var jwspayload = jwt.verify(jws, fs.readFileSync(publicCert, 'utf8'), {
algorithms: ['RS256'],
ignoreNotBefore: true
});
return jwspayload;
}
catch(error) {
throw("Error with verifying and decoding JWS");
}
}
MyInfo Person data follows a specific structure that you need to understand to traverse the data effectively. This section will explain the structure in detail.
The diagram below illustrates how the data is represented logically:
Each top-level data item can either be a data item object or an array of data item objects. Each data item object will consist of the following properties:
classification
(Data classification of data field. Default 'C' - Confidential)source
(see below)lastupdated
(Last updated date of data field. See "full-date" here)unavailable
(in certain situations - see below) The source
property indicates the source of data. Possible values are:
Note: All Government-verified fields must be non-editable on your digital service form (some exceptions apply - see individual field descriptions).
In each data item, there can be multiple data properties or arrays of data properties.
Each data property will contain either:
value
property, orcode
and desc
properties, orNote:
value
property can be strings, numbers, or dates.code
and desc
pairs will contain the code and its matching description.value
is mutually exclusive from (code
+ desc
); i.e. if there is a value
, there will not be any code
or desc
.code
, there will always be a desc
- no value
will be present.Exceptions: For these cases, the values will be directly in the property and not in a value
, code
or desc
subproperty:
classification
, source
, lastupdated
, and unavailable
type
in address formatsSometimes, a requested data item is not applicable to the person. Examples include:
regadd
data item.passtype
data item.For a full list, refer to the "Data Catalog" section of MyInfo API Data in our portal.
Note: When a requested data item is not applicable to the person, the source
property will be 3. In such cases, please ignore the data item completely.
When a requested data item is not applicable to the entity:
source
property will be 3In such cases, please ignore the data item completely.
The RESTful APIs used HTTP specification standard status codes to indicate the success or failure of each request. Except gateway errors, the response content will be in the following JSON format:
{
"code": "integer (int32)",
"message": "string"
}
Refer to the individual API definitions for the error codes you might encounter for each API.
Please refer to the NDI {api} Portal for the following supporting materials where relevant:
For technical queries, contact support@myinfo.gov.sg.
For business queries, contact partner@myinfo.gov.sg.
PKI digital signature for server to server calls. See Request Signing for more details.
Security scheme type: | HTTP |
---|---|
HTTP Authorization Scheme | Mutual authentication via PKI digital signature in Authorization header |
The following are the available OAuth2 scopes for MyInfo APIs
Security scheme type: | OAuth2 |
---|---|
authorizationCode OAuth Flow | Authorization URL: /com/v3/authorise Token URL: /com/v3/token Scopes:
|
Retrieves a sample Person data from MyInfo based on UIN/FIN.
This API does not use OAuth2.0 to perform authentication or authorisation, and does not require authorisation token and digital signature.
Note: Null value indicates that an attribute is unavailable.
uinfin required | string Example: "S9812381D" |
attributes | Array of string Example: "name,hanyupinyinname" Comma separated list of attributes requested. Possible attributes are listed in the scopes of the OAuth2 Security Schema above. |
OK.
Note:
curl https://sandbox.api.myinfo.gov.sg/com/v3/person-sample/S9812381D
This API generates an access token when presented with a valid authcode obtained from the Authorise API. This token can then be used to request for the user's data that were consented.
Authorization required | string Add authorization token constructed containing the RSA digital signature of the base string. Refer to https://api.singpass.gov.sg/library/myinfo/developers/tutorial3 on how this token should be generated. Note: This header is not required when calling Sandbox API. |
code required | string The authcode given by the authorise API. |
grant_type | string Default: "authorization_code" Grant type for getting token (default "authorization_code") |
client_secret required | string Secret key given to your application during onboarding. |
client_id required | string Unique ID for your application. |
redirect_uri required | string Application's callback URL. |
state | string Identifier that represents the user's session with the client, provided earlier during the authorise API call. |
OK.
Returning a JSON object which contains the authorization access token (JWT) that will be used to retrieve the data from MyInfo.
Possible scenarios:
Unauthorized.
Possible scenarios:
Forbidden
Possible scenarios:
Unexpected error. Check response body for actual error.
// function to prepare request for TOKEN API function createTokenRequest(code) { var cacheCtl = "no-cache"; var contentType = "application/x-www-form-urlencoded"; var method = "POST"; var request = null; // preparing the request with header and parameters // assemble params for Token API var strParams = "grant_type=authorization_code" + "&code=" + code + "&redirect_uri=" + _redirectUrl + "&client_id=" + _clientId + "&client_secret=" + _clientSecret; var params = querystring.parse(strParams); // assemble headers for Token API var strHeaders = "Content-Type=" + contentType + "&Cache-Control=" + cacheCtl; var headers = querystring.parse(strHeaders); // Sign request and add Authorization Headers var authHeaders = generateAuthorizationHeader( _tokenApiUrl, params, method, contentType, _authLevel, _clientId, _privateKeyContent, _clientSecret ); if (!_.isEmpty(authHeaders)) { _.set(headers, "Authorization", authHeaders); } var request = restClient.post(_tokenApiUrl); // Set headers if (!_.isUndefined(headers) && !_.isEmpty(headers)) request.set(headers); // Set Params if (!_.isUndefined(params) && !_.isEmpty(params)) request.send(params); return request; }
This API returns user's data from MyInfo when presented with a valid access token obtained from the Token API.
Note: Null value indicates that an attribute is unavailable.
uinfin required | string Example: "S9812381D" UIN/FIN of user |
txnNo | string Transaction ID from requesting digital services for cross referencing. |
attributes required | Array of string Example: "name,hanyupinyinname" Comma separated list of attributes requested. Possible attributes are listed in the scopes of the OAuth2 Security Schema above. |
client_id required | string Example: "STG-180099999K-TEST01" Unique ID for your application. |
subentity | string <= 10 characters Example: "PARTNER001" Field that allows traceability to platform's client who will be receiving the person data. Only applicable to |
Authorization required | any Add authorization token constructed containing the RSA digital signature of the base string. Refer to https://api.singpass.gov.sg/library/myinfo/developers/tutorial3 on how this token should be generated. Also include the access token (JWT) from /token API in your header prefixed with 'Bearer'. Note: Only the Bearer token is required when calling Sandbox API. |
OK.
Note:
Unauthorized.
Possible scenarios:
Details will be given in the error object returned.
Forbidden
Possible scenarios:
Not Found.
Possible scenarios.
Unexpected error. Check response body for actual error.
// function to prepare request for PERSON API function createPersonRequest(uinfin, validToken) { var url = _personApiUrl + "/" + uinfin + "/"; var cacheCtl = "no-cache"; var method = "GET"; var request = null; // assemble params for Person API var strParams = "client_id=" + _clientId + "&attributes=" + _attributes; var params = querystring.parse(strParams); // assemble headers for Person API var strHeaders = "Cache-Control=" + cacheCtl; var headers = querystring.parse(strHeaders); var authHeaders; // Sign request and add Authorization Headers authHeaders = generateAuthorizationHeader( url, params, method, "", // no content type needed for GET _authLevel, _clientId, _privateKeyContent, _clientSecret ); if (!_.isEmpty(authHeaders)) { _.set(headers, "Authorization", authHeaders + ",Bearer " + validToken); } else { // NOTE: include access token in Authorization header as "Bearer " (with space behind) _.set(headers, "Authorization", "Bearer " + validToken); } // invoke token API var request = restClient.get(url); // Set headers if (!_.isUndefined(headers) && !_.isEmpty(headers)) request.set(headers); // Set Params if (!_.isUndefined(params) && !_.isEmpty(params)) request.query(params); return request; }