Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 30 ยท APIs and Integrations

The Webservice API

Use the PrestaShop Webservice: enable it, create keys with permissions, query resources in XML or JSON with filters and display, and add a custom resource from a module.

Sooner or later a shop has to talk to something else: an ERP that needs the order list, a marketplace that pulls stock, a script that updates prices. PrestaShop has shipped a REST-style interface for this for a very long time, called the Webservice. You switch it on in the back office, create an access key, decide what that key may read or change, and then talk to URLs like /api/products and /api/orders/12.

This lesson explains how the Webservice is switched on and secured, how requests are written (resources, XML and JSON, display, filter, sort, limit), and how your own module can add a resource of its own. Real calls are shown as read-only commands because this site cannot reach a PrestaShop. The stand-ins are a small resource server that follows the same query rules and a permission-aware request handler, so you can experiment with the syntax. The Webservice is the older interface; PrestaShop 9 also has a newer OAuth2-based Admin API, and the classic Webservice is still available.

Turning it on

In the back office, open Advanced Parameters > Webservice:

  1. Enable the Webservice (a switch at the top of the page).
  2. Add a new key. PrestaShop proposes a random 32-character key; use it, do not invent a short one.
  3. Give the key a description, such as the name of the integration that will use it.
  4. In the permissions table, tick the verbs this key may use on each resource: GET (read), PUT (update), POST (create), DELETE, HEAD.
  5. Save.

Give every integration its own key with the smallest set of permissions it needs. A stock synchronizer needs GET and PUT on stock resources and nothing else. If one key leaks, you can revoke it without breaking the others.

Always use HTTPS. The key is a secret (it is the password), and without TLS it travels in clear text. Web servers other than Apache need a rewrite rule that sends /api/ requests to the shop's webservice dispatcher; the standard nginx configuration for PrestaShop includes it.

Making requests

The base URL is https://your-shop.example/api/. The key is sent as the user name of HTTP Basic authentication, with an empty password. A first request shows the resources the key may use:

Terminal
# read-only: cannot run on this site
curl -u 'YOUR32CHARACTERKEYGOESHERE:' 'https://your-shop.example/api/'

You can also put the key in the query as ws_key=..., but a key in a URL ends up in logs and browser history, so prefer the header.

By default the answer is XML. Ask for JSON with output_format=JSON (output only) or io_format=JSON (input and output), or send the Output-Format: JSON header:

Terminal
# list the first 5 products, only some fields, as JSON (read-only)
curl -g -u 'YOUR32CHARACTERKEYGOESHERE:' \
  'https://your-shop.example/api/products?display=[id,name,price]&limit=5&output_format=JSON'

The -g flag stops curl from treating the square brackets as its own range syntax.

flowchart LR
    C["Client<br/>key + request"] --> A{"Webservice enabled?<br/>key valid?"}
    A -->|"no"| E1["401"]
    A -->|"yes"| P{"Key may use this<br/>verb on this resource?"}
    P -->|"no"| E2["405"]
    P -->|"yes"| R["Resource class<br/>(ObjectModel)"]
    R --> O["XML or JSON answer"]

Every request is checked for the key and for the permission on the resource before the data layer is touched.

Resources

A resource is a kind of data the Webservice exposes: products, categories, customers, addresses, orders, order_histories, carts, stock_availables, languages, taxes, and many more. A request to /api/orders lists orders; /api/orders/12 returns order 12. A list with no extra options contains just the ids and links to each record, which is intentionally light.

Reading what you need: display

  • display=full returns all fields of every record.
  • display=[id,name,price] returns only these fields.

Use the smallest list you can. Asking for full on thousands of products is slow for both sides.

Filtering: filter[field]

Filters use square brackets around the value, and the position of the brackets selects the matching mode:

Request Meaning
filter[id_customer]=[12] field equals 12
filter[id]=[1,10] field between 1 and 10
filter[id]=[3|8|15] field is one of these values
filter[name]=%[shirt]% field contains "shirt"
filter[name]=[shirt]% field begins with "shirt"
filter[name]=%[shirt] field ends with "shirt"

You can combine several filters; they are joined with AND. Only fields that the resource exposes can be filtered.

Sorting and paging

  • sort=[name_ASC] or sort=[price_DESC,id_ASC] sets the order.
  • limit=10 returns at most 10 records; limit=20,10 skips 20 and returns the next 10.

Read big collections in pages, and sort by a stable field (like the id) so a page boundary does not skip or repeat records when data changes.

Reading, creating, updating

GET reads. To create, fetch a blank skeleton with ?schema=blank (or ?schema=synopsis for a description of the fields), fill it in and send it with POST. To update, GET the record, change the fields you need and send the whole document back with PUT; fields you leave out of a PUT can be reset. DELETE removes a record. Writes go through the same ObjectModel validation as the back office, so an invalid value is rejected with a 400 and a message that names the field.

A resource server you can run

The real Webservice reads from PrestaShop. The stand-in below mimics only the query rules over a small SQLite table: display, filter modes, sort and limit, and the default "ids only" list. Field names are checked against a whitelist (so nobody can sort or filter on a column they should not see), and values are bound as parameters. The output shape is simplified JSON; the real XML and JSON structures have more detail.

PHP Stand-in: display, filter, sort and limit over a resource

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.

Two things to carry over to real work. A list without display returns ids only, so you normally ask for the fields you need. And an unknown or sensitive field name is a 400, not something to pass to SQL.

Permissions and formats you can run

The second stand-in models the front of the service: the key lookup, the per-resource verb table, status codes, and the two output formats. XML here is a simplified version of the real structure (the real one declares the xlink namespace and adds links on every node).

PHP Stand-in: key permissions, status codes, XML and JSON output

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.

The reporting key can read orders but cannot write products, and the stock key cannot see orders at all: least privilege per integration. In the real service the status text and messages differ in detail; the principle is the same.

Adding your own resource

A module can expose its own data through the Webservice with the addWebserviceResources hook. It returns the new resources, keyed by their URL name, each pointing to an ObjectModel class:

PHP
// modules/acmenote/acmenote.php (read-only, shortened)
public function install(): bool
{
    return parent::install()
        && $this->registerHook('addWebserviceResources');
}

public function hookAddWebserviceResources(array $params): array
{
    return [
        'acme_notes' => [
            'description' => 'Customer notes',
            'class' => 'AcmeNote',
        ],
    ];
}
PHP
// modules/acmenote/classes/AcmeNote.php (read-only, shortened)
class AcmeNote extends ObjectModel
{
    public $id_customer;
    public $content;

    public static $definition = [
        'table' => 'acme_note',
        'primary' => 'id_acme_note',
        'fields' => [
            'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true],
            'content' => ['type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 500],
        ],
    ];

    protected $webserviceParameters = [
        'objectsNodeName' => 'acme_notes',
        'objectNodeName' => 'acme_note',
        'fields' => [
            'id_customer' => ['xlink_resource' => 'customers'],
        ],
    ];
}

Remember three things:

  1. The class must be loaded when the Webservice runs, so require the file from the main module file (or use an autoloader), as in Anatomy of a Module.
  2. The new resource appears in the permission table of the key page only after the module is installed and the hook is registered. Then tick the verbs for each key that should use it.
  3. Validation is the ObjectModel's. The validate and size entries in $definition protect writes. Expose only what integrations need, and treat anything the resource shows as readable by every key that has GET on it.

Security checklist

  • Serve the API only over HTTPS and keep keys out of URLs where you can.
  • One key per integration, minimal verbs, and delete keys of integrations you stopped using.
  • Limit the number of records per call from your side, and read with display and limit.
  • Do not store keys in code that goes to a public repository.
  • Treat input from API clients like any other input; see Security in Modules.

For shared ideas that apply to every integration, such as retries and avoiding duplicate writes, read idempotency.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How is the Webservice key normally sent?

    The key is the Basic auth user name. A ws_key query parameter also works, but it ends up in logs and history, so the header is preferred.
  2. 2. What does filter[name]=%[shirt]% match?

    Percent signs outside the brackets act as wildcards on both sides, so the value must appear somewhere in the field.
  3. 3. What does a plain GET of /api/products (no display parameter) return?

    Lists are light by default. Add display=[field,field] or display=full to get field values.
  4. 4. Which hook lets a module add its own Webservice resource?

    The module registers addWebserviceResources and returns a list of resources, each naming an ObjectModel class.
  5. 5. Why give each integration its own key?

    Separate keys with minimal permissions limit the damage of a leak and make revocation simple.

Summary

  • Enable the Webservice under Advanced Parameters, create a long random key per integration and tick only the verbs and resources it needs.
  • Send the key as the Basic auth user name over HTTPS; ask for JSON with output_format=JSON.
  • Shape results with display, filter[field], sort, and limit; lists show ids only unless you ask for fields.
  • Create with schema=blank and POST, update with a full PUT, and expect ObjectModel validation errors as 400 answers.
  • A module adds a resource with the addWebserviceResources hook and an ObjectModel class that declares $webserviceParameters.

Next: The Admin API in PrestaShop 9