API 개요
Server, Load Balancer, Auto Scaling, Monitoring, Security, GeoLocation, Hash Filter 등의 다양한 기능을 API로 제어할 수 있습니다. API는 RESTful API 방식으로 제공되며, XML, JSON 형식으로 응답합니다. 액션에 따라 파라미터 값을 입력하고 등록, 수정, 삭제, 조회할 수 있으며, 서비스 및 운영 도구 자동화에 활용할 수 있습니다.
지원 API
상품 | API | SDK |
---|---|---|
Server | 지원 API - Server | ncloud_server_v2.zip |
Load Balancer | 지원 API - Load Balancer | ncloud_loadbalancer_v2.zip |
Auto Scaling | 지원 API - Auto Scaling | ncloud_autoscaling_v2.zip |
Monitoring | 지원 API - Monitoring | ncloud_monitoring_v2.zip |
Security | 지원 API - Security | ncloud_security_v2.zip |
GeoLocation | 지원 API - GeoLocation | ncloud_geolocation_v2.zip |
CDN | 지원 API - CDN | ncloud_cdn_v2.zip |
Cloud DB | 지원 API - Cloud DB | ncloud_clouddb_v2.zip |
Cloud Outbound Mailer | 지원 API - Cloud Outbound Mailer | ncloud_outboundmailer_v1.2.3.zip |
Contents
준비하기
계정별 키를 발급받아 사용할 수 있습니다.
- 인증키 생성
Access Key ID
,Secret Key
를 확인합니다.- 포털의 마이페이지 > 계정관리 > 인증키 관리 메뉴에서 "신규 API 인증키 생성"을 통해서
Access Key ID
,Secret Key
를 생성합니다. - sub account의 경우, 콘솔의 Sub Account > Sub Accounts > 서브 계정 상세 메뉴에서 "API Key"탭에서 생성한
Access Key ID
,Secret Key
를 사용할 수도 있습니다.
- API Key 생성
API Key
를 확인합니다.- 콘솔의 API Gateway > API Key 메뉴에서 "API Key 생성"을 통해서
API Key
를 생성합니다.
호출하기
- API 요청 메시지는 아래와 같이 구성됩니다.
{API URL}/{액션} + 액션 파라미터 + 응답 포맷 + AUTHPARMS(header)
- 발급받은 키(
Access Key ID
,Secret Key
,API Key
)로 API를 호출합니다. - v1의경우에는 호출시 API Key를 인증과 호출시 헤더에 반드시 포함해야 합니다.
- v2의경우에는 호출시 API Key를 인증이나 호출시 헤더에 포함할 필요가 없습니다
구분 | 정의 |
---|---|
API URL | Server ( https://ncloud.apigw.ntruss.com/server/v1/{action} )( https://ncloud.apigw.ntruss.com/server/v2/{action} )Load Balancer ( https://ncloud.apigw.ntruss.com/loadbalancer/v1/{action} )( https://ncloud.apigw.ntruss.com/loadbalancer/v2/{action} )Auto Scaling ( https://ncloud.apigw.ntruss.com/autoscaling/v1/{action} )( https://ncloud.apigw.ntruss.com/autoscaling/v2/{action} )Monitoring ( https://ncloud.apigw.ntruss.com/monitoring/v1/{action} )( https://ncloud.apigw.ntruss.com/monitoring/v2/{action} )Security ( https://ncloud.apigw.ntruss.com/security/v1/{action} )( https://ncloud.apigw.ntruss.com/security/v2/{action} )GeoLocation ( https://ncloud.apigw.ntruss.com/geolocation/v1/{action} )( https://ncloud.apigw.ntruss.com/geolocation/v2/{action} )Hash Filter ( https://ncloud.apigw.ntruss.com/hashfilter/v1/{action} )( https://ncloud.apigw.ntruss.com/hashfilter/v2/{action} ) |
액션 | 서버 자원 요청 액션(생성, 삭제, 조회 등) action=createServerInstances |
액션 파라미터 | serverName=myserver&serverImageProductCode=SPSWLINUX000031 요청한 파라미터는 URL Encoding이 된상태로 요청되어야 합니다. |
액션 | XML, JSON 응답 형식을 지원(기본값: XML) responseFormatType=xml |
AUTHPARAMS | Request header에 필수 key를 추가 (x-ncp-apigw-api-key, x-ncp-apigw-timestamp, x-ncp-iam-access-key, x-ncp-apigw-signature-v1) |
- API 호출에 대한 응답을 처리합니다.
- 응답형식은 각각의 지원 API에서 확인합니다.
액션 파라미터
기본적으로 Key, Value 쌍으로 구성되어 있으며, 리스트(List
- 일반적인 액션 파라미터
&pageNo=1
&serverName=myServer
…
- 리스트형 액션 파라미터
&serverInstanceNoList.1=1
&serverInstanceNoList.2=2
…
- Map리스트형 액션 파라미터
&loadBalancerRuleList.1.protocolTypeCode=HTTP
&loadBalancerRuleList.1.loadBalancerPort=80
&loadBalancerRuleList.1.serverPort=80
&loadBalancerRuleList.2.l7HealthCheckPath=/l7check.html
&loadBalancerRuleList.1.protocolTypeCode=HTTP
&loadBalancerRuleList.1.loadBalancerPort=81
&loadBalancerRuleList.1.serverPort=81
&loadBalancerRuleList.2.l7HealthCheckPath=/l7check2.html
…
AUTHPARAMS 생성하기
Header | Description |
---|---|
x-ncp-apigw-timestamp | 1970년 1월 1일 00:00:00 협정 세계시(UTC)부터의 경과 시간을 밀리초(millisecond)로 나타낸 것이다. APIGW 서버와 시간차가 5분 이상 나는 경우 유효하지 않은 요청으로 간주 |
x-ncp-apigw-api-key | API Gateway에서 발급받은 키 (primary key 또는 secondary key) |
x-ncp-iam-access-key | 포털 또는 sub account에서 발급받은 Access Key ID |
x-ncp-apigw-signature-v1 | 위 예제의 Body를 Access Key Id와 맵핑되는 SecretKey로 암호화한 서명 HMAC 암호화 알고리즘은 HmacSHA256 사용 |
curl -i -X GET \
-H "x-ncp-apigw-timestamp:1505290625682" \
-H "x-ncp-apigw-api-key:cstWXuw4wqp1EfuqDwZeMz5fh0epaTykRRRuy5Ra" \
-H "x-ncp-iam-access-key:D78BB444D6D3C84CA38A" \
-H "x-ncp-apigw-signature-v1:WTPItrmMIfLUk/UyUIyoQbA/z5hq9o3G8eQMolUzTEo=" \
'https://ncloud.apigw.ntruss.com/petStore/v1/pets'
- Signature 생성하기
요청 | StringToSign |
---|---|
GET /photos/puppy.jpg?query1=&query2 x-ncp-apigw-timestamp={timestamp} x-ncp-apigw-api-key={apiKey} x-ncp-iam-access-key={accesskey} x-ncp-apigw-signature-v1={signature} |
GET /photos/puppy.jpg?query1=&query2 {timeStamp} {apiKey} {accessKey} |
개행문자는 \n을 사용합니다.
요청에 맞게 StringToSign를 생성하고 SecretKey로 HmacSHA256 알고리즘으로 암호화한 후 Base64로 인코딩합니다.
이 값을 x-ncp-apigw-signature-v1
로 사용합니다.
- Java 샘플 코드 (v1)
public String makeSignature() {
String space = " "; // one space
String newLine = "\n"; // new line
String method = "GET"; // method
String url = "/photos/puppy.jpg?query1=&query2"; // url (include query string)
String timestamp = "{timestamp}"; // current timestamp (epoch)
String apiKey = "{apiKey}"; // api key (from api gateway)
String accessKey = "{accessKey}" // access key id (from portal or sub account)
String secretKey = "{secretKey}";
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timestamp)
.append(newLine)
.append(apiKey)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
String encodeBase64String = Base64.encodeBase64String(rawHmac);
return encodeBase64String;
}
- Java 샘플 코드 (v2)
public String makeSignature() {
String space = " "; // one space
String newLine = "\n"; // new line
String method = "GET"; // method
String url = "/photos/puppy.jpg?query1=&query2"; // url (include query string)
String timestamp = "{timestamp}"; // current timestamp (epoch)
String accessKey = "{accessKey}" // access key id (from portal or sub account)
String secretKey = "{secretKey}";
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timestamp)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
String encodeBase64String = Base64.encodeBase64String(rawHmac);
return encodeBase64String;
}
- Java script 샘플 코드(v1)
/*
https://code.google.com/archive/p/crypto-js/
https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/crypto-js/CryptoJS%20v3.1.2.zip
*/
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
<script type="text/javascript" src="./CryptoJS/rollups/hmac-sha256.js"></script>
<script type="text/javascript" src="./CryptoJS/components/enc-base64.js"></script>
function makeSignature() {
var space = " "; // one space
var newLine = "\n"; // new line
var method = "GET"; // method
var url = "/photos/puppy.jpg?query1=&query2"; // url (include query string)
var timestamp = "{timestamp}"; // current timestamp (epoch)
var apiKey = "{apiKey}"; // api key (from api gateway)
var accessKey = "{accessKey}" // access key id (from portal or sub account)
var secretKey = "{secretKey}"; // secret key (from portal or sub account)
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);
hmac.update(method);
hmac.update(space);
hmac.update(url);
hmac.update(newLine);
hmac.update(timestamp);
hmac.update(newLine);
hmac.update(apiKey);
hmac.update(newLine);
hmac.update(accessKey);
var hash = hmac.finalize();
return hash.toString(CryptoJS.enc.Base64);
}
- Java script 샘플 코드(v2)
/*
https://code.google.com/archive/p/crypto-js/
https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/crypto-js/CryptoJS%20v3.1.2.zip
*/
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
<script type="text/javascript" src="./CryptoJS/rollups/hmac-sha256.js"></script>
<script type="text/javascript" src="./CryptoJS/components/enc-base64.js"></script>
function makeSignature() {
var space = " "; // one space
var newLine = "\n"; // new line
var method = "GET"; // method
var url = "/photos/puppy.jpg?query1=&query2"; // url (include query string)
var timestamp = "{timestamp}"; // current timestamp (epoch)
var accessKey = "{accessKey}" // access key id (from portal or sub account)
var secretKey = "{secretKey}"; // secret key (from portal or sub account)
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);
hmac.update(method);
hmac.update(space);
hmac.update(url);
hmac.update(newLine);
hmac.update(timestamp);
hmac.update(newLine);
hmac.update(accessKey);
var hash = hmac.finalize();
return hash.toString(CryptoJS.enc.Base64);
}
- Python 3 샘플 코드(v1)
import sys
import os
import hashlib
import hmac
import base64
import requests
import time
def make_signature():
timestamp = int(time.time() * 1000)
timestamp = str(timestamp)
api_key = "{apiKey}" # api key (from api gateway)
access_key = "{accessKey}" # access key id (from portal or sub account)
secret_key = "{secretKey}" # secret key (from portal or sub account)
secret_key = bytes(secret_key, 'UTF-8')
method = "GET"
uri = "/photos/puppy.jpg?query1=&query2"
message = method + " " + uri + "\n" + timestamp + "\n"
+ api_key + "\n"
+ access_key
message = bytes(message, 'UTF-8')
signingKey = base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())
return signingKey
- Python 3 샘플 코드(v2)
import sys
import os
import hashlib
import hmac
import base64
import requests
import time
def make_signature():
timestamp = int(time.time() * 1000)
timestamp = str(timestamp)
access_key = "{accessKey}" # access key id (from portal or sub account)
secret_key = "{secretKey}" # secret key (from portal or sub account)
secret_key = bytes(secret_key, 'UTF-8')
method = "GET"
uri = "/photos/puppy.jpg?query1=&query2"
message = method + " " + uri + "\n" + timestamp + "\n"
+ access_key
message = bytes(message, 'UTF-8')
signingKey = base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())
return signingKey
- Bash 샘플코드(v1)
function makeSignature() {
nl=$'\\n'
TIMESTAMP=$(echo $(($(date +%s%N)/1000000)))
APIKEY="{apiKey}" # api key (from api gateway)
ACCESSKEY="{accessKey}" # access key id (from portal or sub account)
SECRETKEY="{secretKey}" # secret key (from portal or sub account)
METHOD="GET"
URI="/photos/puppy.jpg?query1=&query2"
SIG="$METHOD"' '"$URI"${nl}
SIG+="$TIMESTAMP"${nl}
SIG+="$APIKEY"${nl}
SIG+="$ACCESSKEY"
SIGNATURE=$(echo -n -e "$SIG"|iconv -t utf8 |openssl dgst -sha256 -hmac $SECRETKEY -binary|openssl enc -base64)
}
- Bash 샘플코드(v2)
function makeSignature() {
nl=$'\\n'
TIMESTAMP=$(echo $(($(date +%s%N)/1000000)))
ACCESSKEY="{accessKey}" # access key id (from portal or sub account)
SECRETKEY="{secretKey}" # secret key (from portal or sub account)
METHOD="GET"
URI="/photos/puppy.jpg?query1=&query2"
SIG="$METHOD"' '"$URI"${nl}
SIG+="$TIMESTAMP"${nl}
SIG+="$APIKEY"${nl}
SIG+="$ACCESSKEY"
SIGNATURE=$(echo -n -e "$SIG"|iconv -t utf8 |openssl dgst -sha256 -hmac $SECRETKEY -binary|openssl enc -base64)
}
응답 처리
API 응답에 대해 설명합니다.
API 응답 포맷
기본적으로 xml, json 형식의 응답 포맷을 지원합니다.
- xml 응답
<getZoneListResponse>
<requestId>c385247e-6c76-4b20-ba67-509d5dc95f68</requestId>
<returnCode>0</returnCode>
<returnMessage>success</returnMessage>
<zoneList>
<zone>
<zoneNo>2</zoneNo>
<zoneName>zone2</zoneName>
<zoneDescription>nang zone</zoneDescription>
</zone>
<zone>
<zoneNo>3</zoneNo>
<zoneName>zone3</zoneName>
<zoneDescription>nang zone2</zoneDescription>
</zone>
</zoneList>
</getZoneListResponse>
- json 응답
{
"getZoneListResponse": {
"requestId": "b6b9d54f-2770-40bb-a8a9-cc6aa46f75e0",
"returnCode": 0,
"returnMessage": "success",
"zoneList": [{
"zone": [{
"zoneNo": 2,
"zoneName": "zone2",
"zoneDescription": "nang zone"
}, {
"zoneNo": 3,
"zoneName": "zone3",
"zoneDescription": "nang zone2"
}]
}]
}
}
오류 처리
API 오류
API 요청이 잘못되거나 처리도중 오류가 발생하면 오류정보를 응답으로 전달합니다.
오류 발생 시 HTTP Response Code는 200 OK 이외의 값이 전달되며, 오류 정보는 리턴코드 < returnCode >와 리턴메시지 < returnMessage >로 구성되며, CommonResponse 데이터 타입을 가집니다. 또한 모든 오류는 < responseError >라는 이름으로 리턴됩니다.
Sample – 사용자오류 : HTTP Response Code = 400
<responseError> <returnCode>900</returnCode> <returnMessage> Required field is not specifie4. location : serverImageProductCode. </returnMessage> </responseError>
Sample – 인증오류 : HTTP Response Code = 401
<responseError> <returnCode>801</returnCode> <returnMessage>Signature is invalided</returnMessage> </responseError>
아래는 HTTP Response Code 기준으로 정렬한 오류 정보입니다.
HTTP Response Code | 리턴코드 | 리턴메시지 |
---|---|---|
400 | 900 ~ 999 | 파라미터 관련 오류 |
400 | 1100 | BAD REQUEST |
400 | 1400 ~ 1499 | 사용자에 의해 발생한 기타 오류 |
400 | 10000 ~ 29999 | 사용자에 의해 발생한 기타 오류 |
401 | 800 ~ 899 | 인증관련 오류 |
404 | 1101 | NOT FOUND |
405 | 1102 | METHOD NOT ALLOWED |
500 | 1000 ~ 1399 | 서버 내부 오류 |
아래 테이블은 위 테이블과 동일한 오류 정보이나 리턴 코드 기준으로 정렬했습니다.
HTTP Response Code | 리턴메시지 | 리턴코드 |
---|---|---|
401 | 인증관련 오류 | 800 – 899 |
400 | 파라미터 관련 오류 | 900 – 999 |
500 | 서버 내부 오류 | 1000 – 1399 |
400 | BAD REQUEST | 1100 |
404 | NOT FOUND | 1101 |
405 | METHOD NOT ALLOWED | 1102 |
400 | 사용자에 의해 발생한 기타 오류 | 1400 – 1499 |
400 | 사용자에 의해 발생한 기타 오류 | 10000 - 29999 |
API Gateway 오류
요청 파라미터가
responseFormatType=xml
일 때<?xml version='1.0' encoding='UTF-8' ?> <Message> <error> <errorCode>210</errorCode> <message>Permission Denied</message> </error> </Message>
요청 파라미터가
responseFormatType=json
일 때(default){ "error":{ "errorCode":"210", "message":"Permission Denied" } }
에러 코드
HttpStatusCode | ErrorCode | ErrorMessage | 설명 |
---|---|---|---|
400 | 100 | Bad Request Exception | protocol(https), endocing(UTF-8) 등 Request 에러 |
401 | 200 | Authentication Failed | 인증 실패 |
401 | 210 | Permission Denied | 권한 없음 |
404 | 300 | Not Found Exception | 권한 없음 |
429 | 400 | Quota Exceeded | Quota 초과 |
429 | 410 | Throttle Limited | Rate 초과 |
429 | 420 | Rate Limited | Rate 초과 |
413 | 430 | Request Entity Too Large | 요청 엔티티 크기 초과 |
503 | 500 | Endpoint Error | 엔드포인트 연결 에러 |
504 | 510 | Endpoint Timeout | 엔드포인트 연결 시간 초과 |
500 | 900 | Unexpected Error | 예외 처리가 안된 에러 |
추가 자세한 내용은 API 호출하기에서 확인합니다.