---
id: CreateBuyer
name: Create buyer
version: 1.0.0
badges:
  - content: Customer Management
    backgroundColor: orange
    textColor: orange
summary: Creates a Buyer profile for the authenticated customer from the supplied address.
owners:
  - commerce-fulfillment-team
schemaPath: schema.json
operation:
  method: POST
  path: /api/v1/buyers
  statusCodes: ["201", "400"]
sidebar:
  badge: "POST"
---

`CreateBuyer` creates a [[entity|buyer]] profile in [[service|order-api]] (`POST /ordering/api/v1/buyers`) using the supplied shipping address while deriving the buyer's identifier and display name from the authenticated Microsoft Entra ID token.

## Overview

| Property                           | Value                                                                                                                             |
| :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| **Bounded Context**                | Ordering                                                                                                                          |
| **Owner Service**                  | [[service\|order-api]]                                                                                                            |
| **Protocol / Format**              | HTTP `POST`, `application/json` request and response                                                                              |
| **Gateway Endpoint**               | `POST /ordering/api/v1/buyers` (service path `/api/v1/buyers`)                                                                    |
| **Authentication & Authorization** | Microsoft Entra ID JWT — `customer` or `admin` role plus scopes `ordering_read`, `ordering_write`                                 |
| **Idempotency / Concurrency**      | Required `x-request-id` header (Redis-backed 3600s TTL; returns `409 Conflict` on duplicate)                                      |
| **Rate Limit / Caching**           | Global concurrency (`100`), per-IP fixed-window (`30 req/min`), and per-user token bucket (`30` burst, `20` per `10s`, queue `5`) |
| **Contract Version**               | `1.0.0` (`ApiVersions.V1`)                                                                                                        |

## Request & Response Contract

### Request Headers

| Name           | Type     | Required | Constraints               | Description                                                        |
| :------------- | :------- | :------- | :------------------------ | :----------------------------------------------------------------- |
| `x-request-id` | `string` | Yes      | Non-empty, non-whitespace | Client-generated idempotency key tracked in Redis for 3600 seconds |

### Request Body (`application/json`)

| Name       | Type     | Required | Constraints                                          | Description                    |
| :--------- | :------- | :------- | :--------------------------------------------------- | :----------------------------- |
| `street`   | `string` | Yes      | Non-empty, max `50` characters; PII-redacted in logs | Street address of the buyer    |
| `city`     | `string` | Yes      | Non-empty, max `50` characters; PII-redacted in logs | City or district of the buyer  |
| `province` | `string` | Yes      | Non-empty, max `50` characters; PII-redacted in logs | Province or state of the buyer |

### Success Response (`201 Created`)

| Name              | Type              | Required | Constraints                             | Description                            |
| :---------------- | :---------------- | :------- | :-------------------------------------- | :------------------------------------- |
| `Location` header | `string`          | Yes      | Relative path `/api/v1/buyers/{id}`     | URI to fetch the created buyer profile |
| Root body         | `string` (`uuid`) | Yes      | Matches caller's `NameIdentifier` claim | Newly created buyer identifier         |

## Behavior & Side Effects

- **Identity derivation:** Extracts the buyer ID from the `NameIdentifier` claim (must be a valid UUID) and the display name from the `name` claim (falling back to `"anonymous"` if absent; stored max length `20` characters).
- **Transactional persistence:** Persists the [[entity|buyer]] aggregate and address value object inside a database transaction; emits no domain or integration events.
- **PII redaction:** Address fields (`street`, `city`, `province`) are automatically redacted in structured logs.
- **Idempotency key lifecycle:** Claims `x-request-id` in Redis for 3600 seconds (`409 Conflict` on replay) and deletes the key if the operation fails with `5xx`.

:::warning
Because the buyer ID is derived directly from the authenticated user's token, a second `CreateBuyer` call for the same user with a new `x-request-id` collides with the existing primary key and fails with `500 Internal Server Error`. Use [[command|UpdateAddress]] to update an existing profile.
:::

## Error Responses

| Status / Code               | Condition                                                                                                                          | Client Recovery Action                                                        |
| :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------- |
| `400 Bad Request`           | Missing `x-request-id` header, empty/whitespace address field, field exceeding `50` characters, or non-UUID `NameIdentifier` claim | Fix headers, payload fields, or token claims; do not retry unchanged          |
| `401 Unauthorized`          | Missing, expired, or invalid Entra ID bearer token                                                                                 | Acquire a fresh Entra ID access token and retry                               |
| `403 Forbidden`             | Caller lacks `customer`/`admin` role or `ordering_read`/`ordering_write` scopes                                                    | Request the required Entra ID role and scopes before retrying                 |
| `409 Conflict`              | Duplicate `x-request-id` for this path within the 3600-second TTL                                                                  | Treat as a duplicate submission and fetch the profile via [[query\|GetBuyer]] |
| `429 Too Many Requests`     | Rate limit quota exceeded (`Retry-After` header included)                                                                          | Wait for the `Retry-After` interval before retrying                           |
| `500 Internal Server Error` | Duplicate buyer profile for the authenticated user, display name exceeding `20` characters, or unhandled persistence error         | Inspect service logs and verify whether the buyer profile already exists      |

## Related Documentation

- [[service|order-api]] — Service architecture, persistence, and endpoints.
- [[entity|buyer]] — Buyer aggregate schema and address value object.
- [[command|UpdateAddress]] — Update the authenticated customer's address.
- [[command|DeleteBuyer]] — Administrative permanent removal of a buyer profile.
- [[query|GetBuyer]] — Retrieve a buyer profile.

<NodeGraph />

<SchemaViewer file="schema.json" title="Create buyer schema" maxHeight="500" search="true" />


 ## Raw Schema:schema.json

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"title": "CreateBuyerCommand",
	"description": "Address fields required to create a Buyer profile.",
	"type": "object",
	"required": ["street", "city", "province"],
	"properties": {
		"street": {
			"type": "string"
		},
		"city": {
			"type": "string"
		},
		"province": {
			"type": "string"
		}
	}
}
