### Pulumi CLI Setup Example Source: https://www.checklyhq.com/docs/pulumi-provider This snippet shows the command to verify the Pulumi CLI installation. Ensure the 'pulumi' command is available in your environment. ```text pulumi login pulumi stack init pulumi up ``` -------------------------------- ### Authentication Example with Setup Script Source: https://www.checklyhq.com/docs/api-checks/teardown-script-examples This example demonstrates how to handle authentication by fetching or signing session tokens within a setup script. It shows a typical folder structure for organizing authentication logic. ```text . |-- api-1.check.ts |-- setup.ts ``` -------------------------------- ### Install and Initialize Checkly CLI Source: https://www.checklyhq.com/docs/cli/command-line-reference Use this command to install the Checkly CLI and set up a new project. It guides you through the necessary steps for a working example. ```shellscript npx @checkly/cli init ``` -------------------------------- ### Basic Setup Script Example Source: https://www.checklyhq.com/docs/api-checks/setup-script-examples A simple JavaScript example demonstrating how to set environment variables and log messages during the setup phase of an API check. This is useful for preparing test conditions. ```javascript /** * @param {import('checkly/ கட்டமை').SetupContext} context */ exports.setup = async ({ env, log }) => { log.info('Setting up API check...'); env.set('API_KEY', 'your-api-key'); env.set('BASE_URL', 'https://api.example.com'); log.info('Setup complete.'); }; ``` -------------------------------- ### Basic Setup Script Example Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts This example demonstrates a basic setup script that constructs a request object with method, URL, and headers. It uses `__dirname` to join with a local file path. ```typescript import { setup } from '@checkly/cli/constructs'; setup({ request: { method: 'GET', url: 'https://api.acme.com/v1/products' } }); ``` -------------------------------- ### Basic Setup Script Example Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts This example demonstrates a basic setup script that logs a message and sets a request method and URL. It shows how to access and modify request details within the script. ```javascript console.log('Running setup script...'); request.method = 'GET'; request.url = 'https://api.acme.com/v1/products'; ``` -------------------------------- ### Authentication Example in Setup Script Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts Demonstrates how to use a setup script to fetch an authentication token and add it to the request headers. ```javascript async ({ request }) => { const response = await fetch('https://api.example.com/auth/token', { method: 'POST', body: JSON.stringify({ username: 'user', password: 'password' }), }); const data = await response.json(); request.headers.set('Authorization', `Bearer ${data.token}`); } ``` -------------------------------- ### TypeScript Setup Script Example Source: https://www.checklyhq.com/docs/api-checks/setup-script-examples A TypeScript example for a setup script, demonstrating type safety and modern JavaScript features. It sets an environment variable and logs information. ```typescript import { SetupContext } from 'checkly/ கட்டமை'; export const setup = async ({ env, log }: SetupContext): Promise => { log.info('Setting up API check with TypeScript...'); env.set('TEST_MODE', 'true'); log.info('TypeScript setup complete.'); }; ``` -------------------------------- ### Basic Setup Script Example Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts A simple setup script that logs a message before a check runs. This script is executed before the main API request. ```javascript async ({ page, request, $ }) => { console.log('Setting up the test environment...'); // Add your setup logic here, e.g., creating test data } ``` -------------------------------- ### Error Handling in Setup Script Source: https://www.checklyhq.com/docs/api-checks/teardown-script-examples This example demonstrates how to implement error handling within a setup script using a try-catch block. If an error occurs during setup, it throws a new Error with a descriptive message. ```javascript async ({ request }) => { try { // ... setup logic ... request.headers.set('X-Custom-Header', 'my-custom-value'); } catch (error) { throw new Error(`Setup script failed: ${error.message}`); } } ``` -------------------------------- ### Basic Webhook Setup Source: https://www.checklyhq.com/docs/alerting-and-retries/webhooks This example demonstrates a basic setup for sending a webhook request. It uses the 'axios' library to make a POST request to a specified URL. ```javascript const axios = require('axios') ;(async () => { const response = await axios.post('YOUR_WEBHOOK_URL', { event: 'test-event', data: { message: 'Hello from Checkly!' } }) console.log('Webhook response:', response.data) })() ``` -------------------------------- ### Ping Monitor with Source and Start Time Source: https://www.checklyhq.com/docs/heartbeat-monitors/ping-examples This example configures a Ping monitor with a specific source and records the start time for the operation. ```javascript const monitor = { "type": "PING", "name": "My first Ping monitor", "url": "https://ping.checklyhq.com/your-heartbeat-id", "source": "backup-service-prod", "startTime": datetime.utcnow() }; try { logger.info("Starting database backup...") # Backup logic backup_size = perform_backup() upload_to_cloud(backup_size) # Calculate job metrics duration = datetime.utcnow() - startTime logger.info(f"Backup completed in {duration} seconds.") } catch (e) { logger.error("Backup failed:", e) } ``` -------------------------------- ### Get IP Information using Python Source: https://www.checklyhq.com/docs/monitoring/ip-info Provides an example of how to access the IP Information API using Python's 'requests' library. Ensure you have the library installed (`pip install requests`). ```python import requests API_KEY = 'YOUR_API_KEY' IP_ADDRESS = '8.8.8.8' url = f"https://api.checklyhq.com/v1/ip-info/{IP_ADDRESS}" headers = { 'X-Api-Key': API_KEY } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes ip_info = response.json() print(ip_info) except requests.exceptions.RequestException as e: print(f"Error fetching IP info: {e}") ``` -------------------------------- ### Basic Prometheus Exporter Setup Source: https://www.checklyhq.com/docs/integrations/prometheus A minimal example of setting up the Prometheus exporter using OpenTelemetry. This requires installing the necessary packages. ```javascript const { PrometheusExporter } = require('@opentelemetry/exporter-prometheus') const { MeterProvider } = require('@opentelemetry/sdk-metrics') const exporter = new PrometheusExporter({ port: 9464 }) const meterProvider = new MeterProvider() meterProvider.addMetricReader(exporter) ``` -------------------------------- ### Basic Get Data as JSON with Playwright Source: https://www.checklyhq.com/docs/accounts-and-users/adding-team-members Launches a browser, navigates to a page, and retrieves page content. This example is a starting point for data extraction. ```javascript const { chromium } = require('playwright') const fs = require('fs') ;(async () => { const browser = await chromium.launch() const page = await browser.newPage() await page.goto('https://danube-web.shop/') const content = await ``` -------------------------------- ### Basic Setup Script Example Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts A simple JavaScript setup script that logs a message indicating it's running before the main API check. This is useful for debugging or simple environment preparation. ```javascript console.log('Running setup script...'); ``` -------------------------------- ### Basic Playwright Test Source: https://www.checklyhq.com/docs/browser-checks/playwright-test A simple Playwright test script to navigate to a page and assert its title. This is a fundamental example for getting started with Playwright tests in Checkly. ```javascript import { test, expect } from '@playwright/test'; test('basic test', async ({ page }) => { await page.goto('https://playwright.dev/'); await expect(page).toHaveTitle(/Playwright/); }); ``` -------------------------------- ### Initialize a new Pulumi project with JavaScript template Source: https://www.checklyhq.com/docs/integrations/pulumi Initialize a new Pulumi project using the 'pulumi new javascript' command. This command guides you through project setup, including naming and description, and installs dependencies. ```text $ pulumi new javascript This command will walk you through creating a new Pulumi project. Enter a value or leave blank to accept the (default), and press . Press ^C at any time to quit. project name: (new-pulumi-checkly-project) project description: (A minimal JavaScript Pulumi program) Created project 'new-pulumi-checkly-project' Please enter your desired stack name. To create a stack in an organization, use the format / (e.g. `acmecorp/dev`). stack name: (dev) Created stack 'dev' Installing dependencies... added 96 packages, and audited 97 packages in 4s Finished installing dependencies ``` -------------------------------- ### Playwright Get Href and Handle Example Source: https://www.checklyhq.com/docs/cicd/github-actions An example demonstrating how to get the `href` attribute from an element and handle it using Playwright. ```javascript const { chromium } = require('playwright') ;(async () => { const browser = await chromium.launch() const page = await browser.newPage() await page.goto('https://danube-web.shop/') const ``` -------------------------------- ### Pulumi CLI Setup Example Source: https://www.checklyhq.com/docs/integrations/pulumi This snippet shows the expected output after successfully setting up the Pulumi CLI. It confirms the command is available in your environment. ```text pulumi ``` -------------------------------- ### GET Request Example Source: https://www.checklyhq.com/docs/heartbeat-monitors/ping-examples Use this example to perform a GET request to a ping monitor. It includes options for retries and silent mode. ```shellscript curl -m 5 --retry 3 -s \"https://ping.checklyhq.com/your-heartbeat-id\" ``` -------------------------------- ### Pulumi CLI Setup and Project Creation Source: https://www.checklyhq.com/docs/integrations/pulumi This snippet shows the basic Pulumi CLI commands for setting up a new project. Ensure you have the Pulumi CLI installed and a Pulumi account. ```text $ pulumi pulumi Pulumi - Modern Infrastructure as Code To begin working with Pulumi, run the `pulumi new` command: $ pulumi new This will prompt you to create a new project for your cloud and language of choice. ... ... ``` -------------------------------- ### Handle Authentication in Setup Script Source: https://www.checklyhq.com/docs/api-checks/teardown-script-examples This example shows how to dynamically fetch an authentication token in a setup script and set it as an Authorization header. It uses the 'request' object to access and modify headers. ```javascript async ({ request }) => { const token = await getToken(); // Assume getToken() fetches the token request.headers.set('Authorization', `Bearer ${token}`); } ``` -------------------------------- ### GET Request with Headers Source: https://www.checklyhq.com/docs/api-checks/setup-script-examples Example of making a GET request with custom headers, such as for authentication. ```javascript const { test, expect } = require('@playwright/test') test('GET request with headers', async ({ request }) => { const response = await request.get('https://api.example.com/users', { headers: { 'Authorization': 'Bearer YOUR_API_TOKEN', 'Accept': 'application/json' } }) expect(response.status()).toBe(200) }) ``` -------------------------------- ### Including Modules in Setup/Teardown Scripts Source: https://www.checklyhq.com/docs/api-checks/teardown-script-examples Demonstrates how to explicitly include modules and libraries in setup and teardown scripts using require. This example includes the 'moment' library. ```javascript const moment = require('moment'); console.log(moment().format()); ``` -------------------------------- ### Basic GET Request Source: https://www.checklyhq.com/docs/api-checks/setup-script-examples A simple example of making a GET request to an API endpoint and asserting the status code. ```javascript const { test, expect } = require('@playwright/test') test('basic GET request', async ({ request }) => { const response = await request.get('https://api.example.com/users') expect(response.status()).toBe(200) }) ``` -------------------------------- ### Using Axios in Setup/Teardown Scripts Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts Demonstrates how to use the 'axios' library to make HTTP requests within your setup or teardown scripts. This example shows how to delete a user and includes setting authorization headers using environment variables. ```javascript const axios = require('axios'); await axios.delete(`https://api.acme.com/users/${testUserId}`, { headers: { Authorization: `Bearer ${process.env.API_KEY}` } }) console.log( ``` -------------------------------- ### Basic Ping Monitor Setup Source: https://www.checklyhq.com/docs/heartbeat-monitors/ping-examples This snippet shows a basic setup for a Ping monitor, sending a GET request to a specified URL. ```shellscript # In your Heroku Scheduler command run_task.sh && curl -m 5 --retry 3 https://ping.checklyhq.com/your-heartbeat-id ``` -------------------------------- ### Basic Ping Monitor Setup in JavaScript Source: https://www.checklyhq.com/docs/heartbeat-monitors/ping-examples This example demonstrates the basic setup for a Ping monitor using the Checkly SDK in JavaScript. It requires the 'https' module and defines a simple check. ```javascript const https = require('https'); exports.handler = async ({ check, request, response }) => { const { hostname, port, path, method } = request; const options = { hostname, port, path, method, }; const req = https.request(options, (res) => { response.send(`Status code: ${res.statusCode}`); }); req.on('error', (error) => { response.send(`Error: ${error.message}`); }); req.end(); }; ``` -------------------------------- ### Fetch and Sign Session Tokens Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts This example demonstrates fetching or signing session tokens within a setup script to authenticate API requests. It shows how to import an auth client and update the request object. ```typescript import { authClient } from "./auth-client"; const session = await authClient.getSession(); request.headers.Authorization = `Bearer ${session.token}`; ``` -------------------------------- ### Incident.io Webhook Setup Source: https://www.checklyhq.com/docs/integrations/incidentio Configure a webhook in Checkly to send incident alerts to Incident.io. This example shows a basic webhook setup. ```json { "type": "webhook", "name": "Incident.io Alert", "url": "https://api.incident.io/v1/webhooks/checkly", "method": "POST", "contentType": "application/json", "template": { "source": "{{{\ \"event\": \"check.degraded\",\n \"data\": {\n \"check_id\": \"{{check.id}}\",\n \"check_name\": \"{{check.name}}\",\n \"check_url\": \"{{check.url}}\",\n \"check_status\": \"{{check.status}}\",\n \"check_run_id\": \"{{check.last_run.id}}\",\n \"check_run_timestamp\": \"{{check.last_run.timestamp}}\"\n }\n}}}" } } ``` -------------------------------- ### Basic Ping Monitor Example Source: https://www.checklyhq.com/docs/heartbeat-monitors/ping-examples A simple example demonstrating how to set up a basic Ping monitor. This is useful for ensuring a service is reachable. ```javascript if __name__ == "__main__": run_scheduled_job() ``` -------------------------------- ### Modify Request in Setup Script Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts Use setup scripts to modify the outgoing request. This example shows how to add a custom header. ```javascript async ({ request }) => { request.headers.set('X-Custom-Header', 'my-value'); } ``` -------------------------------- ### Standard Business APIs Setup Source: https://www.checklyhq.com/docs/api-checks/setup-script-examples Set up checks for standard business APIs. This example defines the frequency, locations, and response time thresholds for monitoring API performance. ```yaml # Important but non-critical APIs Frequency: Every 5-10 minutes Locations: Global coverage Thresholds: - Response time: < 1000ms (degraded), < 5000ms (failed) ``` -------------------------------- ### Setup Script with Authorization Header Source: https://www.checklyhq.com/docs/api-checks/setup-teardown-scripts This setup script demonstrates how to fetch an authentication token and set the Authorization header for the API request. It requires a `getToken` function to be available, typically imported from an authentication module. ```typescript import { getToken } from './common/auth-client'; const token = await getToken(); request.headers.Authorization = `Bearer ${token}`; ``` -------------------------------- ### Node.js Heartbeat Monitor Source: https://www.checklyhq.com/docs/heartbeat-monitors/ping-examples Example of a Node.js script to send a heartbeat ping. Ensure you have the 'axios' package installed (`npm install axios`). ```javascript const axios = require('axios'); async function sendHeartbeat(url, key) { try { await axios.post(url, null, { headers: { 'X-Api-Key': key, }, }); console.log('Heartbeat sent successfully!'); } catch (error) { console.error('Error sending heartbeat:', error.message); } } // Replace with your actual Checkly API key and heartbeat URL const apiKey = 'YOUR_CHECKLY_API_KEY'; const heartbeatUrl = 'YOUR_HEARTBEAT_URL'; sendHeartbeat(heartbeatUrl, apiKey); ``` -------------------------------- ### Setup Script with Authorization Header Source: https://www.checklyhq.com/docs/api-checks/teardown-script-examples This setup script demonstrates how to construct a request object with an Authorization header using a helper function. ```typescript import { getToken } from './common/auth-client' const token = await getToken() request: { method: 'GET', url: 'https://api.acme.com/v1/products' } ```