Manage resources (CRUD)

Learn about the life cycle of Composable Commerce resources and important concepts related to maintaining them.

  • After completing this page, you should be able to:

    • Identify correct usage of fields that identify a Composable Commerce resource.
    • Describe how Composable Commerce manages version control and version conflicts.
  • In a digital commerce project, you will usually work with things like customers, products, carts, and orders. Here’s how a sale generally works:

    • Customers choose products they want to buy.
    • They add these products to a cart.
    • When they’re ready to buy, they place an order.

    Each of these things must be modeled with data. A resource represents the data of an entity in your Project. In a Composable Commerce Project, you will find resources for Customers, Products, Carts, Orders, and many others that can build amazing customer experiences.

    The CRUD lifecycle

    These resources go through a life cycle:

    • Creation: The resource is made.
    • Updates: The resource can change over time, and be called upon or read.
    • Deletion: The resource might be removed. For example, orders are usually retained, but a customer can delete a wishlist if it is no longer required.

    The technical terms for these steps are CREATE, READ, UPDATE, and DELETE. Together, these are known as CRUD operations.

    The CRUD lifecycle refers to the creation, fetching, updating and deleting of a resource.

    Let's take a look at the operations in more detail, and explore what they might look like with the Customer resource in Composable Commerce.

    OperationDescriptionExample
    CreateTo create a resource, we must provide its defining values. Some of these values are mandatory, while others are optional. Without providing the mandatory values, the resource cannot be created.Assume that you want to create a Customer. Usually, you would have to provide their first name, last name, email address, shipping address, password and other information. In Composable Commerce, only the email address is mandatory to create the Customer, whilst the rest are optional (unless authenticationMode is set to Password, then the password is also a required field).
    Read (Get)Once the resource is created, it can be queried. This query must provide parameters that allow the system to identify the desired Customer resources for retrieval.Let’s imagine the customer is looking at their profile, so we need to retrieve the details. We can query the system for a Customer using their provided email address or the Customer key.
    UpdateAn update changes values on an existing resource. As such, we need to provide the resource identifier and its new values.The customer may have gotten married and has a new name. We would then need to update the Customer resource with this new information. We may also want to update their Customer Group information after they have signed up.
    DeleteDeleting a resource removes it from the project. Again, we need to provide an identifier for the resource.A customer may wish to delete their account, or to remove their details for GDPR purposes.

    Composable Commerce uses HTTP methods to handle these operations. In this diagram, we can see which HTTP methods are used for each CRUD operation.

    Each CRUD operation relates to a specific HTTP method in Composable Commerce.

    Identify resources

    Identifying the correct resource in Composable Commerce is crucial to ensuring accurate operation of your Project. For example, let’s assume you want to update a customer's address as they have moved into a new town. You need to provide Composable Commerce with a clear way to identify the correct resource. The Customer’s name might not be enough as the Customer's name is not guaranteed to be unique! Fields that can provide this guarantee of uniqueness are called ID fields.

    Composable Commerce provides the following ID fields:

    • id
    • key
    • sku
    • slug

    Both an id and key exist on most resources, and can be used to identify resources in your project using a GET, UPDATE, or DELETE operation. sku and slug are both specific to Products, whilst slug is also used by Categories.

    Let us take a closer look at each of these fields.

    id

    Every resource created in Composable Commerce is given a unique id. This id is automatically generated when the resource is created. This id is not only unique in the Project but it is also unique globally across all the projects in Composable Commerce.

    This has an important consequence. Assume you would like to synchronize data between two Projects (one Project being your production environment, and the other your staging environment). The two resources will not have the same id! Hence, it is recommended to never use an id value in your code. Read on to learn how to make sure your program code can be used across multiple projects.

    The value of id is unchangeable and has no external meaning. Composable Commerce uses it to track the resource and to reference resources.

    In the sample output of a Customer given below, you can find various id fields. One id is the Customer’s id, while others are used for referencing other resources in the same project.

    {
    "id": "8df2e3a8-2ab3-441c-82b8-45eabb9394ee", // Customer ID
    "version": 9,
    // output truncated
    "user": {
    "typeId": "user",
    "id": "fbec5a72-8b3c-470d-967b-27c062092f7e" // User id
    }
    // output truncated
    "customerGroup": {
    "typeId": "customer-group",
    "id": "2ac07101-751d-41c5-8498-9e131de707e5" // Customer Group id
    },
    "key": "john-doe-berlin-customer", // Customer key
    "custom": {
    "type": {
    "typeId": "type",
    "id": "fa271b19-d392-43c7-93f6-152981a66e17" // Custom Field's type id
    },
    }
    }

    key

    Another way to identify resources is the key field. The key, in contrast to the id, is not created automatically; it is set by developers. However, it can be used for identifying resources during CRUD operations.

    Keys should have some meaningful structure and the values should be reproducible for a given resource. For example, a Product on a production Project should have the same key as the equivalent Product on a staging Project.

    When seeing a key, you should be able to understand what resource it identifies. For example, wte43-2323 does not provide any hint to what resource is being identified. On the other hand, not only does europe-express-delivery-shipping-method tells us that you are referencing a Shipping Method, it also summarizes the Shipping Method.

    commercetools strongly recommends the following concerning keys:

    • Always use keys when maintaining resources.
    • Have a clear key policy (or schema) defined by your development team before you start using a new resource type in your Project. For example, a Product usually carries a lot of keys:
      • Tulip-seed-product
      • Evergreen-candle-product
      • Chianti-wine-glass-small-bottle-variant
      • berlin-store-price

    A programmer habit is to append the resource type to the identifier, for example -product, -variant, and -price. This is not mandatory but is just one possible way to help identify resources easier. You should decide on a clear schema and stick to it.

    When transferring data from one Project to another or updating existing data in your Project from any source, updating by key is easy because the key does not change. Hence, hardcoding key values in your program code or configuration fields will work.

    sku

    An sku (stock-keeping unit) is directly related to the topic of product modeling. Every Product Variant can be uniquely identified by an sku value. This identifier has its root in product and inventory management systems, and you can use it to link the Product Variant with these external systems.

    In a Composable Commerce Project however, it is also used to reference inventory data and Standalone Prices. Also, when adding Product Variants to a Cart, Composable Commerce uses the sku to identify the Product Variant.

    As the sku is usually determined by external systems, it is a free representation that often only makes sense when knowing the external system. Here are some examples of sku values:

    • TULIPSEED01
    • EC-0993
    • earm-04

    slug

    Slugs are easy-to-understand names that online stores often use as direct links to specific pages for items or resources within their website. In Composable Commerce, we use them for Categories (as we have Category pages) and Products (as we have so called product detail pages).

    A slug provides a "nicer" link to products compared to using the key or id. As they are usually part of the URL, they must be unique across the Project and SEO friendly. You can also include slugs for multiple languages to assist in localization.

    For example, in the following URL we can see that chianti-wine-glass is the English-language slug for the referenced Product: https://www.example.com/en/chianti-wine-glass.

    Version control and version conflicts

    Every resource in Composable Commerce maintains a version number which is used to keep track of (partial) updates of the resource. Composable Commerce implements what is known as optimistic concurrency control to handle concurrent requests on resources. This prevents loss updates when changes are made to data concurrently.

    When updating a resource you must send the version number of the resource as a proof that you know the latest values of the fields in the resource. If your version number does not match the one currently stored in your Project, the API returns a 409 Conflict ConcurrentModification error and provides the current version number in the body. This error tells you that an API consumer is trying to make a change to the same resource. You can get the current version from the 409 error body or do a read request on the resource to get the version number. Based on the new value you can then either retry your update request (now knowing the correct version number) or discard your desired update.

    Let’s walk through a series of actions to understand this concept better. In the first step we create a new Customer:

    POST https://api.europe-west1.gcp.commercetools.com/my-project/customers
    Authorization: Bearer 4EURriJZhi3PsPGQlgoWOXyShF9aTZM6
    Content-Type: application/json
    {
    "email": "miller@example.com",
    "password": "12345",
    "firstName": "Tom",
    "lastName": "Miller"
    "key": "tom-miller-customer"
    }

    This should return a 201 Created response with the new Customer in the body:

    {
    "customer": {
    "id": "8d34fd5b-183c-4e9f-b63c-f5d5fc082d04",
    "version": 1
    // ... truncated
    }
    }

    Now we can fetch the Customer, either using their key or id.

    GET https://api.europe-west1.gcp.commercetools.com/my-project/customers/key=tom-miller-customer
    Authorization: Bearer 4EURriJZhi3PsPGQlgoWOXyShF9aTZM6
    Content-Type: application/json

    In the answer we will still find the Customer’s version field set to 1.

    Lets now update the customer's last name to Breitner.

    POST https://api.europe-west1.gcp.commercetools.com/my-project/customers/key=tom-miller-customer
    Authorization: Bearer 4EURriJZhi3PsPGQlgoWOXyShF9aTZM6
    Content-Type: application/json
    {
    "version" : 1,
    "actions" : [
    {
    "action" : "setLastName",
    "lastName" : "Breitner"
    }
    ]
    }

    This should return a 200 OK response and the modified Customer:

    {
    "id": "8d34fd5b-183c-4e9f-b63c-f5d5fc082d04",
    "version": 2
    // ... truncated
    }

    Let’s now re-run the above code to set the Customer’s last name back to Miller.

    POST https://api.europe-west1.gcp.commercetools.com/my-project/customers/key=tom-miller-customer
    Authorization: Bearer 4EURriJZhi3PsPGQlgoWOXyShF9aTZM6
    Content-Type: application/json
    {
    "version" : 1,
    "actions" : [
    {
    "action" : "setLastName",
    "lastName" : "Miller"
    }
    ]
    }

    The answer is a 409 Conflict response.

    And the body tells us more:

    "message": "Object 8d34fd5b-183c-4e9f-b63c-f5d5fc082d04 has a different version than expected. Expected: 1 - Actual: 2."

    Running the above code one more time with the version attribute set to 2 will now work.

    POST https://api.europe-west1.gcp.commercetools.com/my-project/customers/key=tom-miller-customer
    Authorization: Bearer 4EURriJZhi3PsPGQlgoWOXyShF9aTZM6
    Content-Type: application/json
    {
    "version" : 2,
    "actions" : [
    {
    "action" : "setLastName",
    "lastName" : "Miller"
    }
    ]
    }

    The answer is a 200 OK success response. The version conflict is gone.

    However, a version conflict tells you that an API consumer updated the resource. It depends on your use case whether:

    • you resend your request now with the correct version number, or
    • you first read the resource again and learn about the modifications made before deciding on any further action.

    Let us answer three questions that are often asked when speaking about version control.

    1. Will every update increase the version number by 1?

      No. An update will, in most cases, increase the version number by 1. However, this is not always the case. The number of increments made per update, and how they are made, are not part of the API contract and you should never try to infer or guess what the next update will be.

    2. Is there support in the commercetools SDKs?

      Yes. The Java SDK supports optimistic concurrency control, but not currently the TypeScript SDK.

    3. Can you fetch an older (now overwritten) version of my resource from my Project by running a GET request together with an older version number?

      No. Composable Commerce only maintains one version of every resource at any given time. If you are interested in backup/restore services, and what you can or should do, read more in our documentation and/or contact commercetools support.

    Nice work! We covered a lot on this page. Let’s do a quick knowledge check, and then dive further into working with each CRUD operation on the Customer resource in the following pages.

    Test your knowledge