Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 30 ยท APIs

The Admin API and Integrations

Call the Shopware 6 Admin API from other systems: integrations with client credentials, search criteria in JSON, the bulk sync API and batching advice.

The Store API serves shoppers. The Admin API serves everything behind the login: the Administration itself, import scripts, ERP connectors, reporting tools and your own back-office automation. It can read and write almost every entity in the system, which makes it powerful and also something to protect carefully.

In this lesson you will learn how a program gets an access token with an integration, how to read data with the search endpoint and its criteria JSON, how to write many records with the sync API, and what to watch out for when you send large batches. The HTTP examples are read-only, because there is no Shopware server on this site. The runnable examples are PHP stand-ins: a builder that turns criteria into the request body and checks it, and a token and batch simulator. Neither talks to a real shop, and each one says what is simplified. For the PHP side of the same criteria, see Reading and Writing with Repositories.

Integrations and the OAuth client credentials grant

A person logs in with a user name and password. A program should not. In the Administration you create an integration under Settings > System > Integrations. It gets an access key ID and a secret access key. The secret is shown once, so store it in a secrets manager or an environment variable, never in the repository. Each integration can be limited by the same permission system as users (ACL roles), so an ERP connector can be allowed to write products and stock but nothing else. Giving integrations the least privilege they need is the first security rule of the Admin API.

The program trades the key pair for a short-lived bearer token using the OAuth 2 client credentials grant (read-only):

Terminal
curl -X POST "https://shop.example.com/api/oauth/token" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "client_credentials",
    "client_id": "SWIAXXXXXXXXXXXXXXXX",
    "client_secret": "the-secret-shown-once"
  }'

The response contains token_type (Bearer), expires_in in seconds and an access_token. The token lifetime is short (about ten minutes by default), so a long job must request a new token when the old one is about to expire. Every following request carries the token:

Terminal
curl "https://shop.example.com/api/product?limit=5" \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1Qi..." \
  -H "Accept: application/json"

If a request returns status 401, the token is missing, malformed or expired; status 403 means the token is valid but the integration lacks the permission. Treat those two differently in your client: refresh the token on 401, and stop and report on 403.

sequenceDiagram
    participant P as Your program
    participant S as Shopware /api
    P->>S: POST /api/oauth/token (client credentials)
    S-->>P: access_token, expires_in
    P->>S: POST /api/search/product (Bearer token)
    S-->>P: 200 elements and total
    Note over P,S: token expires
    P->>S: GET /api/product (old token)
    S-->>P: 401
    P->>S: POST /api/oauth/token
    S-->>P: new access_token

A client trades its key pair for a short-lived token and fetches a new one after a 401.

Reading with the search endpoint

Besides the plain REST routes (GET /api/product, GET /api/product/{id}), every entity has a POST /api/search/{entity} endpoint. You send the criteria as JSON, and the body maps one-to-one to the Criteria object you know from PHP (read-only):

Terminal
curl -X POST "https://shop.example.com/api/search/product" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "limit": 25,
    "page": 1,
    "total-count-mode": 1,
    "filter": [
      { "type": "equals", "field": "active", "value": true },
      { "type": "range", "field": "stock", "parameters": { "lte": 5 } }
    ],
    "sort": [ { "field": "productNumber", "order": "ASC" } ],
    "associations": {
      "manufacturer": {},
      "prices": { "limit": 5 }
    },
    "includes": {
      "product": ["id", "productNumber", "stock"]
    }
  }'

The most useful keys are:

  • limit and page for paging (the Admin API has a hard upper limit per request, so always page).
  • filter: a list of filters with a type (equals, equalsAny, contains, range, not, multi, ...), a field using dot notation across associations, and a value or parameters.
  • sort: a list of fields with ASC or DESC.
  • associations: which related entities to load. Nested criteria such as limit work inside an association. Load only what you use, because every association costs time and memory.
  • includes: restrict the returned fields. This is the cheapest way to speed up large exports.
  • total-count-mode: 0 means no total (fastest), 1 exact total, 2 the "next pages exist" mode. Ask for an exact count only when you need it.

The response holds data (the records) and total. The shape of the records follows the JSON:API-like format by default; sending Accept: application/json returns simpler plain JSON.

Writing with the sync API

Creating products one request at a time is slow, and half-finished imports are painful. The sync API (POST /api/_action/sync) takes a list of operations and executes them together (read-only):

Terminal
curl -X POST "https://shop.example.com/api/_action/sync" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "indexing-behavior: use-queue-indexing" \
  -d '[
    {
      "key": "write-products",
      "action": "upsert",
      "entity": "product",
      "payload": [
        { "id": "0188a1b2c3d44e5f8a9b0c1d2e3f4a5b", "stock": 14 },
        { "id": "0188a1b2c3d44e5f8a9b0c1d2e3f4a5c", "stock": 3 }
      ]
    },
    {
      "key": "remove-old",
      "action": "delete",
      "entity": "product",
      "payload": [ { "id": "0188a1b2c3d44e5f8a9b0c1d2e3f4a5d" } ]
    }
  ]'

Each operation has a key (any name you choose, echoed back in the response), an action (upsert or delete), an entity and a payload list. Upsert creates the record when the id does not exist and updates the given fields when it does, so an import script can be run again safely. That makes the sync API a natural fit for idempotent syncs (see Idempotency).

The indexing-behavior header controls how the search and derived data indexes are updated. use-queue-indexing pushes the heavy work to the message queue (see Scheduled Tasks and the Message Queue), so the request returns sooner, at the price of data becoming visible in listings a little later. disable-indexing skips indexing entirely and is only for cases where you rebuild indexes yourself afterwards. Check the reference of your Shopware version for the full list of headers.

When you generate ids yourself, use 32-character lowercase hex strings (UUIDs without dashes), the format the DAL expects. Deriving the id from a stable key, such as a hash of the ERP article number, is a neat way to make upserts address the same record every time.

The OpenAPI reference

You do not have to guess entity fields. Each Shopware shop publishes its own API description: the OpenAPI document at /api/_info/openapi3.json and an interactive page at /api/_info/swagger.html (in a development setup). Because the schema is generated from the entity definitions, it includes the fields your own plugin added (see Custom Entities and Definitions). Use it to see exact field names, types and which fields are required.

A request builder stand-in

The first stand-in is a small PHP class that builds the search body and validates it before you send anything. It is real in what it models (the keys and filter types above) and simplified in that it supports only a few filter types, and the checks are our own, not Shopware's validation.

PHP Build and validate a search request body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Tokens and batches stand-in

The second stand-in simulates a client that gets a token, refreshes it when it expires and sends upserts in chunks. The "server" is a few lines of PHP with a clock you control, so the output never changes. Real tokens are signed JWT strings with an expiry claim; here a hash plays that role.

PHP Token refresh and chunked upserts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the counters: the token had to be renewed during the long import, and a second run left the data unchanged. In a real client you would also add a pause or backoff when the server answers with status 429 or a 5xx error, and you would log the failed key values returned by the sync response so you can retry just those.

Rate and batch advice

  • Page through reads with limit and page; use includes and only the associations you need.
  • Batch writes: a few hundred records per sync request is a sensible start. Measure, because large payloads with many associations (prices, translations, media) are much heavier than plain stock updates.
  • Write only what changed. Updating stock for 10,000 products every hour is cheap; rewriting whole product records is not.
  • Use queue indexing for imports and run a full index rebuild only when you must.
  • Back off on errors: wait, retry a few times with growing delays, then stop and alert someone.
  • Keep secrets out of logs. Never print the Authorization header or the integration secret.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which OAuth grant does a server-to-server integration use to get a token?

    An integration has an access key ID and a secret and trades them for a bearer token with the client credentials grant, without any human login.
  2. 2. An Admin API call returns 403 with a valid token. What does it mean?

    401 means the token is missing or expired (refresh it). 403 means the token is accepted but the ACL role of the integration does not allow the action.
  3. 3. Why is the sync API with upsert a good fit for imports?

    Upsert creates or updates by id, and operations are sent in one request, so repeating an import is safe and faster than single calls.
  4. 4. What does the includes key do in a search request?

    includes restricts the response fields per entity, which reduces payload size and time for large exports.
  5. 5. What should a long-running import do when the token expires halfway?

    Tokens are short-lived. Refreshing on 401 and retrying the batch keeps the import going, and idempotent upserts make the retry safe.

Summary

  • Programs use an integration (key ID and secret) and the client credentials grant to get a short-lived bearer token.
  • Refresh the token on 401, stop on 403, and give integrations only the permissions they need.
  • POST /api/search/{entity} takes the criteria as JSON: filters, sorts, associations, includes, paging and total-count-mode.
  • POST /api/_action/sync applies upsert and delete operations in bulk; upserts by stable ids make imports repeatable.
  • The shop's own OpenAPI document lists exact fields, including those from your plugins.
  • Page reads, batch writes, send only changes, back off on errors and never log secrets.

Next, move from polling to being told about changes in Apps, Webhooks and Signatures.