Jump to content

Prestashop Webservice API - JSON


Joao Conde

Recommended Posts

Greetings,

I am trying to use the Webservice API. I have successfully installed Prestashop locally with the demo products. I have enabled the Webservice module and created an API key.

I am issuing the following request via Postman:

GET {{webservice_url}}/api/products?output_format=JSON

And I am getting a successful response with a 200 status code that returns me the HTML page for the products instead of a JSON or even XML body.

I have the Auth headers correctly set as well as the Content-Type to application/json

Any ideas or clues of what might be missing?

Thanks in advance.

Link to comment
Share on other sites

On 11/27/2023 at 1:38 AM, Joao Conde said:

GET {{webservice_url}}/api/products?output_format=JSON


Hi,

It would be really helpful if you could paste your complete code so that we can check what the issue there. If you are looking for a reference below is the code you can refer to get the product

$products = $this->executeCurl('B2C', 'products', 'GET', $data = array('id' => $value['id_product']));

You can define the function like below

public function executeCurl($type, $mapping_type, $method, $data = array())
    {
        $curl = curl_init();

        if ($type == 'B2C') {
            if ($method == 'GET') {
                if (empty($data)) {
                    $url = Configuration::get('KBORDERSYNC_B2C_STORE_URL') . "api/" . $mapping_type . "/&ws_key=" . Configuration::get('KBORDERSYNC_B2C_KEY') . "&output_format=JSON";
                } else {
                    if ($data['id'] != 0) {
                        $url = Configuration::get('KBORDERSYNC_B2C_STORE_URL') . "api/" . $mapping_type . "/" . $data['id'] . "/&ws_key=" . Configuration::get('KBORDERSYNC_B2C_KEY') . "&output_format=JSON";
                    }
                }
            } else {
                $url = Configuration::get('KBORDERSYNC_B2C_STORE_URL') . "api/" . $mapping_type . "&ws_key=" . Configuration::get('KBORDERSYNC_B2C_KEY') . "&output_format=JSON";
            }
        } else {
            $store_url = Context::getContext()->shop->getBaseURL(true);
            if ($method == 'GET') {
                if (empty($data)) {
                    $url = $store_url . "api/" . $mapping_type . "/&ws_key=" . Configuration::get('KBORDERSYNC_B2B_KEY') . "&output_format=JSON";
                } else {
                    if ($data['id'] != 0) {
                        $url = $store_url . "api/" . $mapping_type . "/" . $data['id'] . "/&ws_key=" . Configuration::get('KBORDERSYNC_B2B_KEY') . "&output_format=JSON";
                    }
                }
            } else {
                $url = $store_url . "api/" . $mapping_type . "&ws_key=" . Configuration::get('KBORDERSYNC_B2B_KEY') . "&output_format=JSON";
            }
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        if (strtolower($method) == 'post') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        } elseif (strtolower($method) == 'put') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        } else {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }

        $response = json_decode(curl_exec($curl), 1);
        $curl_error = curl_error($curl);
        curl_close($curl);
        if (!$curl_error) {
            return $response;
        } else {
            throw new Exception("Error in calling the " . $mapping_type . " API on " . $type);
        }
    }

 

Again that depends on the use case. Let us know what you are trying to do so that we can assist you accordingly.

Link to comment
Share on other sites

Hi!

No code yet, just testing the API with postman.

Trying to get a list of all the products from the API.

I can convert it to a curl request:

curl -X GET "http://localhost:8000/api/products?output_format=JSON" -H "Authorization: Basic WTFLS0c3VlZVM1Y1M1lDVFhURjFBV1FNVDQyVTVESVE6"

 

I think something is missing and then I am just sent back the index.html page of the site.

Link to comment
Share on other sites

Hi,

Yes, for using web services you need to pass parameters as well which I can't see here.

ws_key params should be there and this key you can get this from the Advance Parameters ->  Webservices page where you need to click on Add a web service API key and inside it you need to allow permissions that the web service can provide.

Check the snap attached 

image.thumb.png.744c601bdc41ddde5e2f55bfa0f22c56.png

Link to comment
Share on other sites

Hi,

I have generated the key like that yes, and gave it correct permissions. I am passing the key both in the Auth header as well as in the ws_key param.

I think the problem has something to do with this from the docs:

The endpoint /api is reachable if URL is correctly rewritten to use it. For httpd, this is done by the .htaccess which means you need to make sure httpd is processing this file (it needs mod_rewrite enabled and VirtualHost must have AllowOverride All).

I am using the PHP built-in server to serve my local site with:

php -S 127.0.0.1:8000

Could it be that? That /api calls are just not being properly rewritten and so I get the index page? If so, how can I do so for PHP's built-in server?

 

Link to comment
Share on other sites

On 11/29/2023 at 6:23 PM, Joao Conde said:

Hi,

I have generated the key like that yes, and gave it correct permissions. I am passing the key both in the Auth header as well as in the ws_key param.

I think the problem has something to do with this from the docs:

The endpoint /api is reachable if URL is correctly rewritten to use it. For httpd, this is done by the .htaccess which means you need to make sure httpd is processing this file (it needs mod_rewrite enabled and VirtualHost must have AllowOverride All).

I am using the PHP built-in server to serve my local site with:

php -S 127.0.0.1:8000

Could it be that? That /api calls are just not being properly rewritten and so I get the index page? If so, how can I do so for PHP's built-in server?

 

You need to check if you have .htaccess file in your server root directory and in the webservices directory and whether the permissions are denied or allowed by default it's not allowed to make sure no one can modify the files from outside.

The code inside the htaccess file is generally like below

<IfModule mod_headers.c>
	<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg)$">
		Header set Access-Control-Allow-Origin "*"
	</FilesMatch>

    <FilesMatch "\.pdf$">
      Header set Content-Disposition "Attachment"
      Header set X-Content-Type-Options "nosniff"
    </FilesMatch>
</IfModule>

<Files composer.lock>
    # Apache 2.2
    <IfModule !mod_authz_core.c>
        Order deny,allow
        Deny from all
    </IfModule>

    # Apache 2.4
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</Files>
#If rewrite mod isn't enabled
ErrorDocument 404 /prestashop/PS_8.1.0/store1/index.php?controller=404

so at the bottom, you can see that in case rewrite mod isn't enabled we have redirected it to index.php and in your case as well this will be the only scenario. You can contact your store developer to update the same.

Let us know in case of any queries.

Link to comment
Share on other sites

  • 1 month later...
  • 6 months later...
  • 3 weeks later...
On 8/10/2024 at 12:47 PM, fauxhandle said:

I get some strong difficulties to make well working the API also.
Getting examples and tutorials with "working as it" code examples could be a great addition in the documention.

Hi @fauxhandle,

Could you please elaborate on the difficulties faced while working with APIs?

Edited by Babu Amkaian (see edit history)
Link to comment
Share on other sites

I think your previous message is clear enough. Basically, the tutorial part in the PrestaShop API documentation is not really a comprehensive tutorial - there's a lack of concrete, working code examples. And having working examples to demonstrate how to actually use the API to perform common tasks like showing basics of the life-cycle of a cart couls be a great addition to the documentation.

  • Like 1
Link to comment
Share on other sites

Okay @fauxhandle, I will prepare a document with clear details on how to implement the web service API for the following action items, including sample code snippets:

How to create content on PrestaShop.

How to update content.

How to use the PATCH method to update content.

How to delete content on PrestaShop.

How to retrieve all content for a specific content type that we have created.

I will document this and provide an update here shortly.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...