HTTP コールの実行

HTTP コールを実行するポリシープロジェクトの例は、 「Simple OAuth 2.0 Validation Policy Example (簡単な OAuth 2.0 検証ポリシーの例)」​を参照してください。

外部サービスとやりとりするために、ポリシーで HTTP コールを使用できます。HTTP コールは、要求検索条件または応答検索条件からのみ実行できます。

HTTP サービスの定義

HTTP 要求を実行するには、スキーマ定義のパラメーターとしてサービスを定義します。パラメーターの定義の詳細については、policy-pdk-create-schema-definition.adocを参照してください。

外部サービスのスキーマを定義するコードスニペットの例を示します。

properties:
      externalService:
          type: string
          format: service
      endpointPath:
          type: string

ポリシーの Rust ソースコードでは、​Config​ 構造体で定義された外部サービスにアクセスできます。要求を実行するには、ポリシーで HTTP クライアントをコールします。例:

let response = client
    .request(&config.external_service)
    .path(&config.endpoint_path)
    .headers(vec![("Content-Type", "application/json")])
    .body(r#"{"key": "value"}"#.as_bytes())
    .put().await?;

要求の有効化するための HTTP クライアントパラメーターの挿入

HTTP コールを実行するには、​[entrypoint]​ 関数またはラッパー関数に ​HTTPClient​ を挿入します。

  • 要求検索条件と応答検索条件で要求を有効にするには、クライアントパラメーターを ​#[entrypoint]​ 関数に挿入します。

    #[entrypoint]
    async fn configure(launcher: Launcher, Configuration(bytes): Configuration, client: HttpClient) -> Result<()> {
        let config: Config = serde_json::from_slice(&bytes).unwrap();
    
        // Both request and the response handlers will use the client
        let filter = on_request(|request_state| request_filter(request_state, &config, &client))
            .on_response(|response_state, request_data| {
                response_filter(response_state, request_data, &config, &client)
            });
    
        launcher.launch(filter).await?;
        Ok(())
    }
  • 要求または応答でのみ要求を有効にするには、クライアントパラメーターを ​on_request​ または ​on_response​ ラッパー関数に挿入します。

    // Handler with the logic for incoming requests
    ​​async fn request_filter(state: RequestState, conf: &Config, client: HttpClient) {
     ...
    }
    
    #[entrypoint]
    async fn configure(launcher: Launcher, Configuration(bytes): Configuration) -> Result<()> {
        let config: Config = serde_json::from_slice(&bytes).unwrap();
    
        // For incoming request events, using the on_request wrapper, inject the client and pass it to the request_filter handler
        launcher
            .launch(on_request(|request, client| {
                request_filter(request, &config, client)
            }))
            .await?;
        Ok(())
    }