Home / Labrika API: quick start, authentication and errors

Labrika API: quick start, authentication and errors

Labrika API: quick start, authentication and errors. HTTP requests, parameters, response schemas and Labrika workflows.

On this page

Quick start

The Labrika Public API provides programmatic access to SEO data. To make your first request, create an API key and pass it in the Authorization header.

If the API returns HTTP 403 with serp_subscription_required, the API key owner needs an active Business or Agency subscription to retrieve keyword rankings. Lists of sites and available rank-check dates and the test API do not require this subscription.

Base URLs

Live https://app.labrika.com/public-api/v1 — real account data.

Test https://app.labrika.com/public-api-test/v1 — isolated test environment.

Live and test keys are not interchangeable. Use each key in the environment selected when it was created.

Your first request in three steps

  1. Create an API key in the API Keys section of the dashboard and select the scopes required by your integration. Save the key immediately: its full value is no longer displayed after the dialog is closed.
  2. Call GET /public-api/v1/me to verify the key, its mode, and its assigned scopes.
  3. Continue with the section available to your account: Keyword rankings, AI Writer, or Change monitoring. Each section lists the required scopes and request sequence.

GET /public-api/v1/me

Validates the API key and returns its non-sensitive metadata without the secret value.

Example request

curl

curl --fail-with-body --silent --show-error --location \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Accept: application/json' \
  'https://app.labrika.com/public-api/v1/me'

JavaScript

async function main () {
  const response = await fetch("https://app.labrika.com/public-api/v1/me", {
    method: "GET",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
    },
    signal: AbortSignal.timeout(30_000),
  })

  if (!response.ok) {
    const responseText = await response.text()
    throw new Error(`HTTP ${response.status}: ${responseText}`)
  }

  const responseText = await response.text()
  const data = responseText && response.headers.get("content-type")?.includes("application/json") ? JSON.parse(responseText) : responseText

  console.log(data)
}

main().catch(error => {
  console.error(error)
  process.exitCode = 1
})

Python

import json
import requests

url = "https://app.labrika.com/public-api/v1/me"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Accept": "application/json",
}

response = requests.request(
    "GET",
    url,
    headers=headers,
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), ensure_ascii=False, indent=2) if response.content and "application/json" in response.headers.get("Content-Type", "") else response.text)

PHP

<?php

$curl = curl_init('https://app.labrika.com/public-api/v1/me');

if ($curl === false) {
    throw new RuntimeException('Unable to initialize cURL');
}

curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer YOUR_API_KEY',
        'Accept: application/json',
    ],
]);

$response = curl_exec($curl);

if ($response === false) {
    $message = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException('Network error: ' . $message);
}

$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException("HTTP $status: $response");
}

if ($response !== '' && str_contains($contentType, 'application/json')) {
    print_r(json_decode($response, true, 512, JSON_THROW_ON_ERROR));
} else {
    echo $response;
}

Go

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
	defer cancel()

	request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://app.labrika.com/public-api/v1/me", nil)
	if err != nil {
		panic(err)
	}

	request.Header.Set("Authorization", "Bearer YOUR_API_KEY")
	request.Header.Set("Accept", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
		errorBody, readErr := io.ReadAll(response.Body)
		if readErr != nil {
			panic(readErr)
		}
		panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, errorBody))
	}

	if _, err := io.Copy(os.Stdout, response.Body); err != nil {
		panic(err)
	}
}

Google Apps Script

function callLabrikaPublicAPI() {
  const response = UrlFetchApp.fetch("https://app.labrika.com/public-api/v1/me", {
    method: "get",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
    },
    followRedirects: false,
    muteHttpExceptions: true,
  });
  const status = response.getResponseCode();
  if (status < 200 || status >= 300) {
    throw new Error('HTTP ' + status + ': ' + response.getContentText());
  }
  Logger.log(response.getContentText());
}

Response · 200 OK

{
  "data": {
    "api_key": {
      "id": "d1h7s96b4n0m5p2q8r0g",
      "name": "Positions integration",
      "mode": "live",
      "prefix": "lb_live",
      "last4": "A9zQ",
      "scopes": ["serp:read"],
      "created_at": "2026-06-18T10:00:00Z",
      "expires_at": null
    }
  }
}

General rules

JSON responses use snake_case fields. Dates and times are returned in UTC using RFC3339 format, for example 2026-06-18T06:00:00Z.

  • Pagination depends on the method. For lists using offset, pass pagination.next_offset while pagination.has_more=true. The HTML markup report uses after: follow its response schema. Do not borrow offset or cursor from another method, and keep the same filters between pages.
  • If pagination.has_more is true, pass pagination.next_offset in the next request.
  • Do not calculate the next offset yourself and do not expect a total field in SERP responses.
  • Store the X-Request-ID response header: it is required to diagnose the request and contact support.

Paginating a list

{
  "data": [],
  "pagination": {
    "limit": 100,
    "offset": 0,
    "next_offset": 100,
    "has_more": true
  }
}

Using the examples

Replace YOUR_API_KEY, YOUR_TEST_API_KEY, SITE_UUID and other placeholders with your own values. Obtain identifiers from earlier API responses. Run code containing a secret key on a server or in a trusted local environment, not in public browser JavaScript. The curl examples use Bash-compatible syntax; Python examples require requests.

HTTP 202 means the request was accepted, not that processing finished. Save the returned identifier and check the state with the specified GET method. HTTP 200 when reading a state is not proof that the task succeeded: inspect status and error fields. Respect retry_after_seconds when returned.

The shared API/MCP usage budget, account money, subscription allowances and AI credits are separate resources. An estimate that does not charge money can still consume the technical usage budget. Before a paid operation, check the current estimate, payment option and response currency.

Back to contents

Authentication

Every Public API request must include a Labrika API key in the Authorization header using the Bearer authentication scheme. Other methods of passing the key are not supported.

Request header

Authorization: Bearer YOUR_API_KEY

Do not pass the key through X-API-Key or query parameters api_key, apiKey, apikey and x-api-key. The API rejects such requests with the invalid_api_key_location code.

Mode, permissions, and restrictions

mode A live key works with /public-api/v1; a test key works with /public-api-test/v1.

scopes
  • New role permissions do not add scopes to an existing key. Create a new key with the required scopes, verify them through GET /me, replace the key in your integration, then revoke the old key.
  • Main-reports requires public-api.show and public-api-main-reports.show permissions. Select main-reports:read and main-reports:export when creating the key.
  • serp:read grants read access to keyword rankings.
  • ai-writer:read — AI Writer balance.
  • ai-optimization:read — cost calculation and document retrieval.
  • ai-optimization:write — start optimization.

IP / CIDR If this restriction is enabled, the client address must match an allowed IP address or CIDR.

secret The full key value is shown only when it is created. To replace a key, create a new one and revoke the old one.

GET /public-api/v1/me

Use this endpoint to verify the key before starting an integration. The response contains only non-sensitive metadata.

Example request

curl

curl --fail-with-body --silent --show-error --location \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Accept: application/json' \
  'https://app.labrika.com/public-api/v1/me'

JavaScript

async function main () {
  const response = await fetch("https://app.labrika.com/public-api/v1/me", {
    method: "GET",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
    },
    signal: AbortSignal.timeout(30_000),
  })

  if (!response.ok) {
    const responseText = await response.text()
    throw new Error(`HTTP ${response.status}: ${responseText}`)
  }

  const responseText = await response.text()
  const data = responseText && response.headers.get("content-type")?.includes("application/json") ? JSON.parse(responseText) : responseText

  console.log(data)
}

main().catch(error => {
  console.error(error)
  process.exitCode = 1
})

Python

import json
import requests

url = "https://app.labrika.com/public-api/v1/me"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Accept": "application/json",
}

response = requests.request(
    "GET",
    url,
    headers=headers,
    timeout=30,
)
response.raise_for_status()
print(json.dumps(response.json(), ensure_ascii=False, indent=2) if response.content and "application/json" in response.headers.get("Content-Type", "") else response.text)

PHP

<?php

$curl = curl_init('https://app.labrika.com/public-api/v1/me');

if ($curl === false) {
    throw new RuntimeException('Unable to initialize cURL');
}

curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer YOUR_API_KEY',
        'Accept: application/json',
    ],
]);

$response = curl_exec($curl);

if ($response === false) {
    $message = curl_error($curl);
    curl_close($curl);
    throw new RuntimeException('Network error: ' . $message);
}

$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE) ?: '';
curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException("HTTP $status: $response");
}

if ($response !== '' && str_contains($contentType, 'application/json')) {
    print_r(json_decode($response, true, 512, JSON_THROW_ON_ERROR));
} else {
    echo $response;
}

Go

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
	defer cancel()

	request, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://app.labrika.com/public-api/v1/me", nil)
	if err != nil {
		panic(err)
	}

	request.Header.Set("Authorization", "Bearer YOUR_API_KEY")
	request.Header.Set("Accept", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
		errorBody, readErr := io.ReadAll(response.Body)
		if readErr != nil {
			panic(readErr)
		}
		panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, errorBody))
	}

	if _, err := io.Copy(os.Stdout, response.Body); err != nil {
		panic(err)
	}
}

Google Apps Script

function callLabrikaPublicAPI() {
  const response = UrlFetchApp.fetch("https://app.labrika.com/public-api/v1/me", {
    method: "get",
    headers: {
      "Authorization": "Bearer YOUR_API_KEY",
      "Accept": "application/json",
    },
    followRedirects: false,
    muteHttpExceptions: true,
  });
  const status = response.getResponseCode();
  if (status < 200 || status >= 300) {
    throw new Error('HTTP ' + status + ': ' + response.getContentText());
  }
  Logger.log(response.getContentText());
}

Response · 200 OK

{
  "data": {
    "api_key": {
      "id": "d1h7s96b4n0m5p2q8r0g",
      "name": "Positions integration",
      "mode": "live",
      "prefix": "lb_live",
      "last4": "A9zQ",
      "scopes": ["serp:read"],
      "created_at": "2026-06-18T10:00:00Z",
      "expires_at": null
    }
  }
}

Handling keys securely

An API key provides access to account data within its assigned scopes. Treat it like a service account password.

  • Store the key in a secrets manager or environment variable, not in source code.
  • Do not pass the key in a URL: such values can appear in browser history and proxy logs.
  • Assign only the scopes you need and restrict access by IP/CIDR whenever possible.
  • Revoke a compromised key and create a new one instead of reusing it.
HTTP Code What to check
401 invalid_api_key The header is missing, the Bearer format is invalid, or the key is not recognized.
401 api_key_revoked, api_key_expired, api_key_disabled Check the key status and issue a new key if necessary.
403 wrong_key_mode The key is being used in the wrong live/test environment.
403 ip_not_allowed The client IP is not in the key's allowlist.
403 insufficient_scope The key does not have the scope required by the endpoint.

Back to contents

API and MCP usage limits

The shared API/MCP usage budget, account money, subscription allowances and AI credits are separate resources. An estimate that does not charge money can still consume the technical usage budget. Before a paid operation, check the current estimate, payment option and response currency.

All live API keys and MCP connections on an account share a budget of 1,000 points per hour and 5,000 per day. Each operation draws from both balances. Points reset at the start of each hour and at midnight UTC. Request rate limits apply separately, including in the sandbox.

API and MCP usage statistics show points used and remaining in the current hour and day, usage in the previous completed periods, and the next reset times in your profile time zone.

Operation Points
Running an operation billed in money, subscription units or AI credits, or replaying a saved result 0
Status, balance or file metadata 1
Page of a project, task, date, rule or URL list 2
Standard edit or cost estimate 3
Page of keyword rankings, Diff rows, audit data, SERM or SERP results 5 for the first 1,000 requested rows, plus 2 for each additional 1,000 rows or part thereof
Bulk URL addition or rule changes 2 for each 1,000 URLs or part thereof
Charts, aggregates, group estimate or attachment upload 8
Transfer of HTML, a screenshot, an attachment, CSV or XLSX 10
Preparing CSV or XLSX, or creating a board from an audit 15
Preparing a group rankings ZIP 25
Preparing a Main Report ZIP 50
Transferring a ready ZIP 20

Errors and diagnostics

429 usage_budget_exceeded The shared budget is exhausted. The Retry-After header gives the number of seconds to wait before retrying. If both limits are exhausted, wait until the later reset.

usage_budget_exceeded MCP returns a tool error with retry_after_seconds and reset_at. Wait until the indicated time before retrying.

Back to contents

Errors and diagnostics

The Public API uses standard HTTP statuses and a consistent JSON error format. For programmatic handling, check error.code, not the message text.

Validation error · 400 Bad Request

{
  "error": {
    "request_id": "req_example",
    "code": "validation_error",
    "message": "Request validation failed.",
    "details": [
      {
        "field": "collected_at",
        "code": "invalid_datetime",
        "message": "Invalid RFC3339 datetime."
      }
    ]
  }
}

Error fields

request_id Request identifier used for logs and support requests.

code Stable machine-readable error reason.

message Brief diagnostic message in English.

details Optional list of individual field errors or additional constraints.

HTTP statuses

HTTP Meaning Client action
400 The request failed validation. Correct the parameters according to error.code and details.
401 The API key is missing or invalid. Check the Authorization header and key status.
403 The key is recognized, but access is denied. Check the mode, scopes, IP allowlist, and Public API access.
404 The resource was not found or is not accessible to the key. Retrieve the identifiers from the API again and verify the selected object.
429 The rate limit was exceeded. Wait for the number of seconds specified by Retry-After.
500 Internal API error. Retry GET requests after a delay. Before retrying a write or run operation, check its outcome; if the error persists, send the request ID to support.
409 A state, estimate or retry conflict occurred. Read error.code. After an uncertain launch result, do not change Idempotency-Key until you have checked the previous operation. If an estimate explicitly expired or mismatched, obtain a fresh one following the method rules. error.code
413 The request body exceeds the allowed size. Reduce it to the limit of this method. error.code
422 The request cannot be completed under the current conditions. Check the error code, such as insufficient credits or an unrecognized product. Retrying without fixing the cause will not help. error.code

Error codes

The following table lists general codes as well as authentication and keyword rankings endpoint errors.

HTTP Code Reason
400 validation_error One or more path/query parameters do not match the contract.
400 invalid_request_id The client-supplied X-Request-ID has an invalid format.
401 invalid_api_key The key is missing, has an invalid format, or is not recognized.
401 invalid_api_key_location The key was not passed in the Authorization: Bearer header.
401 api_key_revoked The key has been revoked.
401 api_key_expired The key has expired.
401 api_key_disabled The key is disabled.
403 wrong_key_mode A live key was used with the test API or a test key was used with the live API.
403 ip_not_allowed The client IP address is not in the key's allowlist.
403 insufficient_scope The key does not have the scope required by the endpoint.
403 serp_subscription_required The API key owner has no active Business or Agency subscription. Activate one of these subscriptions to retrieve keyword rankings through the live API.
403 public_api_user_blocked, public_api_disabled User access is restricted or the Public API is temporarily disabled.
404 not_found The site, search engine, rank check, or another resource was not found.
429 rate_limit_exceeded The request limit for the current window has been exhausted.
500 internal_error Internal service error; the operation outcome may need verification.

Retries

400–404 Do not retry the request unchanged: correct the parameters, key, or permissions first.

429 Retry after the delay specified by Retry-After.

500 For idempotent GET requests, use exponential backoff with a limited number of attempts.

network A GET request can be safely retried after a timeout or dropped connection.

Request ID and rate-limit headers

Every response contains X-Request-ID. The same value is available in an error as error.request_id. Store it together with the endpoint, request time, and HTTP status before contacting support.

Header Meaning
X-Request-ID Unique request identifier for diagnostics.
X-RateLimit-Limit Maximum number of requests in the current window.
X-RateLimit-Remaining Number of requests remaining.
X-RateLimit-Reset Unix timestamp when the current window ends.
Retry-After Number of seconds until a retry is allowed after a 429 response.

For a missing or invalid key, rate-limit headers describe failed attempts per IP. After authentication, they describe the applicable key or account limit. Headers may be absent for blocks before rate-limit checks or if the counter is unavailable.

The shared API/MCP usage budget is exhausted. For HTTP 429, inspect error.code: usage_budget_exceeded differs from the rate_limit_exceeded frequency limit. Respect Retry-After; do not retry continuously without a delay.

HTTP 202 means the request was accepted, not that processing finished. Save the returned identifier and check the state with the specified GET method. HTTP 200 when reading a state is not proof that the task succeeded: inspect status and error fields. Respect retry_after_seconds when returned.

Back to contents

API sandbox: testing an integration

This guide applies to the test environment. Use a TEST key and /public-api-test/v1 throughout. The examples simulate results; they do not run live generation or charge the production account.

API sandbox

The sandbox sends requests only to the test API. Data is isolated from live projects; checks and AI results are simulated without real charges. The key stays in memory until the page closes; code examples use YOUR_TEST_API_KEY.

https://app.labrika.com/public-api-test/v1

To access the sandbox, ask an administrator to grant the permissions public-api.show and public-api-sandbox.show. Removing either permission also blocks requests made with previously issued TEST keys.

  1. Open the sandbox and create a test key. Save it: the server shows the secret only on creation or rotation. After reloading, paste the saved key or rotate it. A live key will not work here. Start with GET /me.
  2. Select an endpoint and a test project, or a site and search engine. Fill in starred fields. Dates accept last or comma-separated collected_at values. For URLs and rules, request the lists first and use IDs from the response. Edit parameters and JSON before sending; the server checks permissions and limits.
  3. For a report, call reports/cost, then prepare reports/run: cost_estimate_id is filled from the response. For AI, estimate the cost, create a document, then read it by document_id. Preparing the next step sends nothing; execute it separately. Check pending states with another GET; the sandbox does not run AI or fetch the real website.
  4. For 401, check the test key; for 403, the scope; for 404, the ID and latest reset; for 409, Idempotency-Key and the body. For 429, wait for Retry-After. For product descriptions, title=sandbox:product_not_recognized simulates an immediate 422; sandbox:async_product_not_recognized and sandbox:product_description_failed simulate an error after pending. Test product documents remain available until reset, for at most 7 days.
  5. Check the HTTP status, Content-Type, X-Request-ID, duration and response size. Copy JSON or download HTML/CSV/PNG. HTML is shown as text and never executed. Successful deletion returns 204 with an empty body. Code examples match the current form parameters; replace YOUR_TEST_API_KEY before running them outside the browser.

For a retry, keep the same Idempotency-Key and request body. Change the key for a separate new operation. A changed body with the previous key may return 409. Requests are never retried automatically.

Cancel stops waiting in the browser but does not guarantee cancellation on the server. Keep the same Idempotency-Key when retrying.

Resetting the sandbox restores the initial test data. Test URLs, rules, reports and documents you created become unavailable. Obtain new identifiers after a reset; production data is unchanged.

Open the Labrika dashboard

Back to contents