Foundry는 REST(representational state transfer) API를 제공하는 외부 시스템과 통합할 수 있습니다. REST API를 동기화하거나, 내보내거나, 대화형으로 호출하는지에 따라 다른 접근 방식을 사용해야 할 수 있습니다. 이 페이지에서는 REST API와 안전하고 효율적으로 통합하기 위한 여러 연결 옵션을 확인할 수 있습니다.
REST API 소스는 액션을 통해 Foundry 애플리케이션에서 외부 시스템으로 직접 대화형 HTTP 요청을 보내야 하는 워크플로에 사용할 수 있습니다. 예를 들어, 클릭 시 웹훅을 사용하여 REST 엔드포인트를 호출하는 버튼이 있는 Workshop 애플리케이션을 생성하여 해당 애플리케이션을 기존 워크플로 및 소스 시스템에 연결할 수 있습니다.
HTTP 엔드포인트로 연결되는 웹훅은 Data Connection의 REST API 소스 유형을 사용해야 합니다. 기본 URL, 인증 및 포트(선택 사항)를 구성해야 합니다.
| 옵션 | 필수 | 설명 |
|---|---|---|
| 도메인 | 예 | 하나 이상의 도메인을 지정해야 합니다. |
| 인증 | 예 | 각 도메인에 대해 인증을 지정해야 합니다. 옵션에는 없음, 기본, Bearer 토큰, API 키가 있습니다. |
| 포트 | 아니요 | 포트를 선택적으로 지정할 수 있습니다. 기본적으로 모든 REST 웹훅은 포트 443에서 HTTPS를 사용합니다. 다른 포트에서 수신 대기하는 시스템에 연결하려면 기본값이 아닌 포트(예: 8443)를 지정하세요. |
| 요청 옵션 | 아니요 | API 키 인증을 선택할 때 웹훅 요청에서 API 키를 쿼리 파라미터로 전달할지 헤더로 전달할지 선택할 수 있습니다. |
아래 구성 예시는 Bearer 토큰 인증을 사용하여 https://my-domain.com에 대한 연결을 구성하는 방법을 보여줍니다.
REST API 소스 유형은 동기화나 내보내기 같은 다른 기능을 지원하지 않습니다. 레거시 magritte-rest-v2 소스 유형은 웹훅 워크플로에 더 이상 권장되지 않습니다. REST API에 대한 동기화 및 내보내기에는 외부 변환을 사용해야 합니다.
REST API 호출이 필요한 동기화 및 내보내기를 구성하려면 외부 변환을 사용하세요. Python 코드 리포지토리에서 소스를 가져오고 API를 쿼리하는 사용자 지정 로직을 작성하면 됩니다.
에이전트 이그레스 정책을 사용하는 Foundry 워커를 사용할 때는 외부 변환을 통해 인터넷에서 접근할 수 없는 REST API 소스에 접근할 수 있습니다.
아래 예시는 복잡한 외부 변환의 일반적인 패턴을 보여줍니다.
OAuth 클라이언트 자격 증명 부여 ↗는 비대화형 서비스 간 REST API 호출에 사용되는 일반적인 인증 패턴입니다. 클라이언트는 OAuth2 서버의 토큰 엔드포인트에서 client_id와 client_secret을 수명이 짧은 액세스 토큰으로 교환한 다음, 리소스 API에 대한 모든 후속 요청의 Authorization 헤더에 해당 토큰을 Bearer 토큰으로 포함합니다.
변환을 작성하기 전에 OAuth2 토큰 엔드포인트 도메인과 리소스 API 도메인으로 REST API 소스를 구성하고, client_id와 client_secret을 소스의 추가 시크릿으로 저장하세요. 변환에 시크릿을 하드 코딩하지 마세요.
토큰 엔드포인트에 대한 요청은 최소한 다음 파라미터와 함께 application/x-www-form-urlencoded 콘텐츠 유형을 사용해야 합니다.
| 파라미터 | 값 |
|---|---|
grant_type | client_credentials |
client_id | 애플리케이션 클라이언트 ID |
client_secret | 애플리케이션 클라이언트 시크릿 |
scope | 공백으로 구분된 필수 범위 목록 |
액세스 토큰을 얻으면 리소스 API에 대한 모든 요청의 Authorization 헤더에 포함하세요.
Authorization: Bearer <access_token>
많은 API는 결과를 페이지 단위로 반환합니다. 일반적인 패턴에서는 응답의 nextPageToken 필드를 사용하여 추가 결과가 있음을 나타냅니다. 변환은 nextPageToken이 더 이상 반환되지 않을 때까지 반복해야 합니다.
액세스 토큰은 만료됩니다. 변환이 오랫동안 실행되는 경우 실행 도중에 새 토큰을 요청해야 할 수 있습니다. 토큰 응답의 expires_in 필드를 확인하여 토큰이 만료되는 시점을 파악하세요.
client_id/client_secret 예시다음 예시는 액세스 토큰을 요청하고 페이지네이션을 사용하는 리소스 API를 호출합니다. OAuth2로 보호되는 모든 REST 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61import logging import pandas as pd from transforms.api import Output, transform_pandas from transforms.external.systems import external_systems, Source, ResolvedSource logger = logging.getLogger(__name__) @external_systems( api_source=Source("<source_rid>") ) @transform_pandas( Output("<output_dataset_rid>"), ) def compute(api_source: ResolvedSource) -> pd.DataFrame: base_url = api_source.get_https_connection().url client = api_source.get_https_connection().get_client() client_id = api_source.get_secret("additionalSecretClientId") client_secret = api_source.get_secret("additionalSecretClientSecret") token_response = client.post( base_url + "/oauth/token", data={ "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": "<space-separated-scopes>", }, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) token_response.raise_for_status() access_token = token_response.json()["access_token"] auth_headers = {"Authorization": f"Bearer {access_token}"} results = [] page_token = None while True: params = {"pageSize": 100} if page_token: params["pageToken"] = page_token response = client.get( base_url + "/api/v1/<resource>", headers=auth_headers, params=params, ) response.raise_for_status() body = response.json() results.extend(body.get("data", [])) page_token = body.get("nextPageToken") if not page_token: break logger.info(f"Fetched {len(results)} items so far, continuing to next page.") return pd.DataFrame(results)
이 패턴을 적용하려면 토큰 엔드포인트 경로, 리소스 URL 및 scope 값을 대상 API에서 요구하는 값으로 바꾸세요. 일부 OAuth2 서버는 audience 또는 resource와 같은 추가 파라미터를 요구합니다. 이를 토큰 요청의 data 딕셔너리에 추가하세요.
대상 API가 Foundry API 자체인 경우(변환에서 Foundry 간 호출), Foundry 전용 토큰 엔드포인트, 범위 및 설정 단계는 코드에서 Foundry API 호출을 확인하세요.
NetSuite를 비롯한 일부 OAuth2 서버는 클라이언트가 일반 client_secret 대신 서명된 JWT 클라이언트 어설션으로 인증하도록 요구합니다. 다음 예시는 POST /account ↗ 엔드포인트를 사용하여 계정 입력 데이터셋을 기반으로 NetSuite의 계정 이름을 업데이트합니다. 이 부여 유형을 활성화하려면 client_id, certificate_id, certificate_private_key를 소스에 추가 시크릿으로 추가합니다.
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111from transforms.api import ( transform, Output, Input, TransformInput, TransformOutput, TransformContext, ) from transforms.external.systems import external_systems, Source, ResolvedSource import datetime import jwt from urllib.parse import urljoin import logging logger = logging.getLogger(__name__) @external_systems( netsuite_rest_source=Source("<source_rid>") ) @transform( output=Output("<dataset_rid>"), account_updates=Input("<dataset_rid>"), # Dataset with schema [account_id: String, account_name: String] ) def update_account_names( netsuite_rest_source: ResolvedSource, account_updates: TransformInput, output: TransformOutput, ctx: TransformContext, ): # --- Set up connections and secrets --- base_url = netsuite_rest_source.get_https_connection().url client = netsuite_rest_source.get_https_connection().get_client() client_id = netsuite_rest_source.get_secret("additionalSecretClientId") certificate_id = netsuite_rest_source.get_secret("additionalSecretCertificateId") certificate_private_key = netsuite_rest_source.get_secret("additionalSecretPrivateCertificate") # --- Helper: Make JWT token --- def make_jwt_token( url, client_id, certificate_id, certificate_private_key, lifetime_in_minutes=59 ): current_timestamp = datetime.datetime.now() expiration = current_timestamp + datetime.timedelta(minutes=lifetime_in_minutes) payload = { "iss": client_id, "scope": "rest_webservices", "aud": url, "iat": current_timestamp, "exp": expiration, } additional_headers = { "kid": certificate_id, } return jwt.encode( payload, certificate_private_key, algorithm="ES256", headers=additional_headers, ) # --- Helper: Get OAuth2 access token --- def get_oauth2_access_token(): url = urljoin(base_url, "/services/rest/auth/oauth2/v1/token") payload = { "grant_type": "client_credentials", "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "client_assertion": make_jwt_token( url, client_id, certificate_id, certificate_private_key, ), } headers = {"Content-Type": "application/x-www-form-urlencoded"} response = client.post(url, data=payload, headers=headers) return response.json()["access_token"] # --- Prepare data for update --- account_update_data = [ { "account_id": row.account_id, "payload": f'{{"acctName": "{row.account_name}"}}', } for row in account_updates.dataframe().collect() ] # --- Update accounts --- token = get_oauth2_access_token() headers = { "Content-Type": "application/json", "Authorization": f"Bearer {token}", } responses = [] for account in account_update_data: account_id = account["account_id"] payload = account["payload"] logger.info(f"Updating account: {account_id} with payload {payload}") url = urljoin(base_url, f"/services/rest/record/v1/account/{account_id}") response = client.patch(url, data=payload, headers=headers) responses.append( { "account_id": account_id, "response_status": response.status_code, "response": response.text, } ) output.write_dataframe(ctx.spark_session.createDataFrame(responses))
온프레미스 시스템에서는 연결을 신뢰할 수 있도록 소스에 추가해야 하는 자체 서명된 서버 인증서를 사용하는 경우가 있습니다. 이러한 인증서는 일반적으로 외부 변환에서 제공되는 기본 제공 HTTPS 클라이언트에 자동으로 추가됩니다. 하지만 일부 Python 클라이언트는 REQUESTS_CA_BUNDLE 환경 변수에 의존할 수 있습니다. 이 경우 해당 변수를 재정의해야 합니다.
아래 예시는 SharePoint용 Python 클라이언트 ↗인 Office365-REST-Python-Client를 사용하여 온프레미스 SharePoint 소스에서 데이터를 읽기 위해 REQUESTS_CA_BUNDLE을 재정의하는 방법을 보여줍니다. 이는 해당 클라이언트를 사용하기 위한 필수 단계입니다.
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 43 44 45 46from pyspark.sql import DataFrame from transforms.api import Output, transform, lightweight from transforms.external.systems import external_systems, Source import pandas as pd import polars as pl import tempfile import os from office365.sharepoint.client_context import ClientContext @lightweight @external_systems( sharepoint_rest=Source("<source_rid>") ) @transform( output=Output("<dataset_rid>"), ) def compute(ctx, output, sharepoint_rest) -> DataFrame: # 1. Add custom certificates to default certificates environment variable cert_file = tempfile.NamedTemporaryFile(delete=False) with open(cert_file.name, 'w') as tmp_f: with open(os.environ.get("REQUESTS_CA_BUNDLE"), 'r') as ca_f: with open(sharepoint_rest.server_certificates_bundle_path, 'r') as source_ca_f: tmp_f.write(ca_f.read()) tmp_f.write(source_ca_f.read()) cert_file.close() os.environ["REQUESTS_CA_BUNDLE"] = cert_file.name # the REQUESTS_CA_BUNDLE now contains the source self-signed certificate # 2. Connect to Sharepoint using client certificate authentication. client = ClientContext("<sharepoint_url>").with_client_certificate( tenant="<tenant_id>", client_id="<client_id>", thumbprint="<thumbprint>", private_key=sharepoint_rest.get_secret("additionalSecretPrivateKey"), passphrase=sharepoint_rest.get_secret("additionalSecretPrivateKeyPassphrase"), # optional, if the private key is password encrypted ) # 3. Grab web title and return it as DataFrame current_web = client.web client.load(current_web) client.execute_query() data = [{"web_title": current_web.properties['Title']}] output.write_table(pl.from_pandas(pd.DataFrame.from_records(data)))
Foundry 플랫폼을 기반으로 애플리케이션을 빌드하려는 경우 Foundry REST API를 사용하세요. Foundry API는 인증에 OAuth 2.0 프로토콜을 사용하고, 주로 JSON 요청 및 응답을 사용하며, 온톨로지 및 모델링 리소스를 지원합니다.