# Get started with the PHP SDK Learn how to set up and use the PHP SDK. This step-by-step guide leads you through setting up and making API calls using the PHP SDK. ## Requirements To follow this guide you should have the following: - A Project - An [API Client](/api/projects/api-clients.md) - PHP 7.2 (or later) - [Composer](https://getcomposer.org/download/) For more information on setting up a Project or API Client, follow our [Getting Started](/api/getting-started/initial-setup.md) guides. ## Objectives of the get started guide After following this guide you will have: - [Installed the PHP SDK](/dev-tooling/php-sdk-getting-started.md#install-the-php-sdk) - [Created a Client class](/dev-tooling/php-sdk-getting-started.md#create-the-client-class) - [Tested your Client](/dev-tooling/php-sdk-getting-started.md#test-the-client) - [Learned how to make API calls with the PHP SDK](/dev-tooling/php-sdk-getting-started.md#structure-your-api-call) ## Placeholder values Example code in this guide uses the following placeholder values. You should replace these placeholders with the following values. If you do not have an API Client, follow our [Get your API Client](/api/getting-started/create-api-client.md) guide. | Placeholder | Replace with | From | | --- | --- | --- | | `{projectKey}` | project\_key | your API Client | | `{clientID}` | client\_id | your API Client | | `{clientSecret}` | secret | your API Client | | `{scope}` | scope | your API Client | | `{region}` | your Region | [Hosts](/api/general-concepts.md#hosts) | ## Install the PHP SDK Use the following command to install the PHP SDK: ``` composer require commercetools/commercetools-sdk ``` ## Create the Client class Create a file called `Client.php` and insert the following code: ```php createGuzzleClient( new Config([], 'https://api.{region}.commercetools.com'), $authConfig ); /** @var ClientInterface $client */ $builder = new ApiRequestBuilder($client); // Include the Project key with the returned Client return $builder->withProjectKey('{projectKey}'); } } ?> ``` ## Test the Client In your PHP program, add the following code: ```php createApiClient(); // Make a get call to the Project $myProject = $apiRoot->get()->execute(); // Output the Project name echo $myProject->getName(); ?> ``` You can now use `$apiRoot` to build requests to the commerce API. This code includes an example API call that gets your Project to `$myProject` and outputs the Project's name using `getName()`. ## Use the PHP SDK ### Imports Without importing resource-specific classes you cannot use/access specific objects and methods. For example, to create a Shopping List you must import: ```php use Commercetools\Api\Models\ShoppingList\ShoppingListDraftBuilder; require_once __DIR__ . '/vendor/autoload.php'; ``` If not imported, the SDK returns a "Class not found" fatal error with the name of the required class. ### Use builders The PHP SDK follows a builder pattern when constructing drafts, update actions, and other objects/types that contain multiple fields. ```php // Imports use Commercetools\Api\Models\Common\LocalizedStringBuilder; use Commercetools\Api\Models\Common\MoneyBuilder; use Commercetools\Api\Models\Category\CategoryDraftBuilder; require_once __DIR__ . '/vendor/autoload.php'; // Create a LocalizedString $localizedString = LocalizedStringBuilder::of() ->put('en', 'English value') ->put('de', 'German value') ->build(); // Create US$100.00 $money = MoneyBuilder::of() ->withCurrencyCode('USD') ->withCentAmount(10000) ->build(); // Create a CategoryDraft $categoryDraft = CategoryDraftBuilder::of() ->withName( LocalizedStringBuilder::of() ->put('en', 'English name') ->build() ) ->withSlug( LocalizedStringBuilder::of() ->put('en', 'english-slug') ->build() ) ->withKey('category-key') ->build(); ``` Consult the [HTTP API reference](/api/) to ensure that you include all required fields. After you add the fields/values, `build()` finishes building the object. ## Structure your API call ### Add an endpoint Add an endpoint to `$apiRoot`. The following targets the Shopping Lists endpoint: ```php $shoppingListInfo = $apiRoot->shoppingLists(); // ... ``` If your IDE supports auto-complete, you can see the full list of endpoints. ![Screenshot of autocomplete for endpoint](https://docs.commercetools.com/dev-tooling/images/php/php-sdk-endpoint.png) If you do not specify an endpoint, the SDK references the [Project](/api/projects/project.md). ### Retrieve data #### Get a single resource When targeting a specific resource, you should include its ID or key followed by `get()` and `execute()`. ```php // Get a specific Shopping List by ID $shoppingListInfo = $apiRoot ->shoppingLists() ->withId('a-shoppinglist-id') ->get() ->execute(); // Get a specific Shopping List by key $shoppingListInfo = $apiRoot ->shoppingLists() ->withKey('a-shoppinglist-key') ->get() ->execute(); ``` If you query a resource with an id or key that does not exist, the API returns a [Not Found](/api/errors.md#404-not-found) error. In this example, `$shoppingListInfo` now contains the data of the specified Shopping List. You can access information from the fields within that object: ![Screenshot of autocomplete for ShoppingList object](https://docs.commercetools.com/dev-tooling/images/php/php-sdk-get.png) #### Get multiple resources If you do not include an ID or key, the endpoint returns a `PagedQueryResponse`, which is identical to the [PagedQueryResults](/api/general-concepts.md#pagedqueryresult) in the HTTP API. ```php // Return a ShoppingListPagedQueryResponse $shoppingListQuery = $apiRoot ->shoppingLists() ->get() ->execute(); ``` You can alter the results of these calls by including [`withWhere()`](/api/predicates/query.md), [`withSort()`](/api/general-concepts.md#sorting), [`withExpand()`](/api/general-concepts.md#reference-expansion), [`withLimit()`](/api/general-concepts.md#limit), or [`withOffset()`](/api/general-concepts.md#offset) after `get()`. These are identical to the [parameters](/api/general-concepts.md#query-features) you can add to standard HTTP API calls. If your IDE supports autocomplete you can view a full list of methods available: ![Screenshot of autocomplete for parameters](https://docs.commercetools.com/dev-tooling/images/php/php-sdk-parameters.png) ##### View results You can access the list of resources within a `PagedQueryResponse` using `getResults()`: ```php // Return a ShoppingListPagedQueryResponse $shoppingListQuery = $apiRoot ->shoppingLists() ->get() ->execute(); // Put the returned Shopping Lists in a collection $collectionOfShoppingLists = $shoppingListQuery->getResults(); // Output the first Shopping List's English name echo $collectionOfShoppingLists[0]->getName()['en']; ``` ### Write a resource #### Create a new resource Creating a new resource requires a draft of the resource to create. For Shopping Lists this is a [ShoppingListDraft](/urn?urn=ctp%3Aapi%3Atype%3AShoppingListDraft). You create these drafts using [builders](/dev-tooling/php-sdk-getting-started.md#use-builders). ```php // Required import use Commercetools\Api\Models\ShoppingList\ShoppingListDraftBuilder; require_once __DIR__ . '/vendor/autoload.php'; // Build a ShoppingListDraft with the required fields (email address and password) $newShoppingListDetails = (new ShoppingListDraftBuilder()) ->withName( (new LocalizedStringBuilder()) ->put('en', 'English name of Shopping List') ->build() ) ->build(); ``` Include `$newShoppingListDetails` within `post()` and follow with `execute()`. ```php // Post the ShoppingListDraft and get the new Shopping List $newShoppingList = $apiRoot ->shoppingLists() ->post($newShoppingListDetails) ->execute(); ``` #### Update an existing resource Updating an existing resource requires posting an update payload. This payload (in the case of Shopping Lists, a `ShoppingListUpdate`) contains a collection of update actions and the last seen version of the resource. You can create update actions and payloads by using [builders](/dev-tooling/php-sdk-getting-started.md#use-builders). ```php // Required imports use Commercetools\Api\Models\ShoppingList\ShoppingListUpdateBuilder; use Commercetools\Api\Models\ShoppingList\ShoppingListUpdateActionCollection; use Commercetools\Api\Models\ShoppingList\ShoppingListSetKeyActionBuilder; require_once __DIR__ . '/vendor/autoload.php'; // Build a ShoppingListUpdate with the required fields (version and ShoppingListUpdateActionCollection) $shoppingListUpdate = (new ShoppingListUpdateBuilder()) ->withVersion(1) ->withActions( (new ShoppingListUpdateActionCollection())->add( (new ShoppingListSetKeyActionBuilder()) ->withKey('a-new-shoppinglist-key') ->build() ) ) ->build(); ``` You can then post the payload to a single resource (using `withId()` or `withKey()`). ```php // Post the ShoppingListUpdate and return the updated Shopping List $updatedShoppingList = $apiRoot ->shoppingLists() ->withId('{shoppingListID}') ->post($shoppingListUpdate) ->execute(); ``` ### Delete a resource Deleting a resource requires using the `.delete()` method with the last seen version of the resource. You must identify the resource to delete using `withId()` or `withKey()`. ```php // Delete and return a Shopping List $deletedShoppingList = $apiRoot ->shoppingLists() ->withId('{shoppingListID}') ->delete() ->withVersion(1) ->withDataErasure('true') // Include to erase related personal data ->execute(); ``` ### Retrieve the raw API response The above examples use `execute()` to return the resource as an instance of an object. To retrieve the raw API response, use `send()`. ```php // Return a ShoppingListPagedQueryResponse $shoppingListQuery = $apiRoot ->shoppingLists() ->get() ->send() ->getBody(); // Output the raw API response echo $shoppingListQuery; ``` ## Try our example code Continue learning about the PHP SDK by checking our [SDK code examples](/dev-tooling/sdk-example-code?activePath=php). You will find example code for creating, querying, and updating Customers and Products. ## Related pages - [Area overview page with navigation](/dev-tooling.md) - [Previous page: Overview](/dev-tooling/php-sdk.md) - [Next page: Middleware](/dev-tooling/php-sdk-middleware.md)