PocketBase Collections Web API
PocketBase의 Collections(Web API) 엔드포인트를 사용해 컬렉션을 조회/생성/수정/삭제/비우기/일괄 가져오기/스캐폴드 조회한다.
언제 사용하나요?
- PocketBase의 컬렉션(스키마) 자체를 코드/스크립트로 관리해야 할 때
- CI/CD, 마이그레이션, 개발 환경 초기화에서 컬렉션 구성 자동화가 필요할 때
- Dashboard UI가 아닌 HTTP API 호출로 컬렉션 조작이 필요할 때
공통 제약/필요 조건
1) 연결 정보(필수)
다음 값이 필요하다.
PB_URL: PocketBase 서버의 base URL
예: http://127.0.0.1:8090 또는 https://pb.example.com
PB_ADMIN_EMAIL: superuser 이메일
PB_ADMIN_PASSWORD: superuser 비밀번호
입력 우선순위
- 사용자가 명시적으로 제공한 값/환경변수 이름
- 기본 환경변수(
PB_URL, PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD)
- 둘 다 없으면: 아래 환경변수 목록과 설정 방법을 사용자에게 안내하고, 값이 준비되면 다시 진행한다.
환경변수 설정 예시
export PB_URL="http://127.0.0.1:8090"
export PB_ADMIN_EMAIL="admin@example.com"
export PB_ADMIN_PASSWORD="your-password"
2) 인증(필수)
Collections API는 superuser 토큰이 필요하다.
토큰 발급은 _superusers auth 컬렉션의 auth-with-password를 사용한다.
토큰 발급
- POST
${PB_URL}/api/collections/_superusers/auth-with-password
- Body(JSON):
{
"identity": "admin@example.com",
"password": "your-password"
}
- Response(JSON):
{
"token": "JWT_TOKEN_STRING",
"record": { "...": "..." }
}
이후 모든 요청 헤더
Authorization: <token>
Content-Type: application/json (JSON 바디를 보낼 때)
PocketBase는 Authorization: Bearer <token> 형태가 아니라, Authorization: <token> 형태를 사용한다.
토큰 발급 bash 예시 (jq 사용)
PB_TOKEN="$(
curl -sS -X POST "${PB_URL}/api/collections/_superusers/auth-with-password" \
-H "Content-Type: application/json" \
-d "{\"identity\":\"${PB_ADMIN_EMAIL}\",\"password\":\"${PB_ADMIN_PASSWORD}\"}" \
| jq -r .token
)"
jq가 없다면 (python 사용)
PB_TOKEN="$(
curl -sS -X POST "${PB_URL}/api/collections/_superusers/auth-with-password" \
-H "Content-Type: application/json" \
-d "{\"identity\":\"${PB_ADMIN_EMAIL}\",\"password\":\"${PB_ADMIN_PASSWORD}\"}" \
| python -c 'import sys,json; print(json.load(sys.stdin)["token"])'
)"
3) 공통 요청 규칙
- Base path는 항상
${PB_URL}/api/...
- 일부 엔드포인트는 request body를
multipart/form-data로도 보낼 수 있으나, 기본은 JSON을 사용한다.
collectionIdOrName에는 컬렉션 ID 또는 name을 넣을 수 있다.
- 401이 나오면 토큰이 누락/만료/오류일 수 있으니 재인증 후 재시도한다.
- 403이 나오면 superuser가 아니거나 권한이 없다(대부분 collections 조작은 superuser 전용).
4) 파괴적 작업 가드레일(권장)
아래 작업은 되돌리기 어렵다. 사용자가 명시적으로 요청한 경우에만 실행한다.
DELETE /api/collections/{collectionIdOrName} (컬렉션 삭제)
DELETE /api/collections/{collectionIdOrName}/truncate (레코드 전체 삭제)
PUT /api/collections/import 중 deleteMissing=true (누락된 컬렉션/필드/데이터 삭제 가능)
API 레퍼런스: Collections
아래 모든 요청은 기본적으로 다음 헤더를 사용한다.
Authorization: <PB_TOKEN>
Content-Type: application/json
A) List collections
GET /api/collections
- Query:
page (number, default 1)
perPage (number, default 30)
sort (string, 예: -created,id)
filter (string, 예: (name~'abc' && created>'2022-01-01'))
fields (string, 반환 필드 선택)
skipTotal (boolean, total 계산 생략)
- Response 200(JSON):
PageResult<Collection>{
"page": 1,
"perPage": 30,
"totalItems": 123,
"totalPages": 5,
"items": [ { "id": "...", "name": "...", "type": "...", "fields": [ ... ] } ]
}
- curl 예시
curl -sS "${PB_URL}/api/collections?page=1&perPage=50&sort=-created" \
-H "Authorization: ${PB_TOKEN}"
B) View collection
GET /api/collections/{collectionIdOrName}
- Query:
- Response 200(JSON):
Collection{
"id": "COLLECTION_ID",
"name": "posts",
"type": "base",
"system": false,
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"fields": [ { "name": "title", "type": "text" } ],
"indexes": []
}
- curl 예시
curl -sS "${PB_URL}/api/collections/posts" \
-H "Authorization: ${PB_TOKEN}"
C) Create collection
- POST
/api/collections
- Body:
CollectionCreate
CollectionCreate (요약 스키마)
{
"id": "optional_15_chars",
"name": "required_unique_name",
"type": "base | view | auth", // default: base
"fields": [ /* Array<Field> */ ], // view는 viewQuery 기반 자동 채움(보통 생략 가능)
"indexes": [ "CREATE INDEX ..." ], // view는 indexes 미지원
"system": false,
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
// type=view 일 때 필수
"viewQuery": "SELECT ...",
// type=auth 일 때 주로 사용
"manageRule": null,
"authRule": null,
"authAlert": { "enabled": true, "emailTemplate": { "subject": "...", "body": "..." } },
"oauth2": { "enabled": false, "providers": [], "mappedFields": { "id": "", "name": "", "username": "", "avatarURL": "" } },
"passwordAuth": { "enabled": true, "identityFields": ["email"] },
"mfa": { "enabled": false, "duration": 1800, "rule": "" },
"otp": { "enabled": false, "duration": 180, "length": 8, "emailTemplate": { "subject": "...", "body": "..." } }
}
- Response 200(JSON):
Collection
curl 예시 (base)
curl -sS -X POST "${PB_URL}/api/collections" \
-H "Authorization: ${PB_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "exampleBase",
"type": "base",
"fields": [
{ "name": "title", "type": "text", "required": true, "min": 1 },
{ "name": "status", "type": "bool" }
]
}'
curl 예시 (view)
curl -sS -X POST "${PB_URL}/api/collections" \
-H "Authorization: ${PB_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "exampleView",
"type": "view",
"listRule": "@request.auth.id != \"\"",
"viewRule": null,
"viewQuery": "SELECT id, name FROM posts"
}'
curl 예시 (auth)
curl -sS -X POST "${PB_URL}/api/collections" \
-H "Authorization: ${PB_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "exampleAuth",
"type": "auth",
"createRule": "id = @request.auth.id",
"updateRule": "id = @request.auth.id",
"deleteRule": "id = @request.auth.id",
"fields": [
{ "name": "name", "type": "text" }
],
"passwordAuth": { "enabled": true, "identityFields": ["email"] }
}'
D) Update collection
PATCH /api/collections/{collectionIdOrName}
- Body:
CollectionUpdate (부분 업데이트)
CollectionUpdate (요약)
{
"name": "required",
"fields": [ /* Array<Field> */ ],
"indexes": [ "CREATE INDEX ..." ],
"system": false,
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"viewQuery": "SELECT ...",
"manageRule": null,
"authRule": null,
"authAlert": { "enabled": true, "emailTemplate": { "subject": "...", "body": "..." } },
"oauth2": { "enabled": false, "providers": [], "mappedFields": { "id": "", "name": "", "username": "", "avatarURL": "" } },
"passwordAuth": { "enabled": true, "identityFields": ["email"] },
"mfa": { "enabled": false, "duration": 1800, "rule": "" },
"otp": { "enabled": false, "duration": 180, "length": 8, "emailTemplate": { "subject": "...", "body": "..." } }
}
E) Delete collection
F) Truncate collection (records 전체 삭제)
G) Import collections (bulk)
deleteMissing=true는 "import에 없는 기존 컬렉션/필드"를 삭제할 수 있고, 관련 레코드 데이터도 삭제될 수 있으니 주의.
- curl 예시
curl -sS -X PUT "${PB_URL}/api/collections/import" \
-H "Authorization: ${PB_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"collections": [
{
"name": "collection1",
"type": "base",
"fields": [ { "name": "status", "type": "bool" } ]
},
{
"name": "collection2",
"type": "base",
"fields": [ { "name": "title", "type": "text" } ]
}
],
"deleteMissing": false
}' \
-o /dev/null -w "%{http_code}\n"
H) Scaffolds (기본 컬렉션 템플릿 조회)
GET /api/collections/meta/scaffolds
- Response 200(JSON):
Scaffolds{
"auth": { "type": "auth", "fields": [ /* default fields */ ], "...": "..." },
"base": { "type": "base", "fields": [ /* default fields */ ], "...": "..." },
"view": { "type": "view", "fields": [ /* empty by default */ ], "viewQuery": "" }
}
- curl 예시
curl -sS "${PB_URL}/api/collections/meta/scaffolds" \
-H "Authorization: ${PB_TOKEN}"
권장 실행 순서(워크플로우)
- 입력 확인:
PB_URL, PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD 확보
- 토큰 발급:
_superusers/auth-with-password로 PB_TOKEN 획득
- 안전한 조회로 시작:
- List collections → View collection
- 변경 작업:
- 파괴적 작업은 사용자 요청을 재확인 후 실행:
- Delete / Truncate / Import(
deleteMissing=true)
빠른 점검 체크리스트
PB_URL에 /api를 중복으로 붙이지 않았나? (base는 host까지만)
Authorization: <token> 헤더 형식이 맞나?
- superuser로 로그인했나? (일반 auth record 토큰으로는 collections 조작이 막힐 수 있음)
- import에서
deleteMissing=true를 의도했나?
- truncate/delete는 정말 필요한가?
참고
oai_citation:0‡pocketbase.io
1---2name: pocketbase-collection-operation-23description: PocketBase Web API로 컬렉션(list/view/create/update/delete/truncate/import/scaffolds)을 안전하게 조회·수정·삭제한다4---56# PocketBase Collections Web API78PocketBase의 **Collections(Web API)** 엔드포인트를 사용해 컬렉션을 **조회/생성/수정/삭제/비우기/일괄 가져오기/스캐폴드 조회**한다.910## 언제 사용하나요?1112- PocketBase의 **컬렉션(스키마)** 자체를 코드/스크립트로 관리해야 할 때13- CI/CD, 마이그레이션, 개발 환경 초기화에서 **컬렉션 구성 자동화**가 필요할 때14- Dashboard UI가 아닌 **HTTP API 호출로 컬렉션 조작**이 필요할 때151617## 공통 제약/필요 조건1819### 1) 연결 정보(필수)20다음 값이 필요하다.2122- `PB_URL`: PocketBase 서버의 base URL 23 예: `http://127.0.0.1:8090` 또는 `https://pb.example.com`24- `PB_ADMIN_EMAIL`: superuser 이메일25- `PB_ADMIN_PASSWORD`: superuser 비밀번호2627#### 입력 우선순위281. 사용자가 명시적으로 제공한 값/환경변수 이름292. 기본 환경변수(`PB_URL`, `PB_ADMIN_EMAIL`, `PB_ADMIN_PASSWORD`)303. 둘 다 없으면: 아래 **환경변수 목록**과 **설정 방법**을 사용자에게 안내하고, 값이 준비되면 다시 진행한다.3132#### 환경변수 설정 예시33```bash34export PB_URL="http://127.0.0.1:8090"35export PB_ADMIN_EMAIL="admin@example.com"36export PB_ADMIN_PASSWORD="your-password"37```383940### 2) 인증(필수)4142Collections API는 superuser 토큰이 필요하다.43토큰 발급은 _superusers auth 컬렉션의 auth-with-password를 사용한다.4445#### 토큰 발급46- POST `${PB_URL}/api/collections/_superusers/auth-with-password`47- Body(JSON):48 ```json49 {50 "identity": "admin@example.com",51 "password": "your-password"52 }53 ```54- Response(JSON):55 ```json56 {57 "token": "JWT_TOKEN_STRING",58 "record": { "...": "..." }59 }60 ```6162#### 이후 모든 요청 헤더63- `Authorization: <token>`64- `Content-Type: application/json` (JSON 바디를 보낼 때)6566PocketBase는 `Authorization: Bearer <token>` 형태가 아니라, `Authorization: <token>` 형태를 사용한다.6768토큰 발급 bash 예시 (jq 사용)69```bash70PB_TOKEN="$(71 curl -sS -X POST "${PB_URL}/api/collections/_superusers/auth-with-password" \72 -H "Content-Type: application/json" \73 -d "{\"identity\":\"${PB_ADMIN_EMAIL}\",\"password\":\"${PB_ADMIN_PASSWORD}\"}" \74 | jq -r .token75)"76```7778jq가 없다면 (python 사용)79```bash80PB_TOKEN="$(81 curl -sS -X POST "${PB_URL}/api/collections/_superusers/auth-with-password" \82 -H "Content-Type: application/json" \83 -d "{\"identity\":\"${PB_ADMIN_EMAIL}\",\"password\":\"${PB_ADMIN_PASSWORD}\"}" \84 | python -c 'import sys,json; print(json.load(sys.stdin)["token"])'85)"86```8788### 3) 공통 요청 규칙89- Base path는 항상 `${PB_URL}/api/...`90- 일부 엔드포인트는 request body를 `multipart/form-data`로도 보낼 수 있으나, 기본은 JSON을 사용한다.91- `collectionIdOrName`에는 컬렉션 ID 또는 name을 넣을 수 있다.92- 401이 나오면 토큰이 누락/만료/오류일 수 있으니 재인증 후 재시도한다.93- 403이 나오면 superuser가 아니거나 권한이 없다(대부분 collections 조작은 superuser 전용).949596### 4) 파괴적 작업 가드레일(권장)9798아래 작업은 되돌리기 어렵다. 사용자가 명시적으로 요청한 경우에만 실행한다.99- `DELETE /api/collections/{collectionIdOrName}` (컬렉션 삭제)100- `DELETE /api/collections/{collectionIdOrName}/truncate` (레코드 전체 삭제)101- `PUT /api/collections/import 중 deleteMissing=true` (누락된 컬렉션/필드/데이터 삭제 가능)102103## API 레퍼런스: Collections104105아래 모든 요청은 기본적으로 다음 헤더를 사용한다.106```107Authorization: <PB_TOKEN>108Content-Type: application/json109```110111### A) List collections112- `GET /api/collections`113- Query:114 - `page` (number, default 1)115 - `perPage` (number, default 30)116 - `sort` (string, 예: `-created,id`)117 - `filter` (string, 예: (`name~'abc' && created>'2022-01-01'`))118 - `fields` (string, 반환 필드 선택)119 - `skipTotal` (boolean, total 계산 생략)120- Response 200(JSON): `PageResult<Collection>`121 ```json122 {123 "page": 1,124 "perPage": 30,125 "totalItems": 123,126 "totalPages": 5,127 "items": [ { "id": "...", "name": "...", "type": "...", "fields": [ ... ] } ]128 }129 ```130- curl 예시131 ```bash132 curl -sS "${PB_URL}/api/collections?page=1&perPage=50&sort=-created" \133 -H "Authorization: ${PB_TOKEN}"134 ```135136### B) View collection137- `GET /api/collections/{collectionIdOrName}`138- Query:139 - fields (string)140- Response 200(JSON): `Collection`141 ```json142 {143 "id": "COLLECTION_ID",144 "name": "posts",145 "type": "base",146 "system": false,147 "listRule": null,148 "viewRule": null,149 "createRule": null,150 "updateRule": null,151 "deleteRule": null,152 "fields": [ { "name": "title", "type": "text" } ],153 "indexes": []154 }155 ```156- curl 예시157 ```bash158 curl -sS "${PB_URL}/api/collections/posts" \159 -H "Authorization: ${PB_TOKEN}"160 ```161162### C) Create collection163- POST `/api/collections`164- Body: `CollectionCreate`165166#### CollectionCreate (요약 스키마)167```json168{169 "id": "optional_15_chars",170 "name": "required_unique_name",171 "type": "base | view | auth", // default: base172 "fields": [ /* Array<Field> */ ], // view는 viewQuery 기반 자동 채움(보통 생략 가능)173 "indexes": [ "CREATE INDEX ..." ], // view는 indexes 미지원174 "system": false,175176 "listRule": null,177 "viewRule": null,178 "createRule": null,179 "updateRule": null,180 "deleteRule": null,181182 // type=view 일 때 필수183 "viewQuery": "SELECT ...",184185 // type=auth 일 때 주로 사용186 "manageRule": null,187 "authRule": null,188 "authAlert": { "enabled": true, "emailTemplate": { "subject": "...", "body": "..." } },189 "oauth2": { "enabled": false, "providers": [], "mappedFields": { "id": "", "name": "", "username": "", "avatarURL": "" } },190 "passwordAuth": { "enabled": true, "identityFields": ["email"] },191 "mfa": { "enabled": false, "duration": 1800, "rule": "" },192 "otp": { "enabled": false, "duration": 180, "length": 8, "emailTemplate": { "subject": "...", "body": "..." } }193}194```195- Response 200(JSON): `Collection`196197#### curl 예시 (base)198```bash199curl -sS -X POST "${PB_URL}/api/collections" \200 -H "Authorization: ${PB_TOKEN}" \201 -H "Content-Type: application/json" \202 -d '{203 "name": "exampleBase",204 "type": "base",205 "fields": [206 { "name": "title", "type": "text", "required": true, "min": 1 },207 { "name": "status", "type": "bool" }208 ]209 }'210```211212#### curl 예시 (view)213```bash214curl -sS -X POST "${PB_URL}/api/collections" \215 -H "Authorization: ${PB_TOKEN}" \216 -H "Content-Type: application/json" \217 -d '{218 "name": "exampleView",219 "type": "view",220 "listRule": "@request.auth.id != \"\"",221 "viewRule": null,222 "viewQuery": "SELECT id, name FROM posts"223 }'224```225226#### curl 예시 (auth)227```json228curl -sS -X POST "${PB_URL}/api/collections" \229 -H "Authorization: ${PB_TOKEN}" \230 -H "Content-Type: application/json" \231 -d '{232 "name": "exampleAuth",233 "type": "auth",234 "createRule": "id = @request.auth.id",235 "updateRule": "id = @request.auth.id",236 "deleteRule": "id = @request.auth.id",237 "fields": [238 { "name": "name", "type": "text" }239 ],240 "passwordAuth": { "enabled": true, "identityFields": ["email"] }241 }'242```243244245### D) Update collection246- `PATCH /api/collections/{collectionIdOrName}`247- Body: `CollectionUpdate` (부분 업데이트)248249#### CollectionUpdate (요약)250```json251{252 "name": "required",253 "fields": [ /* Array<Field> */ ],254 "indexes": [ "CREATE INDEX ..." ],255 "system": false,256257 "listRule": null,258 "viewRule": null,259 "createRule": null,260 "updateRule": null,261 "deleteRule": null,262263 "viewQuery": "SELECT ...",264265 "manageRule": null,266 "authRule": null,267 "authAlert": { "enabled": true, "emailTemplate": { "subject": "...", "body": "..." } },268 "oauth2": { "enabled": false, "providers": [], "mappedFields": { "id": "", "name": "", "username": "", "avatarURL": "" } },269 "passwordAuth": { "enabled": true, "identityFields": ["email"] },270 "mfa": { "enabled": false, "duration": 1800, "rule": "" },271 "otp": { "enabled": false, "duration": 180, "length": 8, "emailTemplate": { "subject": "...", "body": "..." } }272}273```274- Response 200(JSON): `Collection`275- curl 예시276 ```bash277 curl -sS -X PATCH "${PB_URL}/api/collections/demo" \278 -H "Authorization: ${PB_TOKEN}" \279 -H "Content-Type: application/json" \280 -d '{281 "name": "new_demo",282 "listRule": "created > \"2022-01-01 00:00:00\""283 }'284 ```285286### E) Delete collection287- `DELETE /api/collections/{collectionIdOrName}`288- Response 204: `null`289- curl 예시290 ```bash291 curl -sS -X DELETE "${PB_URL}/api/collections/demo" \292 -H "Authorization: ${PB_TOKEN}" \293 -o /dev/null -w "%{http_code}\n"294 ```295296297### F) Truncate collection (records 전체 삭제)298- `DELETE /api/collections/{collectionIdOrName}/truncate`299- Response 204: `null`300- curl 예시301 ```bash302 curl -sS -X DELETE "${PB_URL}/api/collections/demo/truncate" \303 -H "Authorization: ${PB_TOKEN}" \304 -o /dev/null -w "%{http_code}\n"305 ```306307308### G) Import collections (bulk)309- `PUT /api/collections/import`310- Body(JSON):311 ```json312 {313 "collections": [ /* Array<Collection> */ ],314 "deleteMissing": false315 }316 ```317- Response 204: `null`318319> `deleteMissing=true`는 "import에 없는 기존 컬렉션/필드"를 삭제할 수 있고, 관련 레코드 데이터도 삭제될 수 있으니 주의.320321- curl 예시322 ```bash323 curl -sS -X PUT "${PB_URL}/api/collections/import" \324 -H "Authorization: ${PB_TOKEN}" \325 -H "Content-Type: application/json" \326 -d '{327 "collections": [328 {329 "name": "collection1",330 "type": "base",331 "fields": [ { "name": "status", "type": "bool" } ]332 },333 {334 "name": "collection2",335 "type": "base",336 "fields": [ { "name": "title", "type": "text" } ]337 }338 ],339 "deleteMissing": false340 }' \341 -o /dev/null -w "%{http_code}\n"342 ```343344345### H) Scaffolds (기본 컬렉션 템플릿 조회)346- `GET /api/collections/meta/scaffolds`347- Response 200(JSON): `Scaffolds`348 ```json349 {350 "auth": { "type": "auth", "fields": [ /* default fields */ ], "...": "..." },351 "base": { "type": "base", "fields": [ /* default fields */ ], "...": "..." },352 "view": { "type": "view", "fields": [ /* empty by default */ ], "viewQuery": "" }353 }354 ```355- curl 예시356 ```bash357 curl -sS "${PB_URL}/api/collections/meta/scaffolds" \358 -H "Authorization: ${PB_TOKEN}"359 ```360361362## 권장 실행 순서(워크플로우)3631. 입력 확인: `PB_URL`, `PB_ADMIN_EMAIL`, `PB_ADMIN_PASSWORD` 확보3642. 토큰 발급: `_superusers/auth-with-password`로 `PB_TOKEN` 획득3653. 안전한 조회로 시작:366 - List collections → View collection3674. 변경 작업:368 - Create 또는 Update3695. 파괴적 작업은 사용자 요청을 재확인 후 실행:370 - Delete / Truncate / Import(`deleteMissing=true`)371372373## 빠른 점검 체크리스트374- `PB_URL`에 `/api`를 중복으로 붙이지 않았나? (base는 host까지만)375- `Authorization: <token>` 헤더 형식이 맞나?376- superuser로 로그인했나? (일반 auth record 토큰으로는 collections 조작이 막힐 수 있음)377- import에서 `deleteMissing=true`를 의도했나?378- truncate/delete는 정말 필요한가?379380## 참고381[oai_citation:0‡pocketbase.io](https://pocketbase.io/docs/api-collections/)