---
title: Using the Store API | Shopware Community Hub
description: >-
  Learn how the Store API works, how it is authenticated, and how it is used for
  customer-facing operations.
canonical_url: 'https://hub.shopware.com/learn/unit/using-the-store-api'
---

# Using the Store API

<LearningObjectives>

- Understand the purpose and scope of the Shopware Store API.
- Learn how Store API authentication works using sales channel and context tokens.
- Use core Store API endpoints to retrieve customer-facing data and manage carts.
  
</LearningObjectives>

# Using the Store API

Welcome to the comprehensive guide to the Shopware Store API! This powerful interface is your gateway to building exceptional customer experiences, from custom storefronts to mobile applications and headless commerce solutions.

## Understanding the Store API's Purpose

The Store API is the data layer that feeds information to the storefront that customers interact with. When a customer visits your shop, every piece of information they see, products, prices, categories, cart contents, shipping options, and more, is retrieved through the Store API. Whether you're using Shopware's default storefront, [Composable Frontends](https://frontends.shopware.com/), or building a completely custom headless solution, the Store API is what provides all the customer-facing data and functionality:

- **Product Discovery**: Browse catalogs, search products, and explore categories
- **Shopping Cart Management**: Add, update, and manage cart items
- **Customer Accounts**: Registration, authentication, and profile management
- **Checkout Process**: Address management, shipping, and payment processing
- **Order Management**: View order history and track shipments
- **Search and Filtering**: Advanced product search with multiple criteria

## Authentication: Customer-Centric Security

The Store API uses a token-based authentication mechanism. Unlike the Admin API's OAuth2 flow, the Store API requires a Sales Channel Access Key (`sw-access-key`) for all requests and a Context Token (`sw-context-token`) for session management (cart, login state).

### Guest Access vs. Authenticated Sessions

#### Guest Access

Many Store API endpoints are accessible without a customer login, allowing users to browse products and add items to the cart. However, the `sw-access-key` header is always required.

For **cart and checkout**, guests also need a **context token** so the store can associate the cart with a session. Get a context token first, then send it in the `sw-context-token` header with every cart-related request. You can obtain a token in either of these ways:

- **`GET /store-api/context`** (with `sw-access-key`) — returns a context token; no cart exists yet. A cart is created automatically when you add your first line item or call `GET /store-api/checkout/cart`.
- **`POST /store-api/checkout/cart`** (with `sw-access-key`) — creates a cart and returns a context token in the response. Use that token for subsequent cart operations.

```bash
# Browse products without login (no context token needed)
curl -X GET "https://your-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY"
```

#### Customer Authentication

For personalized experiences and account-specific operations, customers authenticate to obtain a context token:

```bash
# Customer login
curl -X POST "https://your-shop.com/store-api/account/login" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "username": "customer@example.com",
    "password": "customerpassword"
  }'
```

A successful login returns the context token in the `sw-context-token` header of the response (and in the body as `contextToken` or `token`):

```json
{
  "apiAlias": "array_struct",
  "contextToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
  "redirectUrl": null
}
```

### Using Customer Tokens

Include the context token in requests to access the authenticated session:

```bash
curl -X GET "https://your-shop.com/store-api/account" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json"
```

### Example: Store API Request in PHP

Let's explore a simple example of how to fetch a list of products via the **Store API** in PHP.

```php
<?php declare(strict_types=1);

use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use RuntimeException;
use Throwable;

class MyStoreApiProductService
{
    public function __construct(
        private readonly HttpClientInterface $client    
    ) {
    }
    
    public function fetchActiveProducts(string $baseUrl, string $swAccessKey, string $swContextToken): array
    {
        if (true === empty($baseUrl)) {
            throw new RuntimeException('Base URL is required.');        
        }
        
        if (true === empty($swAccessKey)) {
            throw new RuntimeException('Sales channel access key is required.');
        }
        
        if (true === empty($swContextToken)) {
            throw new RuntimeException('Context token is required.');
        }
        
        try {
            $response = $this->client->request('POST', $baseUrl . '/store-api/product', [
              'headers' => [
                  'Accept'           => 'application/json',
                  'Content-Type'     => 'application/json',
                  'sw-access-key'    => $swAccessKey,
                  'sw-context-token' => $swContextToken
              ],
              'json' => [
                  'limit'  => 3,
                  'filter' => [
                      [
                          'type'  => 'equals',
                          'field' => 'active',
                          'value' => true
                      ]
                  ]
              ]
            ]);
            
            if (Response::HTTP_OK !== $response->getStatusCode()) {
                throw new RuntimeException(
                    sprintf('Unexpected response status code: %s.', $response->getStatusCode())
                );
            }
            
            return $response->toArray();
        } catch(Throwable $e) {
            throw new RuntimeException(
                sprintf('Failed to fetch products: %s.', $e->getMessage())
            );
        }
    }
}
```

This example shows a minimal Store API request in PHP. The Store API is accessed via **sales channel context**:

- `sw-access-key` identifies the sales channel. You can find the access key in the administration within your storefront sales channel.
- `sw-context-token` identifies the current customer or guest session.

In this example the endpoint `/store-api/product` is used and the request is scoped to the provided sales channel and session context. For more details about authentication in the Store API context, see the [official documentation](https://shopware.stoplight.io/docs/store-api/8e1d78252fa6f-authentication-and-authorisation).

## Core Store API Operations

Now let's explore the essential operations that power the customer shopping experience.

### Product Discovery and Browsing

#### Retrieving Product Lists

Get products with pagination and filtering:

```bash
curl -X POST "https://your-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "limit": 20,
    "page": 1,
    "filter": [
      {
        "type": "equals",
        "field": "active",
        "value": true
      }
    ]
  }'
```

#### Advanced Product Search

Implement sophisticated product search:

```bash
curl -X POST "https://your-shop.com/store-api/search" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "query": "developer t-shirt",
    "limit": 25,
    "filter": [
      {
        "type": "range",
        "field": "price.gross",
        "parameters": {
          "gte": 20,
          "lte": 100
        }
      }
    ],
    "sort": [
      {
        "field": "name",
        "order": "asc"
      }
    ]
  }'
```

#### Category Navigation

Browse products by category:

```bash
curl -X POST "https://your-shop.com/store-api/category" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "filter": [
      {
        "type": "equals",
        "field": "id",
        "value": "CATEGORY_UUID"
      }
    ],
    "associations": {
      "products": {
        "limit": 50
      }
    }
  }'
```

### Shopping Cart Management

The Store API uses a session-based cart system. Cart operations require a context token (see [Guest Access](/learn/unit/using-the-store-api#guest-access)): get one via `GET /store-api/context` or by creating a cart as shown below.

#### Getting a Context Token and Creating a Cart (Guests)

**Option 1 — Get a token only (cart created on first use):**

```bash
curl -X GET "https://your-shop.com/store-api/context" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY"
```

The response includes a context token. Send it in the `sw-context-token` header for all later cart requests. A cart is created automatically when you add your first line item or request the cart.

**Option 2 — Create a cart and get a token in one step:**

```bash
curl -X POST "https://your-shop.com/store-api/checkout/cart" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY"
```

The response contains the context token (e.g. in `token` or `contextToken`). Use it in the `sw-context-token` header for subsequent cart requests. This is a guest cart with no customer attached.

#### Adding Products to Cart

Add items to the cart using the context token from the previous step:

```bash
curl -X POST "https://your-shop.com/store-api/checkout/cart/line-item" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "sw-context-token: YOUR_CONTEXT_TOKEN" \
  -d '{
    "items": [
      {
        "referencedId": "PRODUCT_UUID",
        "quantity": 2,
        "type": "product"
      }
    ]
  }'
```

#### Updating Cart Items

Modify quantities or remove items. Use the line item's `id` (from the cart response) to update or remove it:

```bash
# Update quantity
curl -X PATCH "https://your-shop.com/store-api/checkout/cart/line-item" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "sw-context-token: YOUR_CONTEXT_TOKEN" \
  -d '{
    "items": [
      {
        "id": "LINE_ITEM_UUID",
        "quantity": 3,
        "referencedId": "NEW_LINE_ITEM_UUID"
      }
    ]
  }'

# Remove item
curl -X DELETE "https://your-shop.com/store-api/checkout/cart/line-item" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "sw-context-token: YOUR_CONTEXT_TOKEN" \
  -d '{
    "ids": ["LINE_ITEM_UUID_01", "LINE_ITEM_UUID_02"]
  }'
```

#### Retrieving Cart Contents

Get current cart information:

```bash
curl -X GET "https://your-shop.com/store-api/checkout/cart" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "sw-context-token: YOUR_CONTEXT_TOKEN"
```

### Customer Account Management

#### Customer Registration

Create new customer accounts:

```bash
curl -X POST "https://your-shop.com/store-api/account/register" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "email": "newcustomer@example.com",
    "password": "securepassword123",
    "firstName": "John",
    "lastName": "Doe",
    "billingAddress": {
      "firstName": "John",
      "lastName": "Doe",
      "street": "123 Main Street",
      "zipcode": "12345",
      "city": "Anytown",
      "countryId": "COUNTRY_UUID"
    }
  }'
```

#### Customer Login and Session Management

Authenticate existing customers:

```bash
curl -X POST "https://your-shop.com/store-api/account/login" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "username": "customer@example.com",
    "password": "customerpassword"
  }'
```

#### Managing Customer Profiles

Retrieve and update customer information:

```bash
# Get customer profile
curl -X GET "https://your-shop.com/store-api/account" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json"

# Update customer profile
curl -X PATCH "https://your-shop.com/store-api/account/profile" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Smith"
  }'
```

#### Address Management

Manage customer addresses:

```bash
# Get customer addresses
curl -X GET "https://your-shop.com/store-api/account/list-address" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json"

# Add new address
curl -X POST "https://your-shop.com/store-api/account/address" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "street": "456 Oak Avenue",
    "zipcode": "54321",
    "city": "Othertown",
    "countryId": "COUNTRY_UUID"
  }'
```

### Checkout Process

#### Shipping Method Selection

Get available shipping methods:

```bash
curl -X POST "https://your-shop.com/store-api/checkout/shipping-method" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "onlyAvailable": true
  }'
```

#### Payment Method Selection

Retrieve available payment options:

```bash
curl -X POST "https://your-shop.com/store-api/checkout/payment-method" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "onlyAvailable": true
  }'
```

#### Order Placement

Complete the checkout process:

```bash
curl -X POST "https://your-shop.com/store-api/checkout/order" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "billingAddressId": "BILLING_ADDRESS_UUID",
    "shippingAddressId": "SHIPPING_ADDRESS_UUID",
    "shippingMethodId": "SHIPPING_METHOD_UUID",
    "paymentMethodId": "PAYMENT_METHOD_UUID"
  }'
```

### Order Management

#### Viewing Order History

Retrieve customer orders:

```bash
curl -X POST "https://your-shop.com/store-api/order" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "limit": 10,
    "page": 1
  }'
```

#### Order Details

Get specific order information:

```bash
curl -X GET "https://your-shop.com/store-api/order/ORDER_UUID" \
  -H "sw-context-token: CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json"
```

## Advanced Store API Features

### Context and Localization

The Store API automatically handles context-specific information like currency, language, and sales channel:

```bash
# Set context headers for specific locale
curl -X GET "https://your-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Accept-Language: de-DE" \
  -H "Accept-Currency: EUR"
```

### Associations and Data Loading

Load related data efficiently:

```bash
curl -X POST "https://your-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "filter": [
      {
        "type": "equals",
        "field": "id",
        "value": "PRODUCT_UUID"
      }
    ],
    "associations": {
      "manufacturer": {},
      "properties": {},
      "media": {},
      "categories": {}
    }
  }'
```

### Custom Fields and Extensions

Access custom fields from plugins like ProductNotes:

```bash
curl -X POST "https://your-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{
    "filter": [
      {
        "type": "equals",
        "field": "id",
        "value": "PRODUCT_UUID"
      }
    ],
    "associations": {
      "academyProductNotes": {}
    }
  }'
```

## Building Custom Storefronts

### Headless Commerce Implementation

The Store API is perfect for building headless commerce solutions:

```vue
<!-- Example: Vue component for product listing using Composable Frontends -->
<template>
  <div class="product-grid">
    <ProductCard
      v-for="product in products"
      :key="product.id"
      :product="product"
    />
  </div>
</template>

<script setup lang="ts">
import { useProductSearch } from '@shopware/api-client';
import { ref, onMounted } from 'vue';

const { search } = useProductSearch();
const products = ref([]);

onMounted(async () => {
  const response = await search({
    limit: 20,
    filter: [
      {
        type: 'equals',
        field: 'active',
        value: true
      }
    ]
  });
  
  products.value = response.elements;
});
</script>
```

### Mobile Application Integration

Integrate with mobile apps for seamless shopping experiences:

```swift
// Example: iOS Swift implementation
func fetchProducts() {
    let url = URL(string: "https://your-shop.com/store-api/product")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let body = [
        "limit": 20,
        "filter": [
            ["type": "equals", "field": "active", "value": true]
        ]
    ]
    
    request.httpBody = try? JSONSerialization.data(withJSONObject: body)
    
    URLSession.shared.dataTask(with: request) { data, response, error in
        // Handle response
    }.resume()
}
```

## Best Practices for Store API Implementation

### Performance Optimization

- **Implement caching**: Cache product data and search results
- **Use associations wisely**: Only load necessary related data
- **Implement pagination**: Handle large datasets efficiently
- **Optimize requests**: Minimize API calls by batching operations

### Security Considerations

- **Validate customer input**: Always validate data before sending to API
- **Implement rate limiting**: Prevent abuse of your API endpoints
- **Secure token storage**: Store customer tokens securely
- **HTTPS enforcement**: Use secure connections for all API calls

### User Experience

- **Progressive enhancement**: Build experiences that work without JavaScript
- **Error handling**: Provide meaningful error messages to customers
- **Loading states**: Show appropriate loading indicators during API calls
- **Offline support**: Consider implementing offline capabilities

## Testing and Development

### Development Environment Setup

Always test in a development environment first:

```bash
# Test basic connectivity
curl -X GET "https://your-dev-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY"

# Test with authentication
curl -X GET "https://your-dev-shop.com/store-api/account" \
  -H "sw-context-token: TEST_CONTEXT_TOKEN" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -H "Content-Type: application/json"
```

### API Testing Tools

- **Postman**: Create collections for different API operations
- **Insomnia**: Test API endpoints with a clean interface
- **Custom scripts**: Build automated testing for your specific use cases
- **Browser DevTools**: Use Network tab for debugging API calls

## Real-World Implementation Examples

### E-commerce Website Integration

Complete product browsing and cart management:

```bash
#!/bin/bash
# Complete shopping flow example

# 1. Browse products
echo "Browsing products..."
PRODUCTS=$(curl -s -X POST "https://your-shop.com/store-api/product" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{"limit": 5}')

# 2. Add product to cart
echo "Adding product to cart..."
CART=$(curl -s -X POST "https://your-shop.com/store-api/checkout/cart/line-item" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" \
  -d '{"items": [{"id": "PRODUCT_UUID", "quantity": 1, "type": "product"}]}')

# 3. View cart
echo "Cart contents:"
curl -s -X GET "https://your-shop.com/store-api/checkout/cart" \
  -H "Content-Type: application/json" \
  -H "sw-access-key: SW_ACCESS_KEY" | jq '.'
```

### Customer Account Dashboard

Build a customer portal:

```bash
# Get customer information and orders
curl -X GET "https://your-shop.com/store-api/account" \
  -H "sw-context-token: $CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: $SW_ACCESS_KEY" \
  -H "Content-Type: application/json" | jq '.'

# Get recent orders
curl -X POST "https://your-shop.com/store-api/order" \
  -H "sw-context-token: $CUSTOMER_CONTEXT_TOKEN" \
  -H "sw-access-key: $SW_ACCESS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"limit": 10}' | jq '.'
```

## Common Challenges and Solutions

### Cart Session Management

- **Session persistence**: Implement proper cart session handling
- **Cross-device sync**: Consider user account linking for cart persistence
- **Abandoned cart recovery**: Implement cart recovery mechanisms

### Performance and Scalability

- **CDN integration**: Use content delivery networks for static content
- **Database optimization**: Ensure efficient database queries
- **Caching strategies**: Implement appropriate caching at multiple levels

### Mobile Responsiveness

- **Touch-friendly interfaces**: Design for mobile-first experiences
- **Progressive web apps**: Consider PWA capabilities for mobile users
- **Offline functionality**: Implement offline shopping capabilities

## Next Steps and Advanced Topics

With the Store API fundamentals mastered, explore:

- **Webhook integration**: Real-time notifications for order updates
- **Payment gateway integration**: Custom payment processing
- **Inventory management**: Real-time stock updates
- **Personalization**: Customer-specific product recommendations
- **Analytics integration**: Track customer behavior and conversions

## Resources and Tools

- **API Documentation**: [https://shopware.stoplight.io/docs/store-api](https://shopware.stoplight.io/docs/store-api/38777d33d92dc-quick-start-guide)
- **API Client Generator**: Use [@shopware/api-gen](https://www.npmjs.com/package/@shopware/api-gen) for type-safe API calls
- **Community Resources**: Shopware developer forums and documentation
- **Testing Tools**: Postman collections and automated testing frameworks

## Summary

In this learning unit, you learned:

- The purpose of the Shopware Store API and how it differs from the Admin API.
- How Store API authentication works using the **sales channel access key** and **context token**.
- How to use common Store API endpoints to retrieve customer-facing data and perform cart and customer operations.
- How the Store API enables **headless commerce**, custom storefronts and mobile integrations.

With this knowledge, you can create seamless, personalized shopping journeys that drive customer satisfaction and business growth.

Remember to always prioritize user experience, implement proper error handling, and test thoroughly across different devices and scenarios. The Store API is your gateway to modern, headless commerce solutions that can adapt to any frontend technology or platform.
