TypeScript v1, TypeScript v2 및 Python Functions에서 외부 소스로 API 호출을 수행할 수 있습니다. 그러나 이를 위해 추가 설정이 필요합니다. 이 설정 및 외부 소스 사용 방법은 아래에 자세히 설명되어 있습니다.
TypeScript v2 및 Python Functions의 경우, source aliases를 통해 소스를 참조하는 것을 권장합니다. Source alias는 특정 소스를 대신하여 소스 식별자로 사용할 수 있는 이동 가능한 이름 참조입니다. Function이 Marketplace product를 통해 배포될 때, 환경별로 alias를 다른 소스로 재매핑할 수 있어 Function 코드의 이동성을 유지할 수 있습니다. TypeScript v1 Functions는 생성된 소스 심볼을 사용하며 alias를 지원하지 않습니다.
기본적으로 Functions는 외부 API 호출이 허용되지 않습니다. Function에서 외부 시스템 호출을 활성화하려면 Data Connection에서 소스를 구성하여 Foundry가 외부 시스템과 연결할 수 있도록 해야 합니다.
Functions가 소스의 외부 시스템에 안전하게 연결하려면, 소스가 exports 활성화를 구성하고 소스를 Code Repositories로 가져오기를 허용해야 합니다. 이 두 가지는 Data Connection에서 소스를 탐색하고 Connection settings 섹션을 열어 구성할 수 있습니다.
TypeScript v1 Functions의 경우, 소스의 API 이름(Connection settings의 Code import configuration 탭에서 구성됨)이 코드에서 참조하는 식별자입니다.
소스에서 인증서 체인을 완전히 구성했는지 확인하세요.
Webhook과 Function 런타임 환경은 동일하지 않습니다.
때로는 Webhook이 올바르게 작동하지만 Function에서의 API 호출이 UNABLE_TO_GET_ISSUER_CERT 오류를 발생시킬 수 있습니다.
소스 터미널에서 openssl 명령을 사용하여 인증서를 검증하는 방법에 대한 문서를 확인하세요.
Function에서 API 호출을 수행하려면 먼저 resource imports sidebar를 사용하여 Functions repository에 소스를 가져와야 합니다. TypeScript v2 및 Python Functions의 경우, source alias 생성을 권장하며, alias 키를 소스 식별자로 사용합니다. TypeScript v1 Functions는 가져온 소스를 직접 참조합니다. 그런 다음 Function이 소스를 사용한다고 선언해야 하며, 아래 예제에서 이를 확인할 수 있습니다.
아래에 예제가 나와 있습니다:
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13import { ExternalSystems } from "@foundry/functions-api"; import { MySource } from "@foundry/external-systems/sources"; export class MyExternalFunctions { @ExternalSystems({ sources: [MySource] }) @Function() public async myExternalFunction(): Promise<string> { const { url } = MySource.getHttpsConnection(); const response = await MySource.fetch(url); return response.text(); } }
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15import { getSource, getHttpsConnection, getFetch } from "@palantir/functions-sources"; export const config = { sources: ["mySourceAlias"] } async function MyExternalFunction(): Promise<string> { const source = await getSource("mySourceAlias"); const { url } = getHttpsConnection(source); const fetch = await getFetch(source); const response = await fetch(url); return response.text(); }
Copied!1 2 3 4 5 6 7 8 9 10 11from functions.api import function from functions.sources import get_source @function(sources=["mySourceAlias"]) def my_external_function() -> str: source = get_source("mySourceAlias") url = source.get_https_connection().url client = source.get_https_connection().get_client() response = client.get(url) return response.text
Function을 live preview에서 테스트하고, 게시된 후 외부 호출에 사용할 수 있습니다.
서버리스 실행 또는 live preview에서는 타사 클라이언트가 아직 지원되지 않습니다. 모든 환경에서 API 호출이 올바르게 작동하도록 하려면, 요청을 올바르게 구성하기 위해 관련 라이브러리 메서드를 사용해야 합니다. 외부 소스 또는 내부 Foundry URL로의 직접 API 호출은 모든 환경에서 작동이 보장되지 않습니다.
각 Function 유형의 관련 라이브러리를 통해 제공되는 소스 속성에 액세스할 수 있습니다.
아래 예제는 위 예제에서 소스의 기본 URL을 얻는 방법을 보여줍니다.
Copied!1const { url } = MySource.getHttpsConnection();
Copied!1const { url } = getHttpsConnection(source);
Copied!1url = get_source("mySourceAlias").get_https_connection().url
또한, 다음 구문을 사용하여 소스에 저장된 추가 비밀 또는 자격 증명에 액세스할 수 있습니다:
Copied!1const secret = MySource.getSecret("MySecret");
Copied!1const secret = source.secrets["MySecret"];
Copied!1secret = get_source("mySourceAlias").get_secret("MySecret")
REST API를 제공하는 소스의 경우, 소스 오브젝트를 통해 클라이언트를 가져올 수 있습니다. 이 클라이언트는 소스에 지정된 서버 및 클라이언트 인증서로 미리 구성됩니다. 또한, Functions가 실행되는 환경에서 외부로 나가는 연결을 허용하는 추가 프록시 구성이 포함됩니다. 가능한 경우 항상 이 클라이언트를 사용하여 모든 환경에서 소스에 연결할 수 있도록 보장해야 합니다.
Copied!1const fetch = MySource.fetch;
Copied!1const fetch = await getFetch(source);
Copied!1client = source.get_https_connection().get_client()
대안으로, 자체 클라이언트나 외부 요청을 수행하는 타사 라이브러리를 사용할 수 있으며, 소스 오브젝트를 사용하여 속성과 자격 증명을 검색할 수 있습니다.
TypeScript v2 Functions는 타사 라이브러리와 함께 사용할 수 있도록 사용자 정의 HTTP 에이전트를 수락하는 추가 통합 지점을 제공합니다.
아래 예제는 이 에이전트를 검색하고 axios ↗와 함께 사용하는 방법을 보여줍니다.
Copied!1 2 3 4 5 6 7 8 9import { getHttpAgent, getHttpsConnection } from "@palantir/functions-sources"; import axios from 'axios'; const agent = await getHttpAgent(source); const { url } = getHttpsConnection(source); const response = await axios.get(url, { httpsAgent: agent, });
현재, 소스가 HTTPS 클라이언트를 제공하지 않는 한 자격 증명이 아닌 소스 속성에 액세스할 수 없습니다. 예를 들어, PostgreSQL 소스의 hostname 또는 기타 비밀이 아닌 속성에 액세스할 수 없습니다.
외부 API가 OAuth 2.0 인증을 요구하는 경우, Control Panel에서 outbound application을 구성하고 이를 REST API 소스의 인증 방법으로 사용할 수 있습니다. Function이 실행되면, 소스는 호출 사용자 OAuth 액세스 토큰을 세션 자격 증명으로 노출합니다. 그런 다음 Function은 이 토큰을 사용하여 사용자를 대신하여 외부 API를 호출할 수 있습니다.
이 패턴은 Python 및 TypeScript v2 Functions에서 지원됩니다. 아래의 소스의 미리 구성된 클라이언트 사용 섹션에서 코드 예제를 확인하세요.
가장 간단한 방법은 소스에서 제공하는 HTTP 클라이언트를 사용하는 것입니다. Authorization 헤더는 자동으로 삽입됩니다.
Copied!1 2 3 4 5 6 7 8 9 10 11from functions.api import function from functions.sources import get_source @function(sources=["myOAuthSourceAlias"]) def call_external_api() -> str: source = get_source("myOAuthSourceAlias") url = source.get_https_connection().url client = source.get_https_connection().get_client() response = client.get(url + "/api/v1/resource", timeout=10) return response.text
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15import { getSource, getHttpsConnection, getFetch } from "@palantir/functions-sources"; export const config = { sources: ["myOAuthSourceAlias"] }; export default async function callExternalApi(): Promise<string> { const source = await getSource("myOAuthSourceAlias"); const { url } = getHttpsConnection(source); const fetch = await getFetch(source); const response = await fetch(url + "/api/v1/resource"); return response.text(); }
소스에서 제공하는 클라이언트 대신 자체 HTTP 클라이언트를 사용해야 하는 경우, 세션 자격 증명에서 OAuth 토큰을 검색하고 Authorization 헤더를 수동으로 설정하세요.
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24import requests from functions.api import function from functions.sources import get_source from external_systems.sources import OauthCredentials, Refreshable, SourceCredentials @function(sources=["myOAuthSourceAlias"]) def call_external_api() -> str: source = get_source("myOAuthSourceAlias") url = source.get_https_connection().url refreshable_credentials: Refreshable[SourceCredentials] = source.get_session_credentials() session_credentials: SourceCredentials = refreshable_credentials.get() if not isinstance(session_credentials, OauthCredentials): raise ValueError("Expected OAuth credentials") access_token: str = session_credentials.access_token response = requests.get( url + "/api/v1/resource", headers={"Authorization": f"Bearer {access_token}"}, timeout=10, ) return response.text
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23import { getSource, getHttpsConnection } from "@palantir/functions-sources"; export const config = { sources: ["myOAuthSourceAlias"] }; export default async function callExternalApi(): Promise<string> { const source = await getSource("myOAuthSourceAlias"); const credentials = await source.sessionCredentials?.get(); if (!credentials || credentials.type !== "oauth") { throw new Error("Expected OAuth credentials"); } const accessToken: string = credentials.accessToken; const { url } = getHttpsConnection(source); const response = await fetch(url + "/api/v1/resource", { headers: { Authorization: `Bearer ${accessToken}` }, }); return response.text(); }
일반적인 패턴은 OAuth 기반 외부 API를 호출하고 결과를 온톨로지 편집에 전달하는 것입니다. 그런 다음 해당 Function을 function-backed action을 통해 노출할 수 있습니다. 사용자가 Workshop 또는 AIP Studio에서 액션을 실행하면, OAuth 토큰이 외부 API 호출에 사용되고, 생성된 오브젝트 편집은 사용자에게 귀속됩니다.
예를 들어, 아래 Function은 OAuth 토큰을 사용하여 타사 ID 서비스에서 호출 사용자의 프로필을 가져옵니다. 그런 다음 해당 정보를 사용하여 새 온톨로지 오브젝트를 생성합니다:
Copied!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22from functions.api import function, OntologyEdit from functions.sources import get_source from ontology_sdk import FoundryClient from ontology_sdk.ontology.objects import UserProfile @function(sources=["myOAuthSourceAlias"], edits=[UserProfile]) def link_user_profile() -> list[OntologyEdit]: source = get_source("myOAuthSourceAlias") url = source.get_https_connection().url client = source.get_https_connection().get_client() response = client.get(url + "/v1/me", timeout=10) response.raise_for_status() profile = response.json() ontology_edits = FoundryClient().ontology.edits() ontology_edits.objects.UserProfile.create( profile["id"], display_name=profile["display_name"], ) return ontology_edits.get_edits()
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 30import { getSource, getHttpsConnection, getFetch } from "@palantir/functions-sources"; import { UserProfile } from "@ontology/sdk"; import { Client } from "@osdk/client"; import { createEditBatch, Edits } from "@osdk/functions"; type OntologyEdit = Edits.Object<UserProfile>; export const config = { sources: ["myOAuthSourceAlias"], edits: [UserProfile], }; export default async function linkUserProfile(client: Client): Promise<OntologyEdit[]> { const source = await getSource("myOAuthSourceAlias"); const { url } = getHttpsConnection(source); const fetch = await getFetch(source); const response = await fetch(url + "/v1/me"); if (!response.ok) { throw new Error(`Failed to fetch profile: ${response.status}`); } const profile = await response.json(); const batch = createEditBatch<OntologyEdit>(client); batch.create(UserProfile, { userProfileId: profile.id, displayName: profile.display_name, }); return batch.getEdits(); }
OAuth 인증 오류(HTTP 401: Unauthorized, Credentials expired and no refresh handler provided, Resolved source credentials are not present on the Source 등)의 경우, Data Connection 문제 해결 출처의 OAuth 및 outbound applications을 확인하세요.
Function 네트워크 요청은 소스의 egress policies에 의해 커버되어야 합니다. 대상 호스트 이름이 허용된 정책과 일치하지 않으면 요청이 HTTP 407: Proxy Authentication Required를 반환할 수 있습니다.
Egress 정책이 올바르게 보이는 경우, 요청 URL이 어떻게 구성되는지 확인하세요. getHttpsConnection()에서 반환된 URL에는 후행 슬래시가 없으므로, 선행 /이 생략된 경로가 호스트 이름에 결합됩니다:
Copied!1 2"https://example.com" + "api/v1" → "https://example.comapi/v1"
결과 호스트 이름(example.comapi)은 어떤 egress 정책에도 포함되지 않으므로 요청이 거부됩니다. 경로 앞에 /를 추가하세요(예: url + "/api/v1").