概要

HTTP テストでは、アプリケーションの API エンドポイントに HTTP リクエストを送信し、応答時間、ステータスコード、ヘッダー、本文のコンテンツなど、定義された条件と応答を確認することができます。

HTTP テストは、ネットワークの外部または内部のどちらからテストを実行するかの好みによって、管理ロケーションとプライベートロケーションの両方から実行できます。HTTP テストは、スケジュール、オンデマンド、または CI/CD パイプライン内で直接実行できます。

構成

テストを作成するには次の方法があります。

  • テンプレートからテストを作成する:

    1. あらかじめ設定されているテンプレートのいずれかにカーソルを合わせて、[View Template] (テンプレートを表示) をクリックします。すると、「Test Details」(テストの詳細)、「Request Details」(リクエストの詳細)、「Assertions」(アサーション)、「Alert Conditions」(アラートの条件)、「Monitor Settings」(モニターの設定) など、あらかじめ設定された構成情報が表示されるサイドパネルが開きます。

    2. [+Create Test] (テストを作成) をクリックして [Define Request] (リクエストの定義) ページを開きます。このページで、あらかじめ設定された構成オプションを確認および編集できます。表示されるフィールドは、テストを一から作成する際に利用可能なフィールドと同じです。

    3. [Save Details] (詳細を保存) をクリックして、API テストを送信します。

  • テストを一から作成する:

    1. テストを一から作成するには、[+ Start from scratch] (一から作成する) テンプレートをクリックし、HTTP リクエストタイプを選択して、クエリする URL を指定します。 利用可能なメソッドは、GETPOSTPATCHPUTHEADDELETE、および OPTIONS です。http および https の両方の URL がサポートされています。

      その他のオプションについては、高度なオプションを参照してください。
    2. Name your HTTP test.

    3. Add Environment Tags as well as any other tag to your HTTP test. You can then use these tags to filter through your Synthetic tests on the Synthetic Monitoring & Continuous Testing page.

    4. Click Send to try out the request configuration. A response preview is displayed on the right side of your screen.

    HTTP リクエストを定義する
    1. Click Create Test to submit your API test.

スニペット

When setting up a new Synthetic Monitoring API test, use snippets to automatically fill in basic auth, performance, and regions, rather than selecting these options manually. The following snippets are available:

  • Basic Auth: Automatically test your APIs using pre-populated basic auth headers, JavaScript, bearer token, and API/app key auth variables.

  • Performance: Automatically configure a test with the shortest frequency (one minute), perform a gRPC health check, and test for overall response time latency with a breakdown of network timing.

  • Regions: Automatically test your API endpoint against a location in each of the three primary geographic regions (AMER, APAC and EMEA).

    Screenshot of the left hand side of an API test creation, showing the snippets example

高度なオプション

  • HTTP version (HTTP バージョン): HTTP/1.1 onlyHTTP/2 only、または HTTP/2 fallback to HTTP/1.1を選択します。
  • Follow redirects (リダイレクトをフォローする): リクエストを実行するときに HTTP テストで最大 10 個のリダイレクトをフォローするように選択します。
  • Ignore server certificate error (サーバー証明書のエラーを無視する): SSL 証明書の検証時にエラーが発生した場合でも、HTTP テストが接続を続行するように選択します。
  • Timeout (タイムアウト): テストがタイムアウトするまでの時間を秒単位で指定します。
  • Request headers (リクエストヘッダー): HTTP リクエストに追加するヘッダーを定義します。デフォルトのヘッダー (たとえば、user-agent ヘッダー) をオーバーライドすることもできます。
  • Cookies (クッキー): HTTP リクエストに追加するクッキーを定義します。複数のクッキーを設定するには次の形式を使用します: <COOKIE_NAME1>=<COOKIE_VALUE1>; <COOKIE_NAME2>=<COOKIE_VALUE2>
  • Client Certificate (クライアント証明書): クライアント証明書 (.crt) と関連する秘密キー (.key) を PEM 形式でアップロードして、mTLS を介して認証します。openssl ライブラリを使用して証明書を変換することができます。たとえば、PKCS12 証明書を PEM 形式の秘密キーと証明書に変換できます。

    openssl pkcs12 -in <CERT>.p12 -out <CERT_KEY>.key -nodes -nocerts
    openssl pkcs12 -in <CERT>.p12 -out <CERT>.cert -nokeys
    
  • HTTP Basic Auth (HTTP 基本認証): HTTP 基本認証の資格情報を追加します。

  • Digest Auth (ダイジェスト認証): ダイジェスト認証の資格情報を追加します。

  • NTLM: NTLM 認証の資格情報を追加します。NTLMv2 と NTLMv1 の両方に対応しています。

  • AWS Signature v4 (AWS 署名バージョン 4): Access Key ID と Secret Access Key を入力します。Datadog は、リクエストの署名を生成します。このオプションは、SigV4 の基本的な実装を使用します。Amazon S3 などの特定の署名は、そのままではサポートされていません。 Amazon S3 バケットへの “Single Chunk” 転送リクエストの場合、リクエストの本文を sha256 エンコードした値を含む x-amz-content-sha256 ヘッダーを追加します (本文が空の場合は x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 を使用します)。

  • OAuth 2.0: クライアント資格情報またはリソース所有者のパスワードのどちらを付与するかを選択し、アクセストークンの URL を入力します。選択内容に応じて、クライアント ID とシークレット、またはユーザー名とパスワードを入力します。ドロップダウンメニューから、API トークンを基本認証ヘッダーとして送信するか、クライアント資格情報を本文で送信するかを選択します。オプションで、オーディエンス、リソース、スコープなどの追加情報を提供できます ([Resource Owner Password] (リソース所有者のパスワード) を選択した場合は、クライアント ID とシークレットも提供できます)。

  • Encode parameters (パラメーターのエンコード): エンコードが必要なクエリパラメーターの名前と値を追加します。
  • Body type (本文のタイプ): HTTP リクエストに追加するリクエスト本文のタイプ (application/jsonapplication/octet-streamapplication/x-www-form-urlencodedmultipart/form-datatext/htmltext/plaintext/xmlGraphQL、または None) を選択します。
  • Request body (リクエスト本文): HTTP リクエスト本文の内容を追加します。
    • application/jsonapplication/x-www-form-urlencodedtext/htmltext/plaintext/xmlGraphQL では、リクエスト本文のサイズが最大 50 キロバイトに制限されます。
    • application/octet-stream では、リクエスト本文は 3 メガバイトのファイル 1 つに制限されます。
    • multipart/form-data では、リクエスト本文はそれぞれ 3 メガバイトのファイル 3 つに制限されます。
  • Proxy URL (プロキシ URL): HTTP リクエストが通過する必要があるプロキシの URL を指定します (http://<YOUR_USER>:<YOUR_PWD>@<YOUR_IP>:<YOUR_PORT>)。
  • Proxy header (プロキシヘッダー): プロキシへの HTTP リクエストに含めるヘッダーを追加します。
  • Do not save response body (応答本文を保存しない): このオプションを選択すると、実行時に応答本文が保存されず、失敗した JavaScript アサーションのエラーメッセージが切り捨てられます。これは、テスト結果に機密データが表示されないようにするために役立ちますが、障害のトラブルシューティングが困難になる可能性があります。セキュリティに関する完全な推奨事項については、Synthetic Monitoring のデータセキュリティを参照してください。

JavaScript を使用して HTTP API テスト用の変数を定義します。

JavaScript を使用して HTTP API テストを定義する
Windows プライベートロケーションでは API テストの JavaScript 機能はサポートされていません。

アサーションを定義する

アサーションは、期待されるテスト結果を定義します。[Test URL] (URL をテスト) をクリックすると、response timestatus codeheadercontent-typeの基本的なアサーションが、取得された応答に基づいて追加されます。テストで監視するには、少なくとも 1 つのアサーションを定義する必要があります。

アサーションのヘッダー、本文、JavaScript の各セクションは、アサーションを定義するためだけに使用されます。追加の HTTP リクエストを行うためには使用できません。
タイプ演算子値の型
bodycontains, does not contain, is, is not,
matches, does not match,
jsonpath, xpath
String
Regex
headercontains, does not contain, is, is not,
matches, does not match
String
Regex
response timeis less thanInteger (ms)
status codeis, is not,
matches, does not match
Integer
Regex

HTTP テストでは、brdeflategzipidentitycontent-encoding ヘッダーを使用して本文を解凍することが可能です。

[New Assertion] (新規アサーション) をクリックするか、応答プレビューを直接クリックすることで、API テストごとに最大 20 個のアサーションを作成できます。

HTTP テストが成功または失敗するためのアサーションを定義する

アサーションで OR ロジックを実行するには、matches regex コンパレーターを使用して、(200|302) のように複数の期待値を持つ正規表現を定義します。たとえば、サーバーが 200 あるいは 302 というステータスコードで応答したときに HTTP テストを成功させたい場合、ステータスコードが 200 あるいは 302 であれば status code アサーションが成功します。matches regex コンパレーターを使用して bodyheader のアサーションに OR ロジックを追加することもできます。

テストに応答本文に関するアサーションが含まれていない場合、本文のペイロードはドロップし、Synthetics Worker で設定されたタイムアウト制限内でリクエストに関連する応答時間が返されます。

応答本文が返されるのは、その内容に関するアサーションが追加されていて、それらのアサーションが失敗した場合だけです。テストに応答本文に関するアサーションが含まれていて、テストが成功した場合は、本文のペイロードはドロップし、応答本文の最初の 50 文字のスニペットのみが表示されます。

テストに応答本文に関するアサーションが含まれていて、タイムアウトの制限に達した場合は、Assertions on the body/response cannot be run beyond this limit というエラーが表示されます。

標準の応答アサーションが検証ニーズを満たさない場合は、JavaScript アサーションを使用します。Synthetic Monitoring は、柔軟なアサーションスタイルのために dd.expect()dd.should、および dd.assert() を提供する Chai アサーションライブラリを使用します。

JSON 応答を扱う場合は、プロパティにアクセスする前に JSON.parse(dd.response.body) を使用して応答本文を解析します。これは、JSON データを検証する際にすべてのアサーションメソッド (dd.assert()dd.expect()、および dd.should) で必要です。

HTTP API テストのための JavaScript アサーション
  • Windows プライベートロケーションでは API テストの JavaScript 機能はサポートされていません。
  • 失敗した JavaScript アサーションのエラーメッセージに機密データが含まれる可能性がある場合は、[Advanced Options] (高度なオプション) > [Privacy] (プライバシー) で、[Do not save response body] (応答本文を保存しない) を有効にします。これにより、アサーションのエラーメッセージが切り捨てられます。

dd.assert() の使用

従来のアサーション構文には dd.assert() を使用します。

たとえば、status.code フィールドの許容値をアサートするには、次のように指定します。

const response = JSON.parse(dd.response.body);
// Assert that the status code is 200, 210, 320, or 330
dd.assert.include([200, 210, 320, 330], response.status.code);

応答例

{
  "status": {
    "code": 200,
    "message": "Success"
  }
}

このアサーションの処理内容

  • JSON 応答本文を解析する
  • status.code が許容値の配列 (200、210、320、または 330) に含まれていることを確認する

このテストは成功します。status.code200 で、許容値の配列に含まれているからです。

assert.include() の詳細については、Chai assert.include() のドキュメントを参照してください。

dd.expect() の使用

ネストされたプロパティの検証を伴うアサーションには dd.expect() を使用します。

たとえば、status.indicator フィールドの予測値をアサートするには、次のように指定します。

const response = JSON.parse(dd.response.body);
const regex = /^(major|critical|minor|none)$/;

dd.expect(response)
  .to.have.nested.property('status.indicator')
  .that.matches(regex);

応答例

{
  "status": {
    "indicator": "none"
  }
}

このアサーションの処理内容

  • JSON 応答本文を解析する
  • ネストされたプロパティ status.indicator が存在することを検証する
  • 値が正規表現パターンと一致することを確認する (majorcriticalminornone のいずれか)

正規表現が /^(major|critical|minor|none)$/ の場合、このテストは成功します。status.indicator"none" で、このパターンと一致するからです。

正規表現が /^(major|critical|minor)$/ の場合、このテストは失敗します。"none" が許容値に含まれていないからです。

expect() の詳細については、Chai expect() のドキュメントを参照してください。

dd.should の使用

自然言語構文でアサーションを書くには dd.should を使用します。

たとえば、status.indicator フィールドが存在し、特定の値と等しいことをアサートするには、次のように指定します。

const response = JSON.parse(dd.response.body);
response.status.should.exist();
const indicator = response.status.indicator;
indicator.should.equal('none');

応答例

{
  "status": {
    "indicator": "none"
  }
}

このアサーションの処理内容

  • JSON 応答本文を解析する
  • status プロパティが存在することを確認する
  • indicator 値を変数に抽出する
  • status.indicator"none" と等しいことを確認する

このテストは成功します。status が存在し、status.indicator"none" であるからです。

should() の詳細については、Chai should() のドキュメントを参照してください。

ロケーションを選択する

HTTP テストを実行するロケーションを選択します。HTTP テストは、ネットワークの外部または内部のどちらからテストを実行するかの好みによって、管理ロケーションとプライベートロケーションの両方から実行できます。

Datadog’s out-of-the-box managed locations allow you to test public-facing websites and endpoints from regions where your customers are located.

AWS:

AmericasAsia PacificEMEA
Canada CentralHong KongBahrain
Northern CaliforniaJakartaCape Town
Northern VirginiaMumbaiFrankfurt
OhioOsakaIreland
OregonSeoulLondon
São PauloSingaporeMilan
SydneyParis
TokyoStockholm

GCP:

AmericasAsia PacificEMEA
DallasTokyoFrankfurt
Los Angeles
Oregon
Virginia

Azure:

RegionLocation
AmericasVirginia

The Datadog for Government site (US1-FED) uses the following managed location:

RegionLocation
AmericasUS-West

テストの頻度を指定する

HTTP テストは次の頻度で実行できます。

  • On a schedule (スケジュール): 最も重要なエンドポイントにユーザーが常にアクセスできるようにします。Datadog で HTTP テストを実行する頻度を選択します。
  • Within your CI/CD pipelines (CI/CD パイプライン内): 欠陥のあるコードがカスタマーエクスペリエンスに影響を与える可能性があることを恐れずに出荷を開始します。 [* On-demand] (オンデマンド): チームにとって最も意味のあるときにいつでもテストを実行します。

Define alert conditions

Set alert conditions to determine the circumstances under which you want a test to fail and trigger an alert.

Alerting rule

When you set the alert conditions to: An alert is triggered if any assertion fails for X minutes from any n of N locations, an alert is triggered only if these two conditions are true:

  • At least one location was in failure (at least one assertion failed) during the last X minutes;
  • At one moment during the last X minutes, at least n locations were in failure.

Fast retry

Your test can trigger retries X times after Y ms in case of a failed test result. Customize the retry interval to suit your alerting sensibility.

Location uptime is computed on a per-evaluation basis (whether the last test result before evaluation was up or down). The total uptime is computed based on the configured alert conditions. Notifications sent are based on the total uptime.

For more information on how Synthetic Monitoring notifications evaluate test results and trigger alerts, see Understanding Synthetic Monitor Alerting.

Configure the test monitor

A notification is sent by your test based on the alerting conditions previously defined. Use this section to define how and what to message your team.

  1. Similar to how you configure monitors, select users and/or services that should receive notifications either by adding an @notification to the message or by searching for team members and connected integrations with the dropdown menu.

  2. Enter the notification message for your test or use pre-filled monitor messages. This field allows standard Markdown formatting and supports the following conditional variables:

Conditional VariableDescription
{{#is_alert}}Show when the test alerts.
{{^is_alert}}Show unless the test alerts.
{{#is_recovery}}Show when the test recovers from alert.
{{^is_recovery}}Show unless the test recovers from alert.
{{#is_renotify}}Show when the monitor renotifies.
{{^is_renotify}}Show unless the monitor renotifies.
{{#is_priority}}Show when the monitor matches priority (P1 to P5).
{{^is_priority}}Show unless the monitor matches priority (P1 to P5).

Notification messages include the message defined in this section and information about the failing locations. Pre-filled monitor messages are included in the message body section:

Synthetic Monitoring monitor section for API tests, highlighting the pre-filled monitor messages
  1. Specify how often you want your test to re-send the notification message in case of test failure. To prevent renotification on failing tests, check the option Stop re-notifying on X occurrences.

  2. Click Save & Start Recording to save your test configuration and monitor.

For more information, see Synthetic Monitoring notifications.

Downtimes

To pause test execution during planned maintenance windows, select an existing Scheduled downtime in the Downtimes section. The test automatically pauses during the downtime’s scheduled time slots.

Note: You cannot create a new downtime from the test creation form. To create one, navigate to Settings > Downtimes.

ワンクリック

API テストの作成は、カタログと既存の API テストからエンドポイントを提案し、関連するオプションをテストフォームに自動入力します。 既存の Datadog データソース (APM トレース、カタログで検出されたエンドポイント、ユーザーが作成した類似の Synthetic テストなど) を活用します。

API テストの [URL] に入力を開始すると、エンドポイントの提案や Synthetic Monitoring の類似テストを取得できます。

既存の API テストの GET 検索を表示している HTTP API テスト

次に、提案を選択してテスト構成 (リクエストオプションとヘッダー、認証、変数) を自動入力します。

選択

Create local variables

To create a local variable, click + All steps > Variables. You can select one of the following available builtins to add to your variable string:

{{ numeric(n) }}
Generates a numeric string with n digits.
{{ alphabetic(n) }}
Generates an alphabetic string with n letters.
{{ alphanumeric(n) }}
Generates an alphanumeric string with n characters.
{{ date(n unit, format) }}
Generates a date in one of Datadog’s accepted formats with a value corresponding to the UTC date the test is initiated at + or - n units.
{{ timestamp(n, unit) }}
Generates a timestamp in one of Datadog’s accepted units with a value corresponding to the UTC timestamp the test is initiated at +/- n units.
{{ uuid }}
Generates a version 4 universally unique identifier (UUID).
{{ public-id }}
Injects the Public ID of your test.
{{ result-id }}
Injects the Result ID of your test run.

To obfuscate local variable values in test results, select Hide and obfuscate variable value. After you have defined the variable string, click Add Variable.

Apply filters to variable values

When you reference a variable, you can transform its resolved value by appending a filter with a pipe (|). Use the syntax {{ VARIABLE_NAME | filter }} anywhere a variable is accepted, such as the URL, request body, headers, and assertions. The following filters are available:

{{ VARIABLE_NAME | urlEncode }}
URL-encodes the variable’s value. For example, hello world becomes hello%20world.
{{ VARIABLE_NAME | urlDecode }}
URL-decodes the variable’s value. For example, hello%20world becomes hello world.
{{ VARIABLE_NAME | base64Encode }}
Base64-encodes the variable’s value. For example, hello becomes aGVsbG8=.
{{ VARIABLE_NAME | base64Decode }}
Base64-decodes the variable’s value. For example, aGVsbG8= becomes hello.

Filters apply to both local and global variables. You can apply one filter per reference, and filter names are case-sensitive.

変数を使用する

[Settings] (設定) ページで定義されたグローバル変数を、HTTP テストの URL、高度なオプション、アサーションで使用できます。

変数のリストを表示するには、目的のフィールドに {{ と入力します。

テストの失敗

テストが 1 つ以上のアサーションを満たさない場合、またはリクエストが時期尚早に失敗した場合、テストは FAILED と見なされます。場合によっては、エンドポイントに対してアサーションをテストすることなくテストが実際に失敗することがあります。

HTTP および SSL のエラーコードの完全なリストについては、API テストのエラーを参照してください。

権限

デフォルトでは、Datadog 管理者および Datadog 標準のロールを持つユーザーのみが、Synthetic HTTP テストを作成、編集、削除できます。Synthetic HTTP テストの作成、編集、削除のアクセスを取得するには、ユーザーをこれら 2 つのデフォルトのロールのいずれかにアップグレードします。

カスタムロール機能を使用している場合は、synthetics_read および synthetics_write の権限を含むカスタムロールにユーザーを追加します。

アクセス制限

Use granular access control to limit who has access to your test based on roles, teams, or individual users:

  1. Open the permissions section of the form.
  2. Click Edit Access.
Set permissions for your test from Private Locations configuration form
  1. Click Restrict Access.
  2. Select teams, roles, or users.
  3. Click Add.
  4. Select the level of access you want to associate with each of them.
  5. Click Done.
You can view results from a Private Location even without Viewer access to that Private Location.
Access levelView test configurationEdit test configurationView test resultsRun test
No access
ViewerYesYes
EditorYesYesYesYes

参考資料