Home / Authentication and API keys

Authentication and API keys

Pass your Labrika key in the Authorization header and check its permissions. Learn how to store the secret and diagnose access errors.

On this page

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.