
Understanding the REST API Prestashop
- Tutorial
- Recovery mode

The other day, the task was to import goods into Prestashop. I had no business with this CMS before, and therefore I began to look for the usual APIs for adding / changing products. Imagine my surprise when I did not find them, well, or did not look very hard. The solution described here did not fit unambiguously, since it required working with product combinations, and a bunch of other parameters. I note that the option of changing the kernel files or creating a bunch of files overriding the system classes were discarded immediately. And then I drew attention to the REST API, as I understand it appeared recently, and there is little information on it, but it seemed to me the best option. I note that in this material I do not set a goal to repeat what is described in the documentation, but only to streamline the information and supplement some points.
Activation of the REST interface in the store
Activation is described in some detail on the documentation website , so we won’t especially stay on this point. The main thing is not to forget to activate the CNC, otherwise nothing will work. After activation, you can check the operation of the API at yoursite.ru/api/ .
Basic concept
Communication with the store takes place entirely in XML, except for the case of loading a picture, which we will consider below. The API system is built on the principle of CRUD (Create, Read, Update, Delete), which when translated into the HTTP request language gives us the following:

Most of the communication with the store will occur through the PSWebServiceLibrary class written by one of the community members. You can download it from the link, or find on the documentation pages .
A list of all possible methods, and an explanation of the types of variables lies here doc.prestashop.com , in fact this is the most necessary document from all the documentation, however, following the link yoursite.ru/api/ and entering the previously created access key as a login, you can resemble the links specified in the attribute “xlink: href”, and visually look at the structure of the API.
Create items
To create any element of the store’s structure (we’ll take the product as an example), we first need to get an XML document blank. To do this, add? Schema = synopsis to the product list link. The following is an example of creating an item through the PSWebServiceLibrary class:
//Создаем обьект класса указав url магазина и созданный секретный ключ из админки
$webService = new PrestaShopWebservice($shop_url, $secret_key, $debug);
//Обратите внимание, метод products без ?schema=synopsis выводит список товаров
$xml_product = $webService->get(array('resource' => 'products?schema=synopsis'));
//После получения заготовки заполняем поля XML
$resources_product = $new_product->children()->children();
$resources_product->name->language[0][0] = "Test product";
$resources_product->link_rewrite->language[0][0] = "tstproduct";
$resources_product->active = 1;
$resources_product->available_for_order = 1;
$resources_product->show_price = 1;
$resources_product->out_of_stock = 2;//Если товара нет на складе, действие по умолчанию
//Если не указать категорию, товар не будет виден в админке, это важно
$resources_product->associations->categories->category[0]->id = 1;
//Отправляем заполненную заготовку на добавление
$created_product = $webService->add(array('resource' => 'products', 'postXml' => $new_product->asXML()));
In the variable $ created_product, we have an XML product card in case of success, or a card with a description of the error. This statement is true for creating any elements other than pictures.
If you look at the debug output, you can see that the class is crawling behind the workpiece at the address yoursite.ru/api/products/?schema=synopsis using the GET method and adds the goods using the POST method at yoursite.ru/api/products/ .
Create Pictures
Unfortunately, there is no ready-made method for loading pictures in the PSWebServiceLibrary class, so I had to trick my own. For good, it would be necessary to introduce it into the aforementioned class, but there was neither the strength nor the time. Therefore, we will upload pictures ourselves. Also, the URL for downloading images is not just / api / images / as for example in the case of goods (/ api / products /) but, if it’s a product picture, / api / images / products / $ product_id /. This feature was identified experimentally.
Product image download code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $shop_url."api/images/products/".$product_id."/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $secret_key.":");
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => '@my_image.png'));
$response= curl_exec($ch);
In the $ response variable, we will end up with either the picture that we uploaded, or an XML error card. Here you need to check for a loading error by checking the server response code, or the response text.
It should be noted that it is impossible to get the id of the downloaded image, for this I immediately after loading the image made a selection of all images of the specified product (/ api / images / products / $ product_id /) and the one with the largest id is ours.
Editing Elements
Editing takes place in much the same way as creating, except that at the beginning we get not a blank card for the product, but the product itself. After modifying the fields, we simply change the method of the PSWebServiceLibrary class from add to edit with the same parameters.
$product = $webService->get(array('resource' => 'products', 'id' => $product_id));
$mod_product = $webService->edit(array('resource' => 'products', 'id' => $product_id, 'putXml' => $product->asXML()));
Delete items
Deletion occurs using the syntax similar to the get method, but only using the delete method
$webService->delete(array('resource' => 'products', 'id' => $product_id));
Nothing will be returned in response.
Catching errors
If we use the PSWebServiceLibrary class, then each call to its methods must be wrapped in a try ... catch block, because if a server fails, it will generate a Fatal error of the PrestaShopWebserviceException type. More details below:
try {
//Создаем обьект класса указав url магазина и созданный секретный ключ из админки
$webService = new PrestaShopWebservice($shop_url, $secret_key, $debug);
//Получаем список товаров
$products = $webService->get( array( 'resource' => 'products' ) );
} catch ( PrestaShopWebserviceException $ex ) {
$trace = $ex->getTrace(); //Получаем информацию об ошибке
$errorCode = $trace[ 0 ][ 'args' ][ 0 ]; //Получаем код ошибки
if ( $errorCode == 401 ) //Выводим сообщение на экран
echo 'Bad auth key';
else
echo 'Other error :
' . $ex->getMessage();
}
Filters, sorting, limits
All of the above is pretty well written in the documentation . And there is no point in repeating this here. Just do not forget that this opportunity exists. The filter can be specified by any field from the XML card by specifying the name of the tag containing the value for the filter.
Underwater rocks
Carefully check the value for compliance with the requirements of the field type, one discrepancy in an insignificant field will lead to the inability to complete a chain of actions. All field types and regular expressions for checking compliance are located here doc.prestashop.com .
PS: If anyone has any questions, I will gladly answer and supplement the material.