온톨로지Functions언어에 구애받지 않는 기능Function에서 API 호출

본 번역은 검증되지 않았습니다. AIP를 통해 영문원문으로부터 번역되었습니다.

Function에서 API 호출

TypeScript v1, TypeScript v2 및 Python Functions에서 외부 소스로 API 호출을 수행할 수 있습니다. 그러나 이를 위해 추가 설정이 필요합니다. 이 설정 및 외부 소스 사용 방법은 아래에 자세히 설명되어 있습니다.

Source aliases

TypeScript v2 및 Python Functions의 경우, source aliases를 통해 소스를 참조하는 것을 권장합니다. Source alias는 특정 소스를 대신하여 소스 식별자로 사용할 수 있는 이동 가능한 이름 참조입니다. Function이 Marketplace product를 통해 배포될 때, 환경별로 alias를 다른 소스로 재매핑할 수 있어 Function 코드의 이동성을 유지할 수 있습니다. TypeScript v1 Functions는 생성된 소스 심볼을 사용하며 alias를 지원하지 않습니다.

외부 API에 대한 액세스 구성

기본적으로 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에서 외부 소스 사용

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 13 import { 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 15 import { 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 11 from 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!
1 const { url } = MySource.getHttpsConnection();
Copied!
1 const { url } = getHttpsConnection(source);
Copied!
1 url = get_source("mySourceAlias").get_https_connection().url

또한, 다음 구문을 사용하여 소스에 저장된 추가 비밀 또는 자격 증명에 액세스할 수 있습니다:

Copied!
1 const secret = MySource.getSecret("MySecret");
Copied!
1 const secret = source.secrets["MySecret"];
Copied!
1 secret = get_source("mySourceAlias").get_secret("MySecret")

미리 구성된 클라이언트 사용

REST API를 제공하는 소스의 경우, 소스 오브젝트를 통해 클라이언트를 가져올 수 있습니다. 이 클라이언트는 소스에 지정된 서버 및 클라이언트 인증서로 미리 구성됩니다. 또한, Functions가 실행되는 환경에서 외부로 나가는 연결을 허용하는 추가 프록시 구성이 포함됩니다. 가능한 경우 항상 이 클라이언트를 사용하여 모든 환경에서 소스에 연결할 수 있도록 보장해야 합니다.

Copied!
1 const fetch = MySource.fetch;
Copied!
1 const fetch = await getFetch(source);
Copied!
1 client = source.get_https_connection().get_client()

대안으로, 자체 클라이언트나 외부 요청을 수행하는 타사 라이브러리를 사용할 수 있으며, 소스 오브젝트를 사용하여 속성과 자격 증명을 검색할 수 있습니다.

TypeScript v2 Functions는 타사 라이브러리와 함께 사용할 수 있도록 사용자 정의 HTTP 에이전트를 수락하는 추가 통합 지점을 제공합니다.

아래 예제는 이 에이전트를 검색하고 axios ↗와 함께 사용하는 방법을 보여줍니다.

Copied!
1 2 3 4 5 6 7 8 9 import { 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 또는 기타 비밀이 아닌 속성에 액세스할 수 없습니다.

OAuth 2.0을 사용한 외부 애플리케이션 사용

외부 API가 OAuth 2.0 인증을 요구하는 경우, Control Panel에서 outbound application을 구성하고 이를 REST API 소스의 인증 방법으로 사용할 수 있습니다. Function이 실행되면, 소스는 호출 사용자 OAuth 액세스 토큰을 세션 자격 증명으로 노출합니다. 그런 다음 Function은 이 토큰을 사용하여 사용자를 대신하여 외부 API를 호출할 수 있습니다.

이 패턴은 Python 및 TypeScript v2 Functions에서 지원됩니다. 아래의 소스의 미리 구성된 클라이언트 사용 섹션에서 코드 예제를 확인하세요.

제한 사항

  • TypeScript v1: TypeScript v1 Functions는 소스에서 OAuth 토큰을 직접 검색할 수 없습니다. TypeScript v1 Function에서 OAuth 2.0 API를 인증하려면, outbound application으로 구성된 REST API 소스에서 호출을 webhook으로 래핑해야 합니다. 직접 토큰 액세스를 위해 TypeScript v2로 마이그레이션을 고려하세요.
  • Deployed mode: Function이 deployed mode에서 실행 중일 때 OAuth 토큰 갱신이 불가능합니다. 호출 사용자의 액세스 토큰이 실행 중 만료되면 Function은 이를 자동으로 갱신할 수 없습니다. OAuth 기반 outbound application을 사용하려면 Function을 serverless mode에서 실행하세요.
  • Workshop에서의 직접 Function 사용: Workshop 모듈에서 직접 사용되는 Functions(예: function-backed variables 또는 위젯 콘텐츠를 채우는 Functions)는 OAuth 2.0 대화형 인증 프롬프트를 트리거할 수 없습니다. 사용자가 아직 outbound application을 인증하지 않은 경우, Function은 프롬프트를 표시하는 대신 실패합니다. Workshop에서 OAuth 기반 Function을 사용하려면 function-backed action으로 래핑하세요. 또는, Function이 Workshop에서 직접 호출되기 전에 다른 대화형 인터페이스(예: 동일한 outbound application에 대한 function-backed action)를 통해 사용자가 인증 흐름을 완료하도록 하세요.

소스의 미리 구성된 클라이언트 사용

가장 간단한 방법은 소스에서 제공하는 HTTP 클라이언트를 사용하는 것입니다. Authorization 헤더는 자동으로 삽입됩니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 from 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 15 import { 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 클라이언트와 수동 토큰 삽입 사용

소스에서 제공하는 클라이언트 대신 자체 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 24 import 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 23 import { 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 기반 Functions를 액션에서 사용

일반적인 패턴은 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 22 from 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 30 import { 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을 확인하세요.

HTTP 407: Proxy authentication required

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").