The Magento REST API and bearer tokens
How other systems talk to a Magento 2.4.9 store: the REST URL structure, the four kinds of access (integration, admin, customer and guest), an integration created in the admin with only the resources it needs, its access token used as a bearer token, and curl calls for each token type. At the end the integration is deleted, so its tokens stop working.
Downloads
Every call from the video as one script, and the request bodies for the admin and customer tokens. Put your own login in the JSON files on the server (chmod 600), so passwords are never typed on the command line or kept in the shell history.
What the REST API is
An ERP, a PIM, a marketplace or your own app reads and changes the store over HTTPS. Every call is a URL under /rest/V1, a method (GET reads, POST creates, PUT updates, DELETE removes) and JSON in and out.
| URL | Meaning |
|---|---|
/rest/V1/products | The default store view |
/rest/de/V1/products | The store view with the code de: names, prices and texts of that view |
/rest/all/V1/products | All store views at once (for saving global values) |
/swagger | Every endpoint, browsable. Only in developer mode: in production mode it returns 404 |
/rest/all/schema?services=all | The same list as JSON, in every mode. With a token it lists what that token can reach |
Which token?
Every call that needs a permission sends a token in the header: Authorization: Bearer <token>.
| Token | Lifetime | Use it for |
|---|---|---|
| Integration access token | Does not expire (until you reauthorize or delete the integration) | Server-to-server connections: ERP, PIM, marketplace. Recommended; reaches only the resources you tick |
Admin token: POST /V1/integration/admin/token | 4 hours | Quick tests. Acts with the admin user’s role; with 2FA it needs the current code |
Customer token: POST /V1/integration/customer/token | 1 hour | Apps and headless storefronts acting as one customer (/V1/customers/me, carts, orders) |
| Guest | no token | Public endpoints: countries, guest carts, the storefront catalog search |
Lifetimes: Stores › Configuration › Services › OAuth › Access Token Expiration.
Creating an integration
- System › Extensions › Integrations › Add New Integration.
- Name:
ERP connector, Email: a contact address. Leave Callback URL and Identity link URL empty: they are for extensions that connect by themselves (OAuth handshake). - Your Password: your own admin password, to confirm it is you.
- API tab: Resource Access: Custom. Tick only what the system needs. In the video: Catalog › Inventory › Products and Stores › Settings › All Stores. Save.
- In the grid the integration is Inactive: click Activate, check the list of resources, Allow.
- Magento shows four values: Consumer Key, Consumer Secret, Access Token and Access Token Secret. Treat them like a password. A bearer call uses only the Access Token. Done.
To save the access token straight into a file on the server instead of copying it:
# on the server, to save the integration's access token in a file (instead of copying it from the popup) sudo mariadb magento -Nse "select t.token from oauth_token t join integration i on i.consumer_id=t.consumer_id where i.name='ERP connector' and t.type='access'" > erp-token.txt chmod 600 erp-token.txt
Allowing bearer tokens
Since Magento 2.4.4 an integration token is not accepted as a bearer token by default: the call returns 401, The consumer isn’t authorized to access %resources. Without the setting, every request must be signed with OAuth 1.0a using all four values.
Stores › Configuration › Services › OAuth › Consumer Settings › Allow OAuth Access Tokens to be used as standalone Bearer tokens: Yes, then Save Config. Or from the command line:
cd /var/www/magento # the same setting from the command line sudo -u magento bin/magento config:set oauth/consumer/enable_integration_as_bearer 1 # token lifetimes in hours (defaults: customer 1, admin 4) sudo -u magento bin/magento config:set oauth/access_token_lifetime/customer 1 sudo -u magento bin/magento config:set oauth/access_token_lifetime/admin 4
The calls
Every call from the video. -g stops curl from reading the square brackets of searchCriteria[pageSize] as a pattern; jq picks the fields.
#!/bin/bash
# Magento 2.4.9 REST API calls from MageBooster Lesson 8. Change U to your store; needs curl and jq.
U=https://www.example.com/rest
# the integration's access token, saved in a file (chmod 600), so it is never typed or shown
TOKEN=$(cat erp-token.txt)
echo "${TOKEN:0:4}...${TOKEN: -4}"
# guest: no token
curl -s $U/V1/directory/countries/GB | jq '.full_name_english'
# needs a permission: 401 without a token
curl -s $U/V1/store/storeViews | jq
# integration token as a bearer token (401 until Services > OAuth allows it)
curl -s -H "Authorization: Bearer $TOKEN" $U/V1/store/storeViews | jq -c '.[] | {code, name}'
# products: page size 1, the total and the first name (-g: the square brackets are not a curl pattern)
curl -sg -H "Authorization: Bearer $TOKEN" "$U/V1/products?searchCriteria[pageSize]=1" | jq '.total_count, .items[0].name'
# every endpoint this token can reach (works in production mode, unlike /swagger)
curl -s -H "Authorization: Bearer $TOKEN" "$U/all/schema?services=all" | jq '.paths | length'
# admin token (4 hours). With 2FA on, Magento answers with the provider endpoints instead
curl -s -X POST -H "Content-Type: application/json" -d @admin-login.json $U/V1/integration/admin/token | jq
# with Google Authenticator: username, password and otp (the current 6-digit code)
# curl -s -X POST -H "Content-Type: application/json" -d @admin-login-otp.json $U/V1/tfa/provider/google/authenticate
# customer token (1 hour) and the customer's own account
CTOKEN=$(curl -s -X POST -H "Content-Type: application/json" -d @customer-login.json $U/V1/integration/customer/token | jq -r .)
curl -s -H "Authorization: Bearer $CTOKEN" $U/V1/customers/me | jq '{firstname, lastname, email}'
| Call | Answer in the video |
|---|---|
| Countries, no token | “United Kingdom” |
| Store views, no token | 401 |
| Store views, integration token, setting off | 401 |
| Store views, integration token, setting on | default, admin, de |
| Products, page size 1 | 2040 products, the first one “Joust Duffle Bag” |
| Schema paths | 148 with the token, 88 without |
Admin token and 2FA
With two-factor authentication on (the default), /V1/integration/admin/token answers Please use the 2fa provider-specific endpoints to obtain a token. Post username, password and otp (the current code from the authenticator app) to /V1/tfa/provider/google/authenticate instead. The token lasts 4 hours and acts with the admin user’s role, so for scripts and connections an integration is the better choice.
Customer token
POST /V1/integration/customer/token with the customer’s email and password returns a token for one hour. With it, /V1/customers/me returns that customer’s own account (in the video: Alex Morgan from Lesson 7), and the /V1/carts/mine endpoints work on their cart. A customer token never reaches admin resources.
Reauthorize and delete
System › Extensions › Integrations: Reauthorize issues new tokens (use it when a token leaks), the bin icon (Remove) deletes the integration. After deleting, the same call returns 401 at once.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
| 401 with an integration token | The bearer setting is off (Services › OAuth › Consumer Settings), the integration is not active, or the resource is not ticked on its API tab. |
| 401 with an admin or customer token | The token expired (4 h / 1 h) or was made on another store. Ask for a new one. |
| /swagger returns 404 | Production mode. Use /rest/all/schema?services=all, or a developer-mode copy of the store. |
| curl: bad range in URL | Add -g (globoff) for searchCriteria[...], or encode the brackets as %5B and %5D. |
| Admin token: use the 2fa provider-specific endpoints | Two-factor authentication is on: use /V1/tfa/provider/google/authenticate with otp. |
| Values differ per store view | Put the store view code after /rest: /rest/de/V1/.... |
Next lesson
Lesson 9: your own free theme: we build a Luma child theme and give each store view its own theme.
▶ Watch every MageBooster lesson on YouTube: all lessons in order · subscribe to the channel
