Kimlik doğrulama ve API anahtarları
Labrika API için Bearer anahtarıyla kimlik doğrulamayı ayarlayın. İzinleri, erişim kısıtlarını ve test ile canlı anahtarların farkını inceleyin.
Bu sayfada
Genel API'ye yapılan her istekte Labrika API anahtarı, Bearer kimlik doğrulama şemasıyla
Authorization başlığında gönderilmelidir. Anahtarı iletmek için başka yöntemler desteklenmez.
İstek başlığı
Authorization: Bearer YOUR_API_KEY
Anahtarı X-API-Key üzerinden veya api_key, apiKey, apikey ve x-api-key sorgu parametreleriyle göndermeyin. API bu istekleri invalid_api_key_location koduyla reddeder.
Mod, yetkiler ve kısıtlamalar
mode Live anahtarı /public-api/v1 ile, test anahtarı /public-api-test/v1 ile çalışır.
scopes - Yeni izinler mevcut anahtara scope eklemez. Yeni anahtar oluşturun, scope’ları GET /me ile doğrulayın, entegrasyondaki anahtarı değiştirin ve eskisini iptal edin.
- Main-reports için public-api.show ve public-api-main-reports.show gerekir. Anahtarı oluştururken main-reports:read ve main-reports:export seçin.
-
serp:read, anahtar kelime sıralamalarını okuma erişimi sağlar. -
ai-writer:read— AI Writer bakiyesi. -
ai-optimization:read— maliyet hesaplama ve belge alma. -
ai-optimization:write— optimizasyon başlatma.
IP / CIDR Bu kısıtlama etkinse istemci adresi, izin verilen bir IP adresiyle veya CIDR aralığıyla eşleşmelidir.
secret Anahtarın tam değeri yalnızca oluşturulduğunda gösterilir. Değiştirmek için yeni bir anahtar oluşturun ve eskisini iptal edin.
GET /public-api/v1/me
Entegrasyona başlamadan önce anahtarı doğrulamak için bu uç noktayı kullanın. Yanıt yalnızca gizli bilgi içermeyen üst verileri içerir.
Örnek istek
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());
}
Yanıt · 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
}
}
}
Anahtarların güvenli kullanımı
API anahtarı, atanmış yetkileri kapsamında hesap verilerine erişim sağlar. Anahtarı bir hizmet hesabı parolası gibi koruyun.
- Anahtarı kaynak kodunda değil, bir gizli bilgi yöneticisinde veya ortam değişkeninde saklayın.
- Anahtarı URL içinde göndermeyin: tarayıcı geçmişinde ve proxy günlüklerinde görünebilir.
- Yalnızca gerekli yetkileri atayın ve mümkün olduğunda erişimi IP/CIDR ile sınırlayın.
- Ele geçirilmiş anahtarı tekrar kullanmak yerine iptal edip yeni bir anahtar oluşturun.
| HTTP | Kod | Kontrol edilecekler |
|---|---|---|
401 | invalid_api_key | Başlık eksik, Bearer biçimi geçersiz veya anahtar tanınmıyor. |
401 |
api_key_revoked, api_key_expired, api_key_disabled
| Anahtarın durumunu kontrol edin ve gerekirse yeni bir anahtar oluşturun. |
403 | wrong_key_mode | Anahtar yanlış live/test ortamında kullanılıyor. |
403 | ip_not_allowed | İstemcinin IP adresi anahtarın izin listesinde değil. |
403 | insufficient_scope | Anahtar, uç noktanın gerektirdiği yetkiye sahip değil. |
