Introduction

You are just a few simple steps away from working with the Allegro REST API. If you haven’t tried it yet, this tutorial will show all the basics you need to know to start working with our API.

This tutorial will show you how to:

The code samples are written in plain PHP 7, without any additional libraries or frameworks. This should allow people who don’t normally use PHP to be able to understand them quite easily. If you want to run this code on your own, you should install a PHP interpreter.

Reading this tutorial and completing the exercises should take you around 15 minutes.

How to register a new application

To start using the Allegro REST API, you need to first register an application on our developer’s portal. In this tutorial we will use Allegro’s sandbox environment.

  • Navigate to https://apps.developer.allegro.pl.allegrosandbox.pl/new and sign in with a sandbox Allegro account. If you don’t have an account on the sandbox environment you can register one on the registration page.
  • Fill in the form with information about your new application, e.g.:

    • Nazwa aplikacji (application name): “My test app <login>
    • Opis aplikacji (description) can be left empty. It’s not presented to the users. You can use it to tell apart your different applications if you have more than one.
    • For now do not change the rodzaj aplikacji option (application type), and in the field Adresy URI do przekierowania (redirect URIs) put http://localhost:8000.
information

Users should be able to identify your app easily - make sure you give it a distinctive and meaningful name. Remember that this name should be unique - you can add your Allegro login to the name to ensure this.

information

You can learn more about application types and redirect URIs in this article.

  • Accept the terms and conditions of the Allegro API and click the button.

If all went well, you should see your new application in the list. Your application will be assigned a unique Client ID and a long Client Secret. The Client ID is a kind of a login - we use it to identify your application in requests sent to the Allegro API. Should you ever run into any issues while using our API please provide the Client ID when using our contact form or on the message board. This will help us find the cause of the problem more easily and solve your issue faster. The Client Secret is your secret password and should be kept safe. You will need it to obtain access tokens to our API. Thanks to this password we really know it is you when we receive a request from your application.

How to obtain an access token

After you register an application, it’s time to obtain an access_token - a token which identifies your application and possibly a user. All requests sent to the Allegro API need to have an access token.

information

At Allegro we use the OAuth 2.0 standard for authorization. If you’re familiar with OAuth you will quickly grasp the flows used in our API.

The token we are about to generate is a client credentials token. This means that it identifies the application but does not identify any Allegro user. You can use it to request data from any resources that serve public data, e.g. from GET /offers/listing.

information

Resources which serve public data are marked in our reference documentation. In the “Authorization” section they have the type bearer-token-for-application.

To obtain an access token, you will need the Client ID and the Client Secret of the application created before. Try to write a simple script which will acquire the token. Copy the following code to a file, e.g. api_allegro.php:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

function getAccessToken(): String
{
    $authUrl = "https://allegro.pl.allegrosandbox.pl/auth/oauth/token?grant_type=client_credentials";
    $clientId = "...";
    $clientSecret = "...";

    $ch = curl_init($authUrl);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERNAME, $clientId);
    curl_setopt($ch, CURLOPT_PASSWORD, $clientSecret);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $tokenResult = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($tokenResult === false || $resultCode !== 200) {
        exit ("Something went wrong");
    }

    $tokenObject = json_decode($tokenResult);

    return $tokenObject->access_token;
}

function main()
{
    echo "access_token = ", getAccessToken();
}

main();
 

Set the values of $clientId and $clientSecret properly and run the script. You can do this from the command line:

 
 php api_allegro.php
 

If no errors occured, you will see the value of the access token in the form of a long string, e.g.:

 
 access_token = eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhbGxlZ3JvX2FwaSJdLCJleHAiOjE1NTI2OTg5NjgsImp0aSI6IjI4ZDg5YmRkLTkxZTItNGY2MC1iZDZlLTEwNTE5YzZiY2IwYyIsImNsaWVudF9pZCI6ImMyODcyYjc5NTdjOTQ1N2Q5NTNhNDZkNjNlZDJlZjBjIn0.moK0uSTnqZ_WDpi0CU70ph4S7tzbaURLWDM57txzs5yn-CHBEz1rjTfGTw4RvZy77u49NbJs9NE92mMbH2C6LIntJ5u6Ii9PnagTDnAKB8yBHJ3FCjpFi8ZqkVrodYHLGfz3n7i5b3yfXNq7avdwd477MxPJyGpJ1SjoFrPg4tD4zyRkZ79I-BTh3Ivy2sfdMtHL0CUUTL-x-zG9pjffO1h7lwFVaU15AcapU4uHlJbQYhfsXmrPhWUknOkaspTc_be87rZbgqlqbn8GXcXPrQOen68mGxSIYF9CpOqiJpofnQsQriAB3IG7z6IVYeCP0wIG2eXIYFkox2xfhhV0TQ
 

Allegro serves tokens in the JWT format. You can read more about JWT in the specification.

There are a few different pieces of information encoded in the token: the ID of the owning user, the Client ID and the validity date of the token, among others. If you want to browse all the token’s fields you have to decode it. You can paste it into an online form available at jwt.io.

The access token is not the only field in the response of the resource we have just used. In the above code you can add a command var_dump($tokenObject); in line 26 to check what other fields are in the response.

information

You can learn more about authorization and tokens from the article Authentication and authorization.

Another step completed - we have the access token so we can send the first API request.

How to send a simple request for data

Let’s try to get the list of main Allegro categories. Add the following code to your php file, below the authorization method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php

function getMainCategories(String $token): stdClass
{
    $getCategoriesUrl = "https://api.allegro.pl.allegrosandbox.pl/sale/categories";

    $ch = curl_init($getCategoriesUrl);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
                 "Authorization: Bearer $token",
                 "Accept: application/vnd.allegro.public.v1+json"
    ]);

    $mainCategoriesResult = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($mainCategoriesResult === false || $resultCode !== 200) {
        exit ("Something went wrong");
    }

    $categoriesList = json_decode($mainCategoriesResult);

    return $categoriesList;
}

Note the lines number 11 and 12. We set there two headers which have to be present in every request to our API:

  1. The Authorization header identifies your aplication and possibly the user. As Allegro API uses Oauth 2.0 the value of this headers must start with the word Bearer followed by one space and then the value of the token obtained in the previous step.

  2. The Accept header describes in what format the data should be returned. The value that can be used in this header can be different for each resource. You can find the proper value in our reference documentation. E.g. for the resource GET /sale/categories, in the Responses table you can find the value application/vnd.allegro.public.v1+json - this is the type of the response you can accept from this resource.

Next, change the body of the main() method to the following:

1
2
3
4
5
6
7
8
<?php

function main()
{
    $token = getAccessToken();
    var_dump(getMainCategories($token));
}

Save the changes and once again run the script, e.g. from the console, using:

 
 php api_allegro.php
 

If no error occured, you will see the following output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
object(stdClass)#29 (1) {
   ["categories"]=>
   array(14) {
     [0]=>
     object(stdClass)#1 (5) {
       ["id"]=>
       string(1) "5"
       ["name"]=>
       string(12) "Dom i Ogród"
       ["parent"]=>
       NULL
               ["leaf"]=>
               bool(false)
       ["options"]=>
       object(stdClass)#2 (3) {
         ["variantsByColorPatternAllowed"]=>
         bool(true)
         ["advertisement"]=>
         bool(false)
         ["advertisementPriceOptional"]=>
         bool(false)
       }
     }
     [1]=>
     object(stdClass)#3 (5) {
       ["id"]=>
       string(5) "11763"
       ["name"]=>
       string(7) "Dziecko"
       ["parent"]=>
       NULL
       ["leaf"]=>
       bool(false)
       ["options"]=>
       object(stdClass)#4 (3) {
         ["variantsByColorPatternAllowed"]=>
         bool(true)
         ["advertisement"]=>
         bool(false)
         ["advertisementPriceOptional"]=>
         bool(false)
       }
     }
     
     // ...
   }
}

Well done! You have just queried the Allegro API and got some data back. You have a list of the main Allegro categories. However, to list an offer you will need a concrete category, which we call a leaf category. Note the above response. Each category has the leaf parameter assigned. Find one that has the parameter set to true - you will be able to use it to list offers.

How to get the details of a specific Allegro category

Getting the list of leaf categories is not much more difficult than obtaining the main categories. All you have to do is to add a query parameter parent.id, which indicates from which category you want to get the results.

Write a simple loop that will find the first leaf category. Copy the following code to your php file, just after the getMainCategories method:

information

The loop used here is a very simple one. It will find the very first leaf category in the tree. In a real-world application make sure that your users can properly traverse the categories tree to easily find the appropriate category.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

function findFirstLeaf(String $parentId, String $token): stdClass
{
    $getCategoriesUrl = "https://api.allegro.pl.allegrosandbox.pl/sale/categories";
    $query = ['parent.id' => $parentId];
    $getChildrenUrl = $getCategoriesUrl . '?' . http_build_query($query);

    $ch = curl_init($getChildrenUrl);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token",
        "Accept: application/vnd.allegro.public.v1+json"
    ]);

    $categoriesResult = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($categoriesResult === false || $resultCode !== 200) {
        exit ("Something went wrong");
    }

    $categoriesList = json_decode($categoriesResult);
    $category = $categoriesList->categories[0];

    if ($category->leaf === true) {
        return $category;
    } else {
        return findFirstLeaf($category->id, $token);
    }
}

Change the body of the main function to:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

function main()
{
    $token = getAccessToken();
    $mainCategories = getMainCategories($token);

    $firstLeafCategory = findFirstLeaf($mainCategories->categories[0]->id, $token);

    var_dump($firstLeafCategory);
}

After running the script you should get the leaf category:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
object(stdClass)#104 (5) {
  ["id"]=>
  string(6) "111852"
  ["name"]=>
  string(21) "Akcesoria dekarskie  "
  ["parent"]=>
  object(stdClass)#105 (1) {
    ["id"]=>
    string(4) "1521"
  }
  ["leaf"]=>
  bool(true)
  ["options"]=>
  object(stdClass)#106 (3) {
    ["variantsByColorPatternAllowed"]=>
    bool(true)
    ["advertisement"]=>
    bool(false)
    ["advertisementPriceOptional"]=>
    bool(false)
  }
}
information

You can learn more about the meaning of the different fields in the above response here.

How to find the cause of an error

An important part of working with a REST API is proper error handling. Not every request will be a successful one, and when you do get an error it’s vital to know how to respond accordingly.

In a REST API the first information you should check in case of an error is the HTTP status code of the response. The basic meaning of the status codes is described in the standard RFC-7231. Checking the status code will give you some basic understanding of the issue, even if you’re not familiar with our API.

Let’s try this out. Try to obtain the list of the main categories without passing an access_token:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

function getMainCategories(String $token): stdClass
{
    $getCategoriesUrl = "https://api.allegro.pl.allegrosandbox.pl/sale/categories";

    $ch = curl_init($getCategoriesUrl);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Accept: application/vnd.allegro.public.v1+json"
         ]);

    $mainCategoriesResult = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($mainCategoriesResult === false || $resultCode !== 200) {
                echo "Response status code: $resultCode\n";
                echo $mainCategoriesResult;
                exit;
    }

    $categoriesList = json_decode($mainCategoriesResult);

    return $categoriesList;
}

function main()
{
    $token = getAccessToken();
    $mainCategories = getMainCategories($token);
}    

What has changed?

  1. In lines 10-13, when you set the headers, do not add the Authorization header
  2. In lines 19-21 add the part for printing out the status code and the body of the response in case of an error.

When you run the script you should see the following output:

 Response status code: 401
 {"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

Check the status code - it’s 401. This means that the request is not authenticated, but it should - the token is missing.

Let’s see another example. Once again add the Authorization header - add a new line above line number 11:

  "Authorization: Bearer $token",

and change the body of the main method:

1
2
3
4
5
6
7
<?php
 
function main()
{
    $mainCategories = getMainCategories("aaa");
}

After running the script you will see:

 Response status code: 401
 {"error":"invalid_token","error_description":"Cannot convert access token to JSON"}

Again, the status code is 401, but this time the problem is different. You can check the details in the message. The token we sent in the request was not in JWT format.

What next

You can now generate a client credentials access token and use it to request the category data from the Allegro REST API. These are some basics which should help you start working with our API. You can read some more articles about the API, e.g.:

or you can go straight to the reference documentation.