REST API reference
- 01Базовые URL и доступ к Swagger
- 02Авторизация
- 03Abilities
- 04Private endpoint reference
- 05Profile
REST API reference
REST API работает в том же Laravel-приложении и доступен под префиксом /api/v1. Private endpoints используют bearer token, а public endpoints предназначены для respondent-facing flows.
Базовые URL и доступ к Swagger
| Назначение | Production | Local |
|---|---|---|
| REST API | https://psylab-research.org/api/v1 | https://localhost/api/v1 |
| Swagger UI | https://psylab-research.org/api/docs | https://localhost/api/docs |
| OpenAPI JSON | https://psylab-research.org/api/docs.json | https://localhost/api/docs.json |
Swagger UI и OpenAPI JSON не являются публичным API: доступ к ним требует входа и plan capability api_access. Локальный HTTPS может использовать self-signed certificate, поэтому для curl в local добавляйте -k.
Авторизация
Private endpoints требуют Sanctum bearer token с аудиторией api, plan capability api_access и ability, указанную для конкретного endpoint.
Создание токена:
- Войдите в Psylab.
- Откройте /settings/api-mcp; старый путь /settings/api-tokens перенаправляет туда.
- Создайте API token и выберите только необходимые API abilities.
- Скопируйте plaintext сразу: он показывается один раз.
- Передавайте его только в HTTPS-запросах.
Accept: application/json
Authorization: Bearer TOKEN_HERE
MCP token с аудиторией mcp не подходит для REST API.
Abilities
| Ability | Назначение |
|---|---|
| profile:read | Читать профиль аккаунта токена. |
| studies:read, studies:write, studies:delete | Читать, создавать/изменять и удалять или архивировать исследования. |
| tests:read, tests:write, tests:delete | Читать, создавать/изменять и удалять или архивировать тесты. |
| questions:read, questions:write, questions:delete | Читать, создавать, изменять, переупорядочивать и удалять вопросы. |
| responses:read, responses:write | Читать/создавать participant sessions и отправлять ответы. |
| results:read | Читать сохранённые результаты тестов. |
| respondents:read, respondents:write, respondents:delete | Читать, создавать/изменять и удалять респондентов. |
| analytics:read | Читать аналитику тестов и исследований. |
Admin-only content abilities и MCP abilities не нужны для research endpoints этой страницы. Контроль владельца объекта применяется поверх token abilities: обычный пользователь видит свои доступные записи, администратор может работать в административном контексте.
Private endpoint reference
Все private endpoints ниже находятся под /api/v1 и используют общие middleware: audience api, capability api_access, throttle:api-auth и integration.usage:api.
Profile
| Method | Path | Ability |
|---|---|---|
| GET | /me | profile:read |
Studies
| Method | Path | Ability |
|---|---|---|
| GET | /studies | studies:read |
| POST | /studies | studies:write |
| GET | /studies/{study} | studies:read |
| PATCH | /studies/{study} | studies:write |
| DELETE | /studies/{study} | studies:delete |
| POST | /studies/{study}/archive | studies:delete |
| POST | /studies/{study}/restore | studies:delete |
| GET | /studies/{study}/analytics | analytics:read |
| GET | /studies/{study}/versions | studies:read |
| POST | /studies/{study}/versions | studies:write |
Study composition
| Method | Path | Ability |
|---|---|---|
| POST | /studies/{study}/tests | tests:write |
| POST | /studies/{study}/respondents | respondents:write |
Tests
| Method | Path | Ability |
|---|---|---|
| GET | /tests | tests:read |
| POST | /tests | tests:write |
| GET | /tests/{test} | tests:read |
| PATCH | /tests/{test} | tests:write |
| DELETE | /tests/{test} | tests:delete |
| POST | /tests/{test}/archive | tests:delete |
| POST | /tests/{test}/restore | tests:delete |
| GET | /tests/{test}/analytics | analytics:read |
| GET | /tests/{test}/versions | tests:read |
| POST | /tests/{test}/versions | tests:write |
Sessions and responses
| Method | Path | Ability |
|---|---|---|
| POST | /tests/{test}/sessions | responses:write |
| GET | /tests/{test}/sessions/{session-token} | responses:read |
| POST | /tests/{test}/sessions/{session-token}/submit | responses:write |
Questions
| Method | Path | Ability |
|---|---|---|
| GET | /tests/{test}/questions | questions:read |
| POST | /tests/{test}/questions | questions:write |
| POST | /tests/{test}/questions/reorder | questions:write |
| GET | /tests/{test}/questions/{question} | questions:read |
| PATCH | /tests/{test}/questions/{question} | questions:write |
| DELETE | /tests/{test}/questions/{question} | questions:delete |
Results and respondents
| Method | Path | Ability |
|---|---|---|
| GET | /results | results:read |
| GET | /results/{result} | results:read |
| GET | /respondents | respondents:read |
| GET | /respondents/{respondent} | respondents:read |
| PATCH | /respondents/{respondent} | respondents:write |
| DELETE | /respondents/{respondent} | respondents:delete |
Request bodies
Create a study
Required fields: title and status; status is draft, active, paused, or completed.
{
"title": "Learning Routines and Daily Wellbeing",
"description": "Synthetic pilot study.",
"instructions": "Answer based on your usual routine.",
"status": "active",
"target_participants": 120,
"is_public": true,
"test_ids": [14, 15]
}
Create a test
Required: title. Optional fields include study_id, description, is_public, show_results, final-screen fields, time_limit_minutes (1–120), ends_at, and scoring version 2.
Create or update a question
POST /tests/{test}/questions requires revision, text, and a supported type. matrix additionally requires matrix_rows and at least two matrix_columns.
{
"revision": "DRAFT_REVISION_64_HEX_CHARS",
"text": "How mentally tired do you usually feel after a typical study day?",
"type": "range",
"order": 1,
"settings": {
"min": 0,
"max": 10,
"step": 1
}
}
Supported types: single, multiple, open, range, rating, boolean, dropdown, nps, scale, email, phone, date, matrix.
Submit a session
{
"respondent_uuid": "OPTIONAL_RESPONDENT_UUID",
"answers": [
{ "question_id": 123, "value": 7 }
],
"response_times": {
"123": 18
},
"total_time": 42
}
answers is required and must be an array; each item requires a distinct question_id and a value. response_times and total_time are optional non-negative integers. The public flow may also accept cf-turnstile-response when the active integration requires it.
Versioning and optimistic concurrency
Changes to studies, tests, and questions use a 64-character draft revision. Read the current revision from the resource or response before a write and send it back unchanged. A stale revision is rejected with a validation error; reread the object and retry against the newest revision.
Publishing is explicit:
- GET /tests/{test}/versions or GET /studies/{study}/versions lists published versions and the current draft_revision.
- POST /tests/{test}/versions and POST /studies/{study}/versions require revision and optional change_note.
- A successful publish returns 201 Created with version id, number, definition hash, and timestamp.
Public endpoint reference
Public routes are under /api/v1, do not require a bearer token, and are for published respondent-facing definitions:
| Method | Path | Purpose |
|---|---|---|
| GET | /public/studies/{study:uuid} | Read public study metadata and test count. |
| POST | /public/studies/{study:uuid}/respondents | Create a respondent for an active public study. |
| POST | /public/studies/{study:uuid}/respondents/{respondent:uuid}/next | Get the next unanswered test session or completion state. |
| GET | /public/tests/{test:slug} | Read a published public test. |
| POST | /public/tests/{test:slug}/sessions | Start an anonymous test session. |
| GET | /public/tests/{test:slug}/sessions/{session-token} | Read an in-progress session. |
| POST | /public/tests/{test:slug}/sessions/{session-token}/submit | Validate and submit answers. |
Public start/submit routes can require the configured Turnstile integration. A session is bound to its test; submitting twice returns 409 Conflict. These endpoints are the participant flow and should be exercised only with synthetic or explicitly authorized data.
Query parameters and rate limits
| Endpoint | Useful query parameters |
|---|---|
| GET /studies | q, status, per_page (1–100). |
| GET /tests | q, study_id, per_page (1–100). |
| GET /respondents | q, study_id, status, sort, direction, per_page = 10, 20, or 50. |
| GET /results | test_id, study_id, respondent_id, sort, direction, per_page = 10, 20, or 50. |
| Analytics | retry=true can request a retry of a failed or stale calculation. |
| Bucket | Limit |
|---|---|
| Authenticated API | 120 requests/minute per user id or IP. |
| Public API | 60 requests/minute per IP. |
| Public submit | 20 submissions/minute per IP. |
Common responses
| Code | Meaning |
|---|---|
| 200 OK | Successful read or update. |
| 201 Created | A study, test, question, session, or version was created. |
| 202 Accepted | Analytics is queued or still running. |
| 204 No Content | A delete completed. |
| 401 Unauthorized | Missing, invalid, expired, or wrong-audience token. |
| 403 Forbidden | Missing ability, plan capability, or object access. |
| 404 Not Found | The object does not exist or is outside the token's access scope. |
| 409 Conflict | The session was already submitted or cannot continue in its current state. |
| 422 Unprocessable Entity | Validation failed, including a missing or stale revision. |
| 429 Too Many Requests | A rate limit was exceeded. |
Validation errors are returned as JSON with field-level messages. Do not treat a successful HTTP status as proof that a participant flow or a publication is complete: inspect the response body and verify the published version.
Example: private request
curl -sS \
-H "Accept: application/json" \
-H "Authorization: Bearer TOKEN_HERE" \
https://psylab-research.org/api/v1/me
Example: publish a draft
curl -sS -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer TOKEN_HERE" \
https://psylab-research.org/api/v1/tests/TEST_ID/versions \
-d '{"revision":"DRAFT_REVISION_64_HEX_CHARS","change_note":"Initial reviewed version"}'
Token revocation and usage
Open /settings/api-mcp and revoke the token there. After revocation, the bearer token stops authorizing requests. The application also records integration usage for authenticated API calls, so keep token names meaningful and avoid putting secrets or participant text into query parameters.
Swagger/OpenAPI is generated from the running application. When a route or request contract changes, use /api/docs.json as the source of truth and update this page alongside the code.