The API lists and reads tests and starts their runs; with a manage key it also creates, changes and deletes them, while their configuration stays in the app. Every test has a numeric id and a public tst_… id shown in the app, and both work wherever a path takes a test {id}.
Test
A test with its kind, schedule, next run, latest run, pass statistics and the notification channels it notifies.
Fields: Test
Field
Type
Description
id
string
The test's numeric id, as a decimal string.
customId
string (tst_…)
The public test id (tst_ and 12 characters) shown in the app; it never changes and works wherever a test id is accepted.
Lists the tests in the key's scope; the optional filters project, kind and query combine. Needs read access, and the list is not paged. The example finds the availability test “Checkout page” in project 42.
Needs a key with access: Read
Parameters
Parameters: GET /tests
Name
In
Type
Required
Description
Example
project
Query string
string (numeric project id)
No
Returns only the tests of this project (numeric id).
// Java 11+: save as Main.java and run `java Main.java`import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public classMain {
public static void main(String[] args) throwsException {
String url = "https://optisway.com/api/v1/tests?project=42&kind=availability&query=checkout";
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.header("Authorization", "Bearer " + System.getenv("OPTISWAY_API_KEY"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) {
String error = response.body();
System.err.println(response.statusCode() + " " + field(error, "error") + ": "
+ field(error, "message"));
System.exit(1);
}
// { "items": [...], "next": ... } -- any JSON library (Jackson, Gson, org.json) parses it;// this example stays dependency-free and prints the raw JSON.System.out.println(response.body());
}
/** The first string value of a JSON key (dependency-free; Jackson or Gson parse JSON properly). */static String field(String json, String key) {
Matcher match = Pattern.compile("\"" + key + "\"\\s*:\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|null)")
.matcher(json);
return match.find() ? match.group(1) : null;
}
}
package main
import (
"encoding/json""fmt""net/http""os"
)
func main() {
url := "https://optisway.com/api/v1/tests?project=42&kind=availability&query=checkout"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("OPTISWAY_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
var envelope struct {
Error string`json:"error"`
Message string`json:"message"`
}
_ = json.NewDecoder(resp.Body).Decode(&envelope)
fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, envelope.Error, envelope.Message)
os.Exit(1)
}
var body map[string]anyif err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
panic(err)
}
for _, raw := range body["items"].([]any) {
item := raw.(map[string]any)
fmt.Println(item["id"], item["name"])
}
}
// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`usingSystem.Net.Http.Headers;
usingSystem.Net.Http.Json;
usingSystem.Text.Json;
using var client = newHttpClient();
client.DefaultRequestHeaders.Authorization =
newAuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var url = "https://optisway.com/api/v1/tests?project=42&kind=availability&query=checkout";
using var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
var error = envelope.GetProperty("error");
var message = envelope.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode}{error}: {message}");
Environment.Exit(1);
}
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
foreach (var item in body.GetProperty("items").EnumerateArray())
{
Console.WriteLine(string.Join(" ",
item.GetProperty("id"), item.GetProperty("name")));
}
Example response
Returns: An object whose items array holds Test objects.
invalid_request400 A path, filter or limit is invalid, or a JSON body is unreadable, too large or invalid.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.
Read a testGET/tests/{id}
Reads one test by its numeric id or by the public tst_… id shown on the test in the app. Needs read access. The test's configuration (steps, scripts, API requests, visual and accessibility settings, session setup) is never returned; you edit it in the app.
Needs a key with access: Read
Parameters
Parameters: GET /tests/{id}
Name
In
Type
Required
Description
Example
id
Path
string (numeric id or tst_… id)
Yes
The test: its numeric id or its public tst_… id from the app.
// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`usingSystem.Net.Http.Headers;
usingSystem.Net.Http.Json;
usingSystem.Text.Json;
using var client = newHttpClient();
client.DefaultRequestHeaders.Authorization =
newAuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd";
using var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
var error = envelope.GetProperty("error");
var message = envelope.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode}{error}: {message}");
Environment.Exit(1);
}
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine($"ID: {body.GetProperty("id")}");
Console.WriteLine($"Name: {body.GetProperty("name")}");
not_found404 The resource does not exist or is outside the key’s scope.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.
Create a testPOST/projects/{id}/tests
Creates a test in the project with a name, a kind, an address and, optionally, a description, a schedule and a paused state. Needs a key with manage access; the API creates availability, links, SEO, Core Web Vitals, visual and accessibility tests with their default settings, while journeys, scripted journeys and API tests need configuration you add in the app. The example adds an hourly check of the pricing page to project 42.
Needs a key with access: Manage
Parameters
Parameters: POST /projects/{id}/tests
Name
In
Type
Required
Description
Example
id
Path
string (numeric project id)
Yes
The numeric id of the project, as returned in Project.id.
42
Request body: POST /projects/{id}/tests
Name
Type
Required
Description
Example
name
string, 1–100 characters
Yes
The test's name as shown in the app: 1–100 characters without line breaks.
What the test checks; the API creates these kinds with their default settings, and journeys, scripted journeys and API tests are created in the app.
"availability"
url
string (public http:// or https:// URL)
Yes
The page or address the test checks: a complete, public http:// or https:// URL.
"https://shop.example.com/pricing"
description
string, ≤ 500 characters | null
No
A note of up to 500 characters; null or an empty string leaves it empty.
"Checks that the pricing page answers quickly."
scheduleMinutes
15 | 60 | 180 | 360 | 720 | 960 | 1440 | null
No
Minutes between two scheduled runs (60 = hourly, 1440 = daily), or null for runs on demand only; the organisation's plan decides which schedules it offers.
60
enabled
boolean, default true
No
false pauses the test, so it gets no scheduled runs; a new test is enabled when you leave it out.
// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`usingSystem.Net.Http.Headers;
usingSystem.Net.Http.Json;
usingSystem.Text;
usingSystem.Text.Json;
using var client = newHttpClient();
client.DefaultRequestHeaders.Authorization =
newAuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var url = "https://optisway.com/api/v1/projects/42/tests";
var json = """
{
"name": "Pricing page",
"kind": "availability",
"url": "https://shop.example.com/pricing",
"description": "Checks that the pricing page answers quickly.",
"scheduleMinutes": 60,
"enabled": true
}
""";using var response = await client.PostAsync(url,
newStringContent(json, Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode)
{
var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
var error = envelope.GetProperty("error");
var message = envelope.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode}{error}: {message}");
Environment.Exit(1);
}
var test = await response.Content.ReadFromJsonAsync<JsonElement>();
var customId = test.GetProperty("customId");
var id = test.GetProperty("id");
Console.WriteLine($"Created test {customId} ({id}): {response.Headers.Location}");
Example response
Returns: The new Test object, with 201 Created and a Location header that points at it.
forbidden403 The key’s access level is too low: a read key tried to start a run, or a key without manage tried to change tests. Also when the key’s creator may not delete tests.
invalid_request400 A path, filter or limit is invalid, or a JSON body is unreadable, too large or invalid.
not_found404 The resource does not exist or is outside the key’s scope.
plan_limit_reached422 The organisation’s plan does not allow it: the test limit is reached, the kind is not included, or (on artifact downloads) run evidence is not included in the plan.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.
Update a testPATCH/tests/{id}
Changes the fields you send and keeps the others; null clears description or the schedule, and kind and the configuration never change here. Needs a key with manage access; a new schedule or enabled value restarts the interval from now, and selecting notification channels needs a plan that includes them. The example renames test tst_7k2m9q4xh3vd, makes it run every hour and sends its notifications only to the checkout team's Slack channel.
Needs a key with access: Manage
Parameters
Parameters: PATCH /tests/{id}
Name
In
Type
Required
Description
Example
id
Path
string (numeric id or tst_… id)
Yes
The test: its numeric id or its public tst_… id from the app.
tst_7k2m9q4xh3vd
Request body: PATCH /tests/{id}
Name
Type
Required
Description
Example
name
string, 1–100 characters
No
The test's name as shown in the app: 1–100 characters without line breaks.
"Checkout page (EU)"
url
string (public http:// or https:// URL)
No
The page or address the test checks: a complete, public http:// or https:// URL.
null
description
string, ≤ 500 characters | null
No
A note of up to 500 characters; null or an empty string leaves it empty.
null
scheduleMinutes
15 | 60 | 180 | 360 | 720 | 960 | 1440 | null
No
Minutes between two scheduled runs (60 = hourly, 1440 = daily), or null for runs on demand only; the organisation's plan decides which schedules it offers.
60
enabled
boolean
No
false pauses the test, so it gets no scheduled runs; a new test is enabled when you leave it out.
null
notificationRouting
NotificationRouting
No
Which notification channels the test notifies, with the ids from the channel list; selecting channels needs a plan that includes notification channels, while every channel is always allowed.
forbidden403 The key’s access level is too low: a read key tried to start a run, or a key without manage tried to change tests. Also when the key’s creator may not delete tests.
invalid_request400 A path, filter or limit is invalid, or a JSON body is unreadable, too large or invalid.
not_found404 The resource does not exist or is outside the key’s scope.
plan_limit_reached422 The organisation’s plan does not allow it: the test limit is reached, the kind is not included, or (on artifact downloads) run evidence is not included in the plan.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.
Delete a testDELETE/tests/{id}
Deletes the test and its run history; this cannot be undone. Needs a key with manage access whose creator is an owner or admin, and while the test has a queued or running run the API answers 409 run_in_progress and deletes nothing. The example deletes test tst_7k2m9q4xh3vd.
Needs a key with access: Manage
Parameters
Parameters: DELETE /tests/{id}
Name
In
Type
Required
Description
Example
id
Path
string (numeric id or tst_… id)
Yes
The test: its numeric id or its public tst_… id from the app.
// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`usingSystem.Net.Http.Headers;
usingSystem.Net.Http.Json;
usingSystem.Text.Json;
using var client = newHttpClient();
client.DefaultRequestHeaders.Authorization =
newAuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd";
using var response = await client.DeleteAsync(url);
if (!response.IsSuccessStatusCode)
{
var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
var error = envelope.GetProperty("error");
var message = envelope.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode}{error}: {message}");
Environment.Exit(1);
}
Console.WriteLine($"Deleted (HTTP {(int)response.StatusCode})");
Example response
Returns: No body: the status is 204 No Content.
Status:204 No Content
Headers:Cache-Control: no-store
There is no body. The test and its runs are gone, and its ids now answer 404 not_found.
Errors you can get
forbidden403 The key’s access level is too low: a read key tried to start a run, or a key without manage tried to change tests. Also when the key’s creator may not delete tests.
not_found404 The resource does not exist or is outside the key’s scope.
run_in_progress409 The test already has a run in progress.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.
List the runs of a testGET/tests/{id}/runs
Lists the runs of one test, newest first, one page at a time. Needs read access. The example asks for two runs per page; because the page is full, next holds the path of the following page.
Needs a key with access: Read
Parameters
Parameters: GET /tests/{id}/runs
Name
In
Type
Required
Description
Example
id
Path
string (numeric id or tst_… id)
Yes
The test: its numeric id or its public tst_… id from the app.
tst_7k2m9q4xh3vd
limit
Query string
integer, 1–50, default 20
No
How many runs one page holds: a whole number from 1 to 50; without it, a page holds 20.
2
before
Query string
string (run id)
No
Returns only runs older than this run id; you normally follow next instead of setting it yourself.
// Java 11+: save as Main.java and run `java Main.java`import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public classMain {
public static void main(String[] args) throwsException {
String url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs?limit=2";
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.header("Authorization", "Bearer " + System.getenv("OPTISWAY_API_KEY"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) {
String error = response.body();
System.err.println(response.statusCode() + " " + field(error, "error") + ": "
+ field(error, "message"));
System.exit(1);
}
// { "items": [...], "next": ... } -- any JSON library (Jackson, Gson, org.json) parses it;// this example stays dependency-free and prints the raw JSON.System.out.println(response.body());
}
/** The first string value of a JSON key (dependency-free; Jackson or Gson parse JSON properly). */static String field(String json, String key) {
Matcher match = Pattern.compile("\"" + key + "\"\\s*:\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|null)")
.matcher(json);
return match.find() ? match.group(1) : null;
}
}
package main
import (
"encoding/json""fmt""net/http""os"
)
func main() {
url := "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs?limit=2"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("OPTISWAY_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
var envelope struct {
Error string`json:"error"`
Message string`json:"message"`
}
_ = json.NewDecoder(resp.Body).Decode(&envelope)
fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, envelope.Error, envelope.Message)
os.Exit(1)
}
var body map[string]anyif err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
panic(err)
}
for _, raw := range body["items"].([]any) {
item := raw.(map[string]any)
fmt.Println(item["id"], item["status"], item["summary"])
}
}
// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`usingSystem.Net.Http.Headers;
usingSystem.Net.Http.Json;
usingSystem.Text.Json;
using var client = newHttpClient();
client.DefaultRequestHeaders.Authorization =
newAuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs?limit=2";
using var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
var error = envelope.GetProperty("error");
var message = envelope.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode}{error}: {message}");
Environment.Exit(1);
}
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
foreach (var item in body.GetProperty("items").EnumerateArray())
{
Console.WriteLine(string.Join(" ",
item.GetProperty("id"), item.GetProperty("status"), item.GetProperty("summary")));
}
Example response
Returns: An object with items (Run objects) and next (the path of the next page, or null on the last page).
invalid_request400 A path, filter or limit is invalid, or a JSON body is unreadable, too large or invalid.
not_found404 The resource does not exist or is outside the key’s scope.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.
Start a runPOST/tests/{id}/runs
Queues a run of the test with triggerapi and answers 202 Accepted at once, without waiting for the result; it counts against the organisation's 30 manual and API runs per hour. Needs a key with run access; send no body (a JSON body of up to 16 KiB is accepted and ignored). The example queues run 4821, and the Location header points at it.
Needs a key with access: Run
Parameters
Parameters: POST /tests/{id}/runs
Name
In
Type
Required
Description
Example
id
Path
string (numeric id or tst_… id)
Yes
The test: its numeric id or its public tst_… id from the app.
tst_7k2m9q4xh3vd
Example request
curl --fail-with-body -sS -X POST -i"https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs" \
-H"Authorization: Bearer $OPTISWAY_API_KEY"
// Node.js 18+: save as optisway.mjs and run `node optisway.mjs`const url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs";
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPTISWAY_API_KEY}`,
},
});
if (!response.ok) {
const { error, message } = await response.json();
console.error(`${response.status}${error}: ${message}`);
process.exit(1);
}
const run = await response.json();
console.log(`Run ${run.id} is ${run.status}: ${response.headers.get("location")}`);
console.log("Poll GET /runs/{id} every 10 seconds until status is passed, failed or error.");
# pip install requestsimport os
import sys
import requests
api_key = os.environ["OPTISWAY_API_KEY"]
response = requests.post(
"https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs",
headers={"Authorization": f"Bearer {api_key}"},
timeout=30,
)
if not response.ok:
envelope = response.json()
print(f"{response.status_code}{envelope['error']}: {envelope['message']}", file=sys.stderr)
sys.exit(1)
run = response.json()
print(f"Run {run['id']} is {run['status']}: {response.headers['Location']}")
print("Poll GET /runs/{id} every 10 seconds until status is passed, failed or error.")
require"json"require"net/http"require"uri"
uri = URI("https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{ENV.fetch("OPTISWAY_API_KEY")}"
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
unless response.is_a?(Net::HTTPSuccess)
envelope = JSON.parse(response.body)
warn "#{response.code}#{envelope["error"]}: #{envelope["message"]}"
exit 1end
run = JSON.parse(response.body)
puts"Run #{run["id"]} is #{run["status"]}: #{response["Location"]}"puts"Poll GET /runs/{id} every 10 seconds until status is passed, failed or error."
<?php$location = null;
$curl = curl_init("https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs");
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("OPTISWAY_API_KEY"),
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => "",
CURLOPT_HEADERFUNCTION => function ($curl, $line) use (&$location) {
if (stripos($line, "location:") === 0) $location = trim(substr($line, 9));
return strlen($line);
},
]);
$body = curl_exec($curl);
if ($body === false) {
fwrite(STDERR, curl_error($curl) . "\n");
exit(1);
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($status < 200 || $status >= 300) {
$envelope = json_decode($body, true);
fwrite(STDERR, "$status{$envelope['error']}: {$envelope['message']}\n");
exit(1);
}
$run = json_decode($body, true);
echo"Run {$run['id']} is {$run['status']}: $location\n";
echo"Poll GET /runs/{id} every 10 seconds until status is passed, failed or error.", "\n";
// Java 11+: save as Main.java and run `java Main.java`import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public classMain {
public static void main(String[] args) throwsException {
String url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs";
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.header("Authorization", "Bearer " + System.getenv("OPTISWAY_API_KEY"))
.POST(HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 300) {
String error = response.body();
System.err.println(response.statusCode() + " " + field(error, "error") + ": "
+ field(error, "message"));
System.exit(1);
}
String body = response.body();
String location = response.headers().firstValue("Location").orElse("");
System.out.println("Run " + field(body, "id") + " is " + field(body, "status") + ": " + location);
System.out.println("Poll GET /runs/{id} every 10 seconds until status is passed, failed or error.");
}
/** The first string value of a JSON key (dependency-free; Jackson or Gson parse JSON properly). */static String field(String json, String key) {
Matcher match = Pattern.compile("\"" + key + "\"\\s*:\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|null)")
.matcher(json);
return match.find() ? match.group(1) : null;
}
}
package main
import (
"encoding/json""fmt""net/http""os"
)
func main() {
url := "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs"
req, err := http.NewRequest(http.MethodPost, url, nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("OPTISWAY_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
var envelope struct {
Error string`json:"error"`
Message string`json:"message"`
}
_ = json.NewDecoder(resp.Body).Decode(&envelope)
fmt.Fprintf(os.Stderr, "%d %s: %s\n", resp.StatusCode, envelope.Error, envelope.Message)
os.Exit(1)
}
var body map[string]anyif err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
panic(err)
}
fmt.Printf("Run %v is %v: %s\n", body["id"], body["status"], resp.Header.Get("Location"))
fmt.Println("Poll GET /runs/{id} every 10 seconds until status is passed, failed or error.")
}
// .NET 8: `dotnet new console`, replace Program.cs with this file, then `dotnet run`usingSystem.Net.Http.Headers;
usingSystem.Net.Http.Json;
usingSystem.Text.Json;
using var client = newHttpClient();
client.DefaultRequestHeaders.Authorization =
newAuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("OPTISWAY_API_KEY"));
var url = "https://optisway.com/api/v1/tests/tst_7k2m9q4xh3vd/runs";
using var response = await client.PostAsync(url, null);
if (!response.IsSuccessStatusCode)
{
var envelope = await response.Content.ReadFromJsonAsync<JsonElement>();
var error = envelope.GetProperty("error");
var message = envelope.GetProperty("message");
Console.Error.WriteLine($"{(int)response.StatusCode}{error}: {message}");
Environment.Exit(1);
}
var run = await response.Content.ReadFromJsonAsync<JsonElement>();
var id = run.GetProperty("id");
var status = run.GetProperty("status");
Console.WriteLine($"Run {id} is {status}: {response.Headers.Location}");
Console.WriteLine("Poll GET /runs/{id} every 10 seconds until status is passed, failed or error.");
Example response
Returns: The queued Run object (status is queued).
forbidden403 The key’s access level is too low: a read key tried to start a run, or a key without manage tried to change tests. Also when the key’s creator may not delete tests.
not_found404 The resource does not exist or is outside the key’s scope.
run_in_progress409 The test already has a run in progress.
run_limit_reached429 The organisation has used its hourly run budget or its plan’s daily or monthly run quota; Retry-After says when to try again.
kind_unsupported422 This server cannot run the test’s kind right now.
plan_limit_reached422 The organisation’s plan does not allow it: the test limit is reached, the kind is not included, or (on artifact downloads) run evidence is not included in the plan.
invalid_request400 A path, filter or limit is invalid, or a JSON body is unreadable, too large or invalid.
unauthorized401 The key is missing, malformed, unknown, revoked or expired, or its creator is no longer a member.
rate_limited429 The key sent too many requests; wait the seconds in Retry-After.
unavailable503 A temporary problem on our side; try again later.