여기에 설명된 사용자 지정 magritte-rest-v2 소스 유형을 사용하는 레거시 REST API 옵션은 과거 기록 참조용으로만 제공됩니다. 이 기능은 더 이상 활발하게 개발되지 않으므로 사용하지 않아야 합니다.
대신 다음을 지원하는 REST API 소스 유형을 사용하세요.
REST API 소스 유형은 에이전트 프록시 송신 정책을 사용하여 온프레미스 REST API에 연결하는 데에도 사용할 수 있습니다.
다음 개념은 magritte-rest-v2 소스를 사용할 때의 정보 흐름을 설명합니다.
state의 변수를 후속 호출에 주입할 수 있습니다. 이를 통해 상호 의존적인 요청을 수행할 수 있습니다.다음 다이어그램은 위 개념의 상호 작용을 보여줍니다.

magritte-rest-v2 소스 생성magritte-rest-v2 소스를 생성하려면 Data Connection 애플리케이션의 소스 탭에서 새 소스를 선택하세요. 그런 다음 사용자 지정 소스 추가 옵션을 선택하세요. magritte-rest-v2 플러그인은 주로 YAML 에디터를 통해 구성합니다.
다음 예제는 다양한 인증 유형을 구성하는 데 필요한 YAML 코드 스니펫을 제공합니다.
이 관련 문서는 다음 주제에 대한 추가 지침도 제공합니다.
Copied!1 2 3 4 5 6 7type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest headers: Authorization: 'Bearer {{token}}' url: "https://some-api.com/"
Basic 인증이라고도 합니다.
Copied!1 2 3 4 5 6type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest usernamePassword: '{{username}}:{{password}}' url: "https://some-api.com/"
Copied!1 2 3 4 5 6 7 8type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest-auth-call-source url: "https://some-api.com/" requestMimeType: application/json body: '{"username": "{{username}}", "password": "{{password}}"}' authCalls: []
Copied!1 2 3 4 5 6 7 8 9type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest-auth-call-source url: "https://some-api.com/" parameters: username: "{{username}}" password: "{{password}}" authCalls: []
다음 구성을 사용하면 URL로 인코딩된 양식 본문을 /auth 엔드포인트에 제출하고 반환된 토큰을 동기화에 사용할 수 있습니다. 엔드포인트가 양식 유형인 경우에만 formBody를 사용하고, 그렇지 않으면 body를 사용하세요.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest-auth-call-source url: "https://some-api.com/" headers: Authorization: 'Bearer {%token%}' authCalls: - type: magritte-rest-call path: /auth method: POST formBody: username: '{{username}}' password: '{{password}}' extractor: - type: magritte-rest-json-extractor assign: token: /token
반환된 토큰이 동기화가 완료되기 전에 자주 만료되는 경우 authExpiration 파라미터를 사용하여 authCalls 아래의 호출을 재시도할 주기를 지정하세요. authExpiration 값은 /auth 엔드포인트에서 반환된 토큰의 유효 기간을 초과하지 않도록 설정하세요.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest-auth-call-source url: "https://some-api.com/" authExpiration: 30m headers: Authorization: 'Bearer {%token%}' authCalls: - type: magritte-rest-call path: /auth method: POST formBody: username: '{{username}}' password: '{{password}}' extractor: - type: magritte-rest-json-extractor assign: token: /token
API에서 로그인에 성공하기 위해 구독 키와 같은 보안 헤더를 사용하는 경우 authCalls 아래에 헤더 섹션을 추가해야 합니다. 이 두 번째 헤더 섹션은 인증 호출 전용으로 사용되며 첫 번째 헤더 섹션과는 완전히 별개입니다. 인증 호출을 제외한 다른 모든 API 호출은 첫 번째 헤더 섹션을 사용합니다. 이러한 헤더 섹션을 올바르게 구성하지 않으면 401 인증 실패가 발생할 수 있습니다. 다음은 예제입니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest-auth-call-source url: "https://some-api.com/" headers: X-service-identifier: SWN Authorization: 'Bearer {%token%}' Ocp-Apim-Subscription-Key: '{{subscriptionKey}}' authCalls: - type: magritte-rest-call path: /auth method: POST headers: X-service-identifier: SWN Ocp-Apim-Subscription-Key: '{{subscriptionKey}}' body: username: '{{username}}' password: '{{password}}' extractor: - type: magritte-rest-json-extractor assign: token: /token
다음 구성을 사용하면 한 도메인에서 인증하여 다른 도메인에서 토큰을 사용할 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22type: magritte-rest-v2 sourceMap: auth_api: type: magritte-rest url: "https://auth.api.com" data_api: type: magritte-rest-auth-call-source url: "https://data-api.com/" headers: Authorization: 'Bearer {%token%}' authCalls: - type: magritte-rest-call source: auth_api path: /auth method: POST formBody: username: '{{username}}' password: '{{password}}' extractor: - type: magritte-rest-json-extractor assign: token: /token
소스는 인증을 위한 Java KeyStore(JKS) 파일 제공을 지원합니다.
Copied!1 2 3 4 5 6 7type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest url: "https://some-api.com/" keystorePath: "/my/keystore/keystore.jks" keystorePassword: "{{password}}"
다음 curl 명령 curl -v http://example.com/do.asmx --ntlm -u DOMAIN\\username:password는 다음과 같이 변환할 수 있습니다.
Copied!1 2 3 4 5 6type: magritte-rest-ntlm-source url: http://example.com user: "{{username}}" password: "{{password}}" domain: DOMAIN (optional) workstation: (optional) the name of your machine as given by $(hostname)
Copied!1 2 3 4 5 6type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest url: http://example.com proxy: 'http://my-proxy:8888/' # IP 주소를 전달할 수도 있습니다
구성에 프록시 자격 증명을 전달할 수도 있습니다.
Copied!1 2 3 4 5 6 7 8 9type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest url: http://example.com proxy: url: 'http://my-proxy:8888/' # IP 주소를 전달할 수도 있습니다 username: 'my-proxy-username' password: 'my-proxy-password'
javax.net.ssl.SSLHandshakeException과 같은 오류가 표시되면 이 가이드에 따라 서버 인증서를 에이전트의 신뢰 저장소에 추가해야 할 수 있습니다.
디버깅 목적으로만 인증서 검사를 비활성화할 수도 있습니다. 이는 안전하지 않은 -k 플래그를 사용하여 curl을 실행하는 것과 같습니다(curl -k https://some-domain).
Copied!1 2 3 4 5 6type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest url: https://example.com insecure: true
기본적으로 플러그인은 최신 TLS 버젼(TLSv1.2 및 TLSv1.3)으로만 연결합니다.
이전 버젼을 사용하려면 구성에서 TLS 버젼을 지정하세요.
Copied!1 2 3 4 5 6type: magritte-rest-v2 sourceMap: my_api: type: magritte-rest url: https://example.com tlsVersion: 'TLSv1.1'
지원되는 버젼: TLSv1.3, TLSv1.2, TLSv1.1, TLSv1, SSLv3.
동기화를 생성하려면 magritte-rest-v2 소스 상단에서 "동기화 생성" 버튼을 클릭합니다. 기본 보기에서는 데이터를 가져오는 하나 이상의 호출을 생성하는 과정을 안내합니다. 고급 보기에서는 YAML 구성을 직접 편집할 수 있습니다. 페이지 오른쪽 상단에서 두 보기 사이를 전환할 수 있습니다.
동기화에는 하나 이상의 호출이 필요합니다. 기본 보기에서는 "순차적으로 호출 수행" 제목 아래의 "추가" 버튼을 클릭하여 새 호출을 생성할 수 있습니다.
그런 다음 "단일 호출"을 선택하여 호출을 한 번 수행할지, 루프, 시간 범위, 날짜 범위, 목록 또는 결과 페이징을 기반으로 여러 번 수행할지 지정할 수 있습니다.
각 호출에는 쿼리 시 소스 URL에 추가할 경로가 필요합니다. 예를 들어 소스의 URL이 https://my-ap-source.com이고 경로로 /api/v1/get-documents를 사용하면 호출은 https://my-ap-source.com/api/v1/get-documents를 쿼리합니다.
이 섹션에서는 일반적인 시나리오에 해당하는 YAML 구성 목록을 제공합니다.
이 관련 문서에서는 다음 주제에 대한 추가 지침도 제공합니다.
/daily_data?date=2020-01-01에서 각 날짜에 대한 CSV 보고서를 제공하는 API를 가정해 보겠습니다. 이 예제에서는 이러한 보고서가 제공되는 대로 수집하려고 합니다. 이를 위해 보고서가 동기화된 마지막 날짜를 기억하는 일일 동기화 일정을 설정하여, 오늘까지 동기화되지 않은 날짜의 보고서를 자동으로 가져올 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26type: rest-source-adapter2 outputFileType: csv incrementalStateVars: incremental_date_to_query: '2020-01-01' initialStateVars: yesterday: type: magritte-rest-datetime-expression offset: '-P1D' timezone: UTC formatString: 'yyyy-MM-dd' restCalls: - type: magritte-increasing-date-param-call checkConditionFirst: true paramToIncrease: date_to_query increaseBy: P1D initValue: '{%incremental_date_to_query%}' stopValue: '{%yesterday%}' format: 'yyyy-MM-dd' method: GET path: '/daily_data' parameters: date: '{%date_to_query%}' extractor: - type: magritte-rest-string-extractor fromStateVar: 'date_to_query' var: 'incremental_date_to_query'
위 구성을 동일한 기능의 Python 스니펫과 비교하면 도움이 될 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20import requests from datetime import datetime, timedelta incremental_state = load_incremental_state() if incremental_state is None: incremental_state = {'incremental_date_to_query': '2020-01-01'} yesterday = datetime.utcnow() - timedelta(days=1) date_to_query = incremental_state['incremental_date_to_query'] date_to_query = datetime.strptime(date_to_query, '%Y-%m-%d') while yesterday >= date_to_query: response = requests.get(source.url + '/daily_data', params={ 'date': date_to_query.strftime('%Y-%m-%d') }) upload(response) date_to_query += timedelta(days=1) incremental_date_to_query = date_to_query save_incremental_state({'incremental_date_to_query': incremental_date_to_query})
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-paging-inc-param-call paramToIncrease: page initValue: 0 increaseBy: 1 method: GET path: '/data' parameters: page: '{%page%}' entries_per_page: 1000 extractor: - type: magritte-rest-json-extractor assign: page_items: '/items' condition: type: magritte-rest-non-empty-condition var: page_items
개발자라면 위 구성을 동일한 기능의 Python 스니펫과 비교하여 더 쉽게 이해할 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14import requests page = 0 while True: response = requests.get(source.url + '/data', params={ 'page': page, 'entries_per_page': 1000 }) upload(response) page += 1 page_items = response.json().get('items') if not page_items: break
다음은 ElasticSearch 기본 검색 API의 예제입니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-paging-inc-param-call paramToIncrease: offset initValue: 0 increaseBy: 100 method: POST path: '/_search' body: |- { "from": {%offset%}, "size": 100 } extractor: - type: magritte-rest-json-extractor assign: hits: '/hits' condition: type: magritte-rest-non-empty-condition var: hits
다음 페이지 토큰은 커서, 연속 또는 페이지 매김 토큰이라고도 합니다.
다음은 ElasticSearch 검색 및 스크롤 API의 예제입니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-rest-call method: GET path: /my-es-index/_search?scroll=1m parameters: scroll: 1m extractor: - type: json assign: scroll_id: /_scroll_id - type: magritte-do-while-call method: GET checkConditionFirst: true path: /_search/scroll parameters: scroll: 1m scroll_id: '{%scroll_id%}' extractor: - type: json assign: scroll_id: /_scroll_id hits: /hits timeBetweenCalls: 0s condition: type: magritte-rest-non-empty-condition var: hits
다음은 AWS nextToken 페이지 매김 API의 예제입니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-rest-call method: POST path: /findings/list extractor: - type: json assign: nextToken: /nextToken allowNull: false allowMissingField: true requestMimeType: application/json body: '{}' - type: magritte-do-while-call method: POST checkConditionFirst: true path: /findings/list extractor: - type: json assign: findings: /findings nextToken: /nextToken allowNull: false allowMissingField: true condition: type: magritte-rest-available-condition var: nextToken timeBetweenCalls: 0s requestMimeType: application/json body: '{"nextToken":"{%nextToken%}"}'
다음 sync는 상호 의존적인 세 단계가 필요한 API를 위한 것입니다.
status 필드가 포함됩니다.Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-rest-call path: '/findRelevantId' method: POST requestMimeType: application/json extractor: - type: json assign: id: /id body: > body saveResponse: false - type: magritte-do-while-call path: '/reportReady' method: GET parameters: id: '{%id%}' extractor: - type: magritte-rest-json-extractor assign: status: /status condition: type: "magritte-rest-regex-condition" var: status matches: "(processing|queued)" timeBetweenCalls: 8s saveResponse: false - type: magritte-rest-call path: '/getReport/{%id%}' method: GET requestMimeType: application/json
Extractor는 상태에 저장할 필드를 정의하며, 이러한 변수는 이후의 모든 REST 호출에서 사용할 수 있습니다. 저장된 변수를 삽입하려면 변수 이름을 {%%}로 감쌉니다. 두 번째 do-while 호출은 상태 변수가 더 이상 대기 중 또는 처리 중이 아닐 때까지 요청을 보내는 루프를 구현합니다.
일부 API에는 status 엔드포인트가 없으며, 대신 보고서가 준비될 때까지 빈 응답을 제공하는 getReport 엔드포인트를 폴링해야 합니다. 다음 구성은 이러한 시나리오를 처리하는 방법을 보여줍니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-do-while-call path: '/getReport/{%id%}' method: GET extractor: - type: magritte-rest-string-extractor var: response condition: type: magritte-rest-not-condition condition: type: magritte-rest-non-empty-condition var: response timeBetweenCalls: 8s
또는 getReport 엔드포인트가 보고서가 준비될 때까지 204 상태 코드를 반환하는 경우 다음과 같이 처리할 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14type: rest-source-adapter2 outputFileType: json restCalls: - type: magritte-do-while-call path: '/getReport/{%id%}' method: GET extractor: - type: magritte-rest-http-status-code-extractor assign: responseCode condition: type: magritte-rest-regex-condition var: responseCode matches: 204 timeBetweenCalls: 8s
이 플러그인은 점진적 동기화를 지원합니다. 이를 사용하려면 incrementalStateVars를 지정하여 state에서 동기화의 점진적 state로 저장할 변수를 선택합니다.
Copied!1 2 3type: rest-source-adapter2 incrementalStateVars: var_name: initial_value # 점진적 메타데이터를 찾을 수 없을 때 사용하는 초기값
Copied!1 2 3type: rest-source-adapter2 incrementalStateVars: lastModifiedDate: 20190101
저장된 점진적 state는 동기화 실행 시 초기 state로 사용됩니다.
더 자세한 예제:
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23type: rest-source-adapter2 outputFileType: json incrementalStateVars: lastModifiedTime: 'Some initial start time' initialStateVars: # 현재 시간 가져오기 currentTime: type: magritte-rest-datetime-expression timezone: 'Some timezone, e.g. Europe/Paris' formatString: 'Some format string https://docs.oracle.com/javase/8/docs/api/ \ java/time/format/DateTimeFormatter.html' restCalls: - type: magritte-rest-call path: /my/values method: GET parameters: from: '{%lastModifiedTime%}' until: '{%currentTime%}' extractor: # 마지막 수정 시간을 현재 시간으로 업데이트 - type: magritte-rest-string-extractor var: lastModifiedTime fromStateVar: currentTime
API 소스를 두 개 이상 추가하는 경우 각 REST 호출에서 source 속성으로 사용할 소스를 지정해야 합니다.
동기화 구성에는 다음 필드가 포함됩니다.
Copied!1 2 3 4 5 6 7 8 9type: rest-source-adapter2 restCalls: [calls] # 아래 Calls 관련 문서 참조 initialStateVars: {variableName}: {variableValue} incrementalStateVars: {variableName}: {variableValue} outputFileType: json # oneFilePerResponse에 필수 cacheToDisk: defaults to True oneFilePerResponse: defaults to True; when set to True "outputFileType" is required
outputFileType으로 결과물 파일 유형을 설정하려면 oneFilePerResponse가 true여야 합니다. 그렇지 않으면 응답이 데이터셋의 행으로 저장됩니다. 응답 유형에 따른 권장 옵션은 아래의 응답 저장을 참조하세요.
바이너리 응답이거나 응답 크기의 총합이 100MB를 초과하는 경우 다음을 권장합니다.
Copied!1 2 3cacheToDisk: true outputFileType: [any file format, e.g. txt, json, jpg] oneFilePerResponse: true # 기본값이므로 지정할 필요 없음
개별 크기가 수 MB 이하이고 응답 크기의 총합이 100MB 미만인 비바이너리 응답에는 다음을 권장합니다.
Copied!1 2cacheToDisk: false oneFilePerResponse: false
응답이 디스크에 모두 들어가지 않지만 총 동기화 시간이 짧은 경우(3분 미만)에는 다음을 권장합니다.
Copied!1 2 3cacheToDisk: false oneFilePerResponse: true outputFileType: [any file format, e.g. txt, json, jpg]
모든 호출은 다음 필드가 포함된 기본 RestCall 오브젝트를 상속합니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28type: Rest call type path: Endpoint method: GET | POST | PUT | PATCH # 아래 항목은 모두 선택 사항 source: The API source to use for this call. # API 소스가 여러 개인 경우 필수입니다. parameters: Map of parameters to pass with request # 기본값은 빈 맵 saveResponse: Should the response be saved in foundry # 기본값은 True body: Body to post formBody: # x-www-form-urlencoded POST에 사용할 파라미터 맵입니다. # 선택 사항이며, x-www-form-urlencoded 엔드포인트를 호출할 때만 body 대신 사용합니다. param1: value1 requestMimeType: application/json headers: Request headers, these append to the source headers, but replace matching headers # validResponseCodes: 선택 사항으로, API 호출자가 종료되지 않는 HTTP 응답 코드 집합입니다. # 설정하지 않으면 유효한 HTTP 응답 코드는 200, 201, 204입니다. validResponseCodes: - 200 - 201 - 204 # retries: 기본값은 0입니다. 취소, 연결 문제 또는 시간 초과로 인해 요청이 실패할 수 있습니다. # 이 호출에서 수행하는 요청별로 원하는 재시도 횟수를 설정할 수 있습니다. retries: 0 extractor: A list of extractor object, see Extractors # 파일 이름 템플릿(예: 'data_{%page%}'), # 그렇지 않으면 파일 이름은 '[sourceName][path][parameters]'이 됩니다 filename: '<dont override if not necessary>' addTimestampToFilename: Defaults to true, whether timestamp should be appended to filename
상속하는 호출은 위 필드 외에 추가 필드를 포함할 수 있습니다.
Copied!1type: magritte-rest-call
단일 요청을 수행합니다. 핵심 호출과 동일한 YAML 설정을 사용합니다.
특정 조건이 충족되는 동안 파라미터 값을 증가시키며 동일한 요청을 수행합니다. 주로 페이징에 사용됩니다. 증가시키는 파라미터가 경로 또는 parameters: 섹션에 포함된 경우 해당 값은 {%paramToIncrease%}여야 합니다.
Copied!1 2 3 4 5 6 7 8 9 10 11type: magritte-paging-inc-param-call paramToIncrease: state key to param to increase. checkConditionFirst: when set to "true", equivalent to a while loop. When "false" (default) equivalent to do-while loop. initValue: Initial value of increasing parameter. increaseBy: How much to increase the parameter by in each iteration. onEach: List of calls to run in each iteration. Optional and used to do nested calls. condition: Condition object that keeps requests going. As long as the condition is true, a new request is created. The condition is checked only after the first request, so this acts similarly to a do-while loop. maxIterationsAllowed: How many iterations to run before throwing an error. timeBetweenCalls: (optional) time to wait between requests
특정 조건이 충족될 때까지 날짜 파라미터를 증가시키며 동일한 요청을 수행합니다. 날짜를 순회하는 데 사용됩니다. LocalDate 및 Period 유형을 사용하므로 사용 가능한 최소 증분 단위는 하루입니다. 날짜만 일치시키는 경우에만 작동합니다. 더 세밀한 단위로 증가시켜야 하는 경우 `magritte-increasing-time-param-call``을 참조하세요.
Copied!1 2 3 4 5 6 7 8 9type: magritte-increasing-date-param-call paramToIncrease: state key to param to increase. checkConditionFirst: when set to "true", equivalent to a while loop. When "false" (default) equivalent to do-while loop. initValue: Initial value of increasing parameter. increaseBy: How much to increase the parameter by in each iteration, parseable as a java.time.Period stopValue: The last date which will be used, including this value if applicable. format: The format (java.time.format.DateTimeFormatter) for the DateTime parameter in each call, the same as initValue and stopValue. timeBetweenCalls: (optional) time to wait between requests
특정 조건이 충족될 때까지 DateTime 파라미터를 증가시키며 동일한 요청을 수행합니다. DateTime을 순회하는 데 사용됩니다. magritte-incrementing-date-param-call과 달리 OffsetDateTime 및 Duration 유형을 사용합니다. OffsetDateTime은 일광 절약 시간제에 따른 변경 사항을 고려하지 않습니다. 이로 인해 API의 DateTime 처리 방식에서 예상치 못한 공백이 발생하지 않는지 확인하세요.
Copied!1 2 3 4 5 6 7 8 9 10type: magritte-increasing-time-param-call paramToIncrease: state key to param to increase. checkConditionFirst: when set to "true", equivalent to a while loop. When "false" (default) equivalent to do-while loop. initValue: Initial value of increasing parameter. increaseBy: How much to increase the parameter by in each iteration, parseable as a java.time.Duration stopValue: The last DateTime which will be used, including this value if applicable. format: The format (java.time.format.DateTimeFormatter) for the DateTime parameter in each call, the same as initValue and stopValue. timeBetweenCalls: (optional) time to wait between requests
지정된 조건이 더 이상 충족되지 않을 때까지 요청을 수행합니다. 핵심 호출 필드 외에 두 개의 필드를 제공해야 합니다.
Copied!1 2 3 4 5 6type: magritte-do-while-call timeBetweenCalls: time to wait between requests checkConditionFirst: when set to "true", equivalent to a while loop. When "false" (default) equivalent to do-while loop. condition: Condition object that keeps requests going. As long as the condition is true, a new request is created. maxIterationsAllowed: How many iterations to run before throwing an error. Defaults to 50.
선택적으로 첫 번째 호출을 시작하기 위한 초기 state를 제공할 수 있습니다.
예:
Copied!1 2initialState: nextPage: ""
초기 state와 점진적 state가 충돌하는 경우 점진적 state가 초기 상태를 재정의합니다.
반복 가능한 state 요소의 각 항목에 대해 요청을 수행합니다.
Copied!1 2 3 4 5 6 7 8 9type: magritte-iterable-state-call timeBetweenCalls: 5s # 각 호출 사이의 시간 간격 조절 iterableField: The state key to iterate over. This variable must be iterable. iteratorExtractor: List of extractors to run on each element in the iterable. onEach: List of calls to run in each iteration. Optional and used to do nested calls. maxIterationsAllowed: How many iterations to run before throwing an error. Defaults to 50. parallelism: Integer number of threads to use for the sync. Assumptions/limitations include no side effect in request, no guarantee as to order that calls are made or their responses update state, no time between calls. This field is optional and defaults to 1.
추출기는 응답 또는 state 변수의 변수를 State에 저장하는 방법을 정의합니다. URL, URL 파라미터 또는 요청 본문에서 state의 변수를 {%var_name_1%}로 참조할 수 있습니다.
추출기는 기본적으로 응답에서 값을 추출합니다. 선택적으로 fromStateVar 설정을 추가하여 State에서 추출할 수 있습니다. 이를 통해 다음 예시와 같이 여러 추출기를 차례로 실행할 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15type: rest-source-adapter2 outputFileType: csv restCalls: - type: magritte-rest-call path: /my/path/index.html source: mysource method: GET extractor: - type: magritte-rest-json-extractor assign: full_name: /my/field/full_name - type: magritte-rest-regexp-extractor fromStateVar: full_name assign: names: '\w+'
모든 추출기에는 사용할 수 있는 조건 검사가 내장되어 있습니다.
Copied!1condition: Check whether the input state meets the given condition. If not, do not run the extractor.
모든 JSON 추출기는 Jackson JsonNode ↗를 사용하며 동일한 표기법을 따릅니다.
필드 참조에 대한 간단한 가이드:
JSON {"id":1}이 주어진 경우:
"/id"를 사용하면 1을 반환합니다."/"를 사용하면 {"id":1}을 반환합니다.[1,2,3] 또는 [{"id":1},{"id":2}]와 같은 리스트가 주어진 경우:
""를 사용하면 리스트를 반환합니다.와일드카드를 사용하여 리스트의 모든 항목에 있는 하위 인덱스 또는 필드를 참조할 수 있습니다. 예를 들면 다음과 같습니다.
{ "result": [[1], [2, 3, 4]] }와 같이 중첩된 리스트가 포함된 필드가 주어진 경우:
"/result/*/0"을 사용하면 [1,2]를 반환합니다.{ "result": [{ "foo": 1}, {"foo": 2}]}와 같이 오브젝트 리스트가 포함된 필드가 주어진 경우:
"/result/*/foo"를 사용하면 [1,2]를 반환합니다.응답의 필드를 State에 배치하는 추출기입니다. YAML 설정은 저장할 변수의 맵입니다. 왼쪽 스트링은 State에 있는 변수의 이름이고, 오른쪽 스트링은 변수의 경로입니다.
JSON 추출기는 와일드카드를 지원합니다. JSON [{"id":1}, {"id":2}]가 주어진 경우 /*/id를 사용하면 [1,2]를 반환하고, ""(빈 스트링)를 사용하면 전체 리스트를 반환합니다.
Copied!1 2 3 4type: json assign: var_name_1: /field-name1 var_name_2: /field_name2
기본적으로 추출된 필드의 값이 null이거나 필드가 존재하지 않으면 호출이 실패합니다.
이러한 상황에서 호출이 실패하지 않도록 다음 플래그를 사용할 수 있습니다.
allowMissingField: 필드가 존재하지 않거나 필드의 값이 null일 때 실패하지 않도록 합니다.allowNull: 존재하는 필드의 값이 null일 때 실패하지 않도록 합니다.allowUnescapedControlChars: JSON 응답에 과 같이 이스케이프되지 않은 제어 문자가 포함되어 있을 때 실패하지 않도록 합니다.Copied!1 2 3 4 5type: json allowMissingField: true assign: var_name_1: /field-name1 var_name_2: /field_name2
Copied!1 2 3 4type: magritte-rest-append-json-extractor appendFrom: /field in response that contains an array to append from appendFromItem: /field per array element to extract # 선택 사항 appendTo: variable name in state to append elements to.
응답이 다음과 같은 경우:
Copied!1 2 3 4{ "things": [{"name": "dummy", "id": "1"}, {"name": "dummy2", "id": "2"}] }
다음 YAML은:
Copied!1 2 3 4type: magritte-rest-append-json-extractor appendFrom: /things appendFromItem: /id appendTo: var
var에 [1,2]를 추가합니다.
또는 다음을 사용할 수 있습니다.
Copied!1 2 3type: magritte-rest-append-json-extractor appendFrom: /things appendTo: var
이 경우 state 변수에 [{"name": "dummy", "id": "1"}, {"name": "dummy", "id": "2"}]를 추가합니다.
Copied!1 2 3 4 5type: magritte-rest-max-json-extractor list: /field in response that contains an array to max over. item: /field per array element to extract var: state variable to save the max value to. previousVal: state variable to get the current max value from# Optional
응답이 다음과 같은 경우:
Copied!1 2 3 4{ "things": [{"name": "dummy", "value": "1"}, {"name": "dummy2", "value": "2"}] }
다음 YAML은:
Copied!1 2 3 4type: magritte-rest-max-json-extractor list: /things item: /id var: max_value
max_value에 2를 저장합니다.
또는 max_value에 이미 값 5가 있다고 가정하면 다음은:
Copied!1 2 3 4 5type: magritte-rest-max-json-extractor list: /things item: /id var: max_value previousVal: max_value
max_value를 5로 유지합니다.
응답의 각 줄에 JSON 파일이 포함되는 스트리밍 JSON(NDJSON) 형식용 추출기입니다. 이 형식은 일반적으로 데이터셋을 반환하는 데 사용되므로 각 줄에 동일한 형식의 JSON이 있어야 합니다.
이 추출기는 NDJSON 파일의 마지막 줄에 있는 경로에서 변수를 추출하는 기능을 지원합니다.
Copied!1 2 3 4type: magritte-rest-last-streaming-json-extractor nodePath: /id # JSON이 {'value':'somevalue', 'id':1} 형태인 경우 1을 추출합니다 varName: id # 값을 저장할 상태 변수의 이름 saveNulls: false # null을 변수에 저장할지 건너뛸지 여부(기본값: false)
이 추출기는 NDJSON 파일의 각 줄에서 변수를 추출하여 배열에 넣는 기능과 마지막으로 발견한 변수를 추출하는 기능을 지원합니다. 추출기가 null을 발견하면(줄 누락, 키 누락 또는 키의 값이 null인 경우) 반복을 중지합니다.
Copied!1 2 3 4 5 6type: magritte-rest-last-streaming-json-extractor nodePath: /id # JSON이 {'value':'somevalue', 'id':1} 형태인 경우 1을 추출합니다 arrayVarName: ids # 배열을 저장할 상태 변수의 이름 optional<lastVarName>: lastId # 배열의 마지막 값을 저장할 상태 변수의 이름 optional<limit>: 10 # 파싱할 줄 수를 제한하며, lastVarName과 함께 사용하고 # iterableStateCall과 결합하여 추출 실행당 호출 수를 제한할 수 있습니다
응답의 필드를 State에 배치하는 추출기입니다. YAML 설정은 저장할 변수의 맵입니다. 왼쪽 스트링은 State에 있는 변수의 이름이고, 오른쪽 스트링은 xpath 표기법을 사용하는 변수의 경로입니다.
Copied!1 2 3 4type: magritte-rest-xml-extractor assign: var_name_1: /top_level_tag/second_level_tag/text() var_name_2: /top_level_tag/text()
CSS 선택자를 사용하여 HTML에서 추출합니다(지원되는 선택자 구문 ↗). 추출할 속성을 지정할 수 있으며, 비워 두면 선택한 요소의 텍스트를 반환합니다. first가 true이면 추출기는 첫 번째 요소를 스트링 또는 숫자로 반환하려고 시도합니다. 이 추출기는 올바른 형식이 아닌 XML에도 사용할 수 있습니다.
Copied!1 2 3 4 5type: magritte-rest-html-extractor var: 'links' selector: "a[href$='pdf']" attribute: href # 선택 사항 first: false # 선택 사항, 기본값은 false
제공된 예시는 .pdf로 끝나는 모든 앵커 태그 하이퍼미디어 참조를 스트링 배열로 links 변수에 저장합니다.
스트링을 추출하고 정의된 변수에 이 스트링이 할당된 새 state를 반환합니다.
Copied!1 2type: magritte-rest-string-extractor var: 'variable_name'
state에 있는 변수의 부분 스트링을 추출하여 다른 상태에 저장합니다.
Copied!1 2 3 4 5 6type: magritte-rest-substr-extractor start: 2 # 시작 인덱스 length: 5 # 선택 사항, 부분 스트링의 길이(시작 인덱스 포함). # 설정하지 않으면 부분 스트링은 시작 인덱스 이후의 전체 스트링이 됩니다. assign: var_to_save_substring_to # var: state_variable_to_substring - DEPRECATED, use fromStateVar instead!
스트링에서 하나 이상의 정규식 일치 항목을 추출하는 추출기입니다. YAML 설정은 저장할 변수의 맵입니다. 왼쪽 스트링은 State에 있는 변수의 이름이고, 오른쪽 스트링은 일치 여부를 확인할 정규식입니다.
Copied!1 2 3 4type: magritte-rest-regexp-extractor assign: var_name_1: (1(.*)3|a(.*)c) var_name_2: (NotInString)
입력 스트링이 다음과 같으면:
abcHelloWorld123
응답은 다음과 같습니다.
Copied!1 2 3 4{ "var_name_1": ["abc", "123"], "var_name_2": [] }
다음은 HTML에서 CSV 링크를 추출한 다음 CSV를 가져오는 전체 사용 예시입니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22type: rest-source-adapter2 outputFileType: csv restCalls: - type: magritte-rest-call path: /my/path/index.html source: mysource method: GET extractor: - type: magritte-rest-regexp-extractor assign: file_paths: '(?<=https://www\.mysite\.com)(.*filename.*csv)(?=\")' saveResponse: false - type: magritte-iterable-state-call source: mysource timeBetweenCalls: 1s iterableField: file_paths method: GET path: '{%path%}' saveResponse: true iteratorExtractor: - type: magritte-rest-string-extractor var: 'path'
PySpark 함수 pyspark.sql.functions.regexp_replace와 유사하게 스트링에서 하나의 정규식 일치 항목을 치환하는 추출기입니다.
Copied!1 2 3 4type: magritte-rest-regexp-replace-extractor var: result # 결과 스트링으로 생성하거나 덮어쓸 `state` 변수 pattern: "[a]" # 검색할 정규 표현식 replacement: "A" # 정규 표현식과 일치하는 항목을 대체할 새 스트링
배열 추가 추출기는 state 변수를 받아 배열의 끝에 추가합니다. 이 추출기는 반복 가능한 state 호출에 전달할 경로를 수집하는 데 유용합니다.
Copied!1 2 3type: magritte-rest-append-array-extractor appendTo: target # target이 초기화되지 않은 경우 추출기가 빈 배열로 초기화합니다. fromStateVar: args # 단일 인수(append) 또는 컬렉션(extend)을 허용합니다
다음은 전체 예시입니다.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30type: rest-source-adapter2 restCalls: - type: magritte-paging-inc-param-call method: GET path: category paramToIncrease: page initValue: 0 increaseBy: 100 parameters: start_element: '{%page%}' num_elements: 100 extractor: - type: magritte-rest-json-extractor assign: res: /response/categories - type: magritte-rest-append-array-extractor fromStateVar: res appendTo: categories until: type: magritte-rest-non-empty-condition var: res - type: magritte-iterable-state-call method: GET path: 'category/{%category%}' timeBetweenCalls: 5s iterableField: categories iteratorExtractor: - type: magritte-rest-string-extractor var: category outputFileType: json
응답에서 HTTP 상태 코드를 추출합니다.
Copied!1 2type: magritte-rest-http-status-code-extractor assign: 'variable_name'
응답의 Set-Cookie 헤더에서 쿠키를 추출합니다.
Copied!1 2 3type: magritte-rest-set-cookie-header-extractor assign: var_name_1: cookie_name_in_set_cookie_header
지정된 배열에서 요소를 추출합니다.
Copied!1 2 3 4type: magritte-rest-array-element-extractor fromStateVar: Array var to extract an element from. index: The index of the element in the input array to extract. toStateVar: Name of the variable to extract the element to.
지정된 인덱스 파라미터는 음수일 수 있으며, 이 경우 배열의 끝에서 시작합니다. 예를 들어 -1은 마지막 요소를 추출합니다.
변수를 받아 사전 정의된 캐스팅 로직을 사용하여 변수의 유형을 캐스팅하고, 결과를 대상 변수에 저장하는 추출기입니다.
Copied!1 2 3 4type: magritte-rest-typecast-extractor fromStateVar: Input variable to the extractor. toStateVar: Output variable of the extractor. toType: Type of the output variable after casting.
toType 파라미터는 'java.lang.' 패키지 내의 유효한 Java 유형이어야 합니다.
유효한 유형의 예로는 'String', 'Integer'가 있으며, 'java.lang.Double'과 같이 전체 'java.lang' 패키지와 이름을 사용할 수도 있습니다.
유형 캐스팅이 작동하려면 입력 변수의 유형을 결과물 유형으로 캐스팅하는 사전 정의된 메서드가 있어야 합니다. 즉, 설정된 유형 간에 변수를 변환하는 코드가 플러그인 내에 있어야 합니다.
참고: 두 스트링 a와 b로 구성된 java.util.Arrays를 스트링으로 캐스팅하면 [a, b]가 반환됩니다. 반면 두 스트링 a와 b로 구성된 com.fasterxml.jackson.databind.node.ArrayNode를 스트링으로 캐스팅하면 JSON 배열의 스트링 표현인 ["a","b"]가 반환됩니다.
조건은 ElasticSearch 조건과 유사하게 작동합니다. 현재 지원되는 조건은 다음과 같습니다.
Copied!1 2 3type: magritte-rest-regex-condition var: a state variable key matches: a valid regular expression
예시:
Copied!1 2 3type: "magritte-rest-regex-condition" var: my_state_variable matches: '^\d+$'
지정된 변수를 사용할 수 있는지(null이 아닌 값이 할당되어 있는지) 확인합니다.
Copied!1 2type: magritte-rest-available-condition var: a state variable key
예시:
Copied!1 2type: magritte-rest-available-condition var: my_state_variable
지정된 변수를 사용할 수 있고 비어 있지 않은지 확인합니다.
Copied!1 2type: magritte-rest-non-empty-condition var: a state variable key
예시:
Copied!1 2type: magritte-rest-non-empty-condition var: my_array_state_variable
지정된 하위 조건을 부정합니다.
Copied!1 2type: magritte-rest-not-condition condition: A condition to negate.
예시:
Copied!1 2 3 4type: magritte-rest-not-condition condition: type: magritte-rest-available-condition var: my_state_variable
지정된 모든 하위 조건이 참이어야 합니다.
Copied!1 2type: magritte-rest-and-condition conditions: A list of conditions to AND over.
예시:
Copied!1 2 3 4 5 6type: magritte-rest-and-condition conditions: - type: magritte-rest-available-condition var: my_state_variable - type: magritte-rest-non-empty-condition var: my_array-state_variable
Copied!1 2 3 4 5type: magritte-rest-binary-condition toCompare: left: `state` key to compare on the left side of condition right: `state` key to compare on the right side of condition op: One of the following "=", "<", ">", "<=", ">="
예시:
Copied!1 2 3 4 5type: magritte-rest-binary-condition toCompare: left: a_state_variable right: another_state_variable op: <
표현식은 Magritte REST 동기화 중 어느 시점에서든 특정 값을 계산하는 데 사용할 수 있습니다. 추출기와 달리 표현식의 결과는 동기화의 state에 종속되지 않습니다.
특정 날짜 및/또는 시간을 제공하는 표현식입니다. 현재 날짜/시간을 기준으로 주어진 오프셋을 더합니다.
이 초기 state 변수의 기타 파라미터(예: 최상위 initialStateVars: 블록에 배치해야 함):
Copied!1 2 3 4 5type: magritte-rest-datetime-expression offset: Optional. Time to add or subtract from the current date/time. Can be negative. timezone: Optional. Which timezone to calculate the date/time for. Defaults to UTC. formatString: Optional. Output format of the calculated date and time. Defaults to ISO 8601 datetime with offset.
유효한 오프셋은 Java 8 Duration 관련 문서 ↗를 참조하세요.
유효한 시간대는 Java 8 ZoneId 관련 문서 ↗를 참조하세요.
유효한 결과물 형식 스트링은 Java 8 DateTimeFormatter ↗를 참조하세요.
리터럴 값을 제공하는 표현식입니다.
리터럴의 유형은 자동으로 추론되며 리터럴 표현식의 로그에서 확인할 수 있습니다. 현재 지원되는 유형은 스트링, 숫자, 리스트입니다.
Copied!1 2type: magritte-rest-literal-expression literalValue: Required.
예시:
Copied!1 2type: magritte-rest-literal-expression literalValue: 270
리스트 예시:
Copied!1 2type: magritte-rest-literal-expression literalValue: ["it's", "a", "kind", "of", "magic"]
JSON 데이터를 수집할 때:
Copied!1 2 3 4 5 6 7 8 9 10{ "response": { "size": 1000, "items": [ { "item id": 1, "status": { "modifiedAt": "2020-02-11" }, "com.palantir.metadata": { ... } }, { "item id": 2, "status": { "modifiedAt": "2020-02-12" }, "com.palantir.metadata": { ... } }, { "item id": 3, "status": { "modifiedAt": "2020-02-13" }, "com.palantir.metadata": { ... } } ] } }
magritte-rest-v2 플러그인을 사용하면 각 JSON 응답이 데이터셋에 별도의 파일로 저장됩니다.
이 데이터를 쉽게 처리하려면 원시 데이터셋에 스키마를 적용하세요.
{
"fieldSchemaList": [
{
"type": "STRING",
"name": "row",
"nullable": null,
"userDefinedTypeClass": null,
"customMetadata": {},
"arraySubtype": null,
"precision": null,
"scale": null,
"mapKeyType": null,
"mapValueType": null,
"subSchemas": null
}
],
"dataFrameReaderClass": "com.palantir.foundry.spark.input.DataSourceDataFrameReader",
"customMetadata": {
"format": "text",
"options": {}
}
}
이 데이터셋을 정리하여 각 item이 데이터셋의 별도 행이 되고 item 필드가 열이 되도록 하려면 Python 트랜스폼 리포지토리를 생성하세요.
새 utils/read_json.py 파일에 다음 스니펫을 추가하세요.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43from pyspark.sql import functions as F import json import re def flattenSchema(df, dontFlattenCols=[], jsonCols=[]): new_cols = [] for col in df.schema: _flattenSchema(col, [], new_cols, dontFlattenCols + jsonCols, jsonCols) print(new_cols) return df.select(new_cols) def _flattenSchema(field, path, cols, dontFlattenCols, jsonCols): curentPath = path + [field.name] currentPathStr = '.'.join(curentPath) if field.dataType.typeName() == 'struct' and currentPathStr not in dontFlattenCols: for field2 in field.dataType.fields: _flattenSchema(field2, curentPath, cols, dontFlattenCols, jsonCols) else: fullPath = '.'.join(['`{0}`'.format(col) for col in curentPath]) newName = '_'.join(curentPath) sanitized = re.sub('[ ,;{}()\n\t\\.]', '_', newName) if currentPathStr in jsonCols: cols.append(F.to_json(fullPath).alias(sanitized)) else: cols.append(F.col(fullPath).alias(sanitized)) def parse_json(df, node_path, spark): rdd = df.dataframe().rdd.flatMap(get_json_rows(node_path)) df = spark.read.json(rdd) return df def get_json_rows(node_path): def _get_json_object(row): parsed_json = json.loads(row[0]) node = parsed_json for segment in node_path: node = node[segment] return [json.dumps(x) for x in node] return _get_json_object
그런 다음 아래와 같은 코드로 Python 트랜스폼을 생성할 수 있습니다.
Copied!1 2 3 4 5 6 7 8 9 10 11from transforms.api import transform, Input, Output from utils import read_json @transform( output=Output("/output"), json_raw=Input("/raw/json_files"), ) def my_compute_function(json_raw, output, ctx): df = read_json.parse_json(json_raw, ['response', 'items'], ctx.spark_session) df = read_json.flattenSchema(df, jsonCols=['com.palantir.metadata']) output.write_dataframe(df)
다음과 같은 데이터셋이 생성됩니다.
item_id | status_modifiedAt | com_palantir_metadata
1 | "2020-02-11" | "{ ... }"
2 | "2020-02-12" | "{ ... }"
3 | "2020-02-13" | "{ ... }"