# Getting Started

The User API provides endpoints for customer interactions on your commerce platform. These APIs enable customers (end users) to:

* Register and authenticate
* View and update their profile
* Manage their orders and order history
* Handle payment methods
* Interact with customer support

## <mark style="color:red;">How It Works</mark>

These APIs can be integrated in different ways depending on your architecture:

| Integration Type           | Description                                                                                                        | Example                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------- |
| **Headless / Server-side** | Your backend server makes API calls on behalf of the customer. You must store and manage cookies programmatically. | Django Zero Storefront |
| **Mobile apps**            | Mobile app makes API calls directly. Cookies must be stored and sent with each request.                            | Custom mobile apps     |

> **Reference implementations:** Django Zero Storefront and Next.js Zero Storefront both use these endpoints. You can refer to their source code for real-world integration examples.

**Important:**

* Each session is unique to the end user (customer)
* **Even guest users have sessions** - a session is created before login to track cart, preferences, etc.
* **Always store and resend cookies** with every request to maintain session continuity
* When a guest user logs in, their session is associated with their account

## <mark style="color:red;">Base URL</mark>

All API endpoints in this documentation use the following base URL:

```
{commerce_url}
```

Replace `{commerce_url}` with your commerce service URL.

> **Note:** This is the customer-facing commerce API, not the management/admin API. These endpoints are designed for end-user interactions on your storefront.

***

## <mark style="color:red;">Quick Start</mark>

Follow these three steps to authenticate a customer and make API requests on their behalf.

```
┌─────────────────┐      ┌─────────────────┐      ┌─────────────────┐
│  1. Get CSRF    │ ──►  │  2. Login       │ ──►  │  3. API Calls   │
│     Token       │      │     Customer    │      │     (authenticated)
└─────────────────┘      └─────────────────┘      └─────────────────┘
     csrftoken              osessionid            Both cookies +
     cookie                 cookie                x-csrftoken header
```

> **Note:** In browser-based apps, cookies are handled automatically. In headless/mobile apps, you must store cookies from every response and send them with each subsequent request—even for guest users.

### Step 1: Get CSRF Token

Before making any non-GET request, obtain a CSRF token.

**Request:**

```bash
# Get CSRF token (saved to cookies.txt, extract to variable)
curl -s -c cookies.txt "{commerce_url}/csrf_token/"
CSRF_TOKEN=$(awk '/csrf_token/ {print $7}' cookies.txt)
```

```python
import requests

COMMERCE_URL = "https://commerce.example.com"

session = requests.Session()
session.get(f"{COMMERCE_URL}/csrf_token/")

print(f"CSRF Token: {session.cookies.get('csrftoken')}")
```

**Response:**

The response sets a `csrftoken` cookie. Store this value for subsequent requests.

***

### Step 2: Customer Login

Authenticate the customer using their credentials to obtain a session cookie.

**Request:**

```bash
curl -X POST "{commerce_url}/users/login/" -H "Content-Type: application/json" -H "x-csrftoken: $CSRF_TOKEN" -b cookies.txt -c cookies.txt -d '{"email": "user@example.com", "password": "your_password"}'
```

```python
import requests

COMMERCE_URL = "https://commerce.example.com"

session = requests.Session()
session.get(f"{COMMERCE_URL}/csrf_token/")

response = session.post(
    f"{COMMERCE_URL}/users/login/",
    headers={"x-csrftoken": session.cookies.get("csrftoken")},
    json={"email": "customer@example.com", "password": "customer_password"}
)

print(f"Login: {response.status_code}")
```

**Response:**

On successful login, the response sets an `osessionid` cookie. The customer session is now authenticated.

***

### Step 3: Make Authenticated Requests

Include cookies in all requests. Add `x-csrftoken` header only for POST/PUT/DELETE requests.

**Important:** Always store cookies from responses—they may be refreshed by the server.

**Request:**

```bash
curl -X GET "{commerce_url}/current_user/" -b cookies.txt
```

```python
import requests

COMMERCE_URL = "https://commerce.example.com"

session = requests.Session()
session.get(f"{COMMERCE_URL}/csrf_token/")   
session.post(
    f"{COMMERCE_URL}/users/login/",
    headers={"x-csrftoken": session.cookies.get("csrftoken")},
    json={"email": "customer@example.com", "password": "customer_password"}
)

# Now make authenticated requests (GET doesn't need x-csrftoken)
response = session.get(f"{COMMERCE_URL}/current_user/")

print(response.json())
```

***

## <mark style="color:red;">Authentication</mark>

| Endpoint Type     | Authentication Required | Example Use Cases                        |
| ----------------- | ----------------------- | ---------------------------------------- |
| **Public**        | No                      | Product listings, store info, categories |
| **Authenticated** | Yes (session cookie)    | Profile, orders, addresses, payments     |

**Public endpoints** can be called without any authentication.

**Authenticated endpoints** require the customer to be logged in. The `osessionid` cookie proves the customer's identity and gives access to their personal data.

***

## <mark style="color:red;">Session Cookie</mark>

The session cookie identifies the customer's authenticated session.

**Default cookie name:** `osessionid`

**Example:**

```
Cookie: osessionid=yji6ppwys9a2k2myv3k9e5q2jifggqt9
```

**Custom cookie name:**

The session cookie name can be customized via the `SESSION_COOKIE_NAME` environment variable through Akinon Commerce Cloud (ACC). If modified, use the updated cookie name in your requests:

```
Cookie: <custom_session_cookie_name>=yji6ppwys9a2k2myv3k9e5q2jifggqt9
```

***

## <mark style="color:red;">CSRF Token</mark>

For all API requests except `GET`, CSRF verification is required. The CSRF token must be included in both:

1. The `csrftoken` cookie
2. The `x-csrftoken` header (must match the cookie value)

**Obtaining the CSRF Token:**

To fetch the CSRF token for the first time, call the `/csrf_token/` endpoint. The response will include a `csrftoken` cookie.

**Important:** Always store both the session cookie and CSRF token after each request, as they may be refreshed.

**Example (CSRF token only):**

```
Cookie: csrftoken=KxlMDi8Nfy0HljwuWTRnJwDMfGtP5Zh8xHn4BMOEJFAxaRAFJx6MarlaHDM66LZ7
x-csrftoken: KxlMDi8Nfy0HljwuWTRnJwDMfGtP5Zh8xHn4BMOEJFAxaRAFJx6MarlaHDM66LZ7
```

**Example (with session cookie):**

```
Cookie: osessionid=yji6ppwys9a2k2myv3k9e5q2jifggqt9; csrftoken=KxlMDi8Nfy0HljwuWTRnJwDMfGtP5Zh8xHn4BMOEJFAxaRAFJx6MarlaHDM66LZ7
x-csrftoken: KxlMDi8Nfy0HljwuWTRnJwDMfGtP5Zh8xHn4BMOEJFAxaRAFJx6MarlaHDM66LZ7
```

***

## <mark style="color:red;">Common Errors</mark>

| Error Code         | Description                   | Solution                                                             |
| ------------------ | ----------------------------- | -------------------------------------------------------------------- |
| `403 Forbidden`    | CSRF token missing or invalid | Ensure the `x-csrftoken` header matches the `csrftoken` cookie value |
| `401 Unauthorized` | Session expired or invalid    | Re-authenticate by logging in again                                  |
| `400 Bad Request`  | Invalid request data          | Check your request body and parameters                               |

***

## <mark style="color:red;">Quick Reference</mark>

**Cookies to manage:**

| Cookie       | Purpose                                     | When Set                        |
| ------------ | ------------------------------------------- | ------------------------------- |
| `csrftoken`  | Security token for POST/PUT/DELETE requests | After calling `/csrf_token/`    |
| `osessionid` | Session identifier (guest or logged-in)     | On first request or after login |

> **Remember:** Store cookies from every response and resend them with the next request. This applies to both guest and logged-in users.

**Headers for authenticated requests:**

```
Cookie: osessionid=<session_id>; csrftoken=<csrf_token>
x-csrftoken: <csrf_token>
```

**Key endpoints:**

| Endpoint         | Method | Purpose                      |
| ---------------- | ------ | ---------------------------- |
| `/csrf_token/`   | GET    | Get CSRF token               |
| `/users/login/`  | POST   | Customer login               |
| `/current_user/` | GET    | Get current customer profile |
