# POST /api/api-keys/{id}/rotate

Rotate an API key

Mints a replacement owned by the same user and merchant, with the same access, and returns
it with its value revealed. This is the only time that value is shown.
            
The key being rotated keeps authenticating for an overlap window (24 hours by default,
seven days at most) so the integration can deploy the replacement without an outage, and
is then refused with KEY_REVOKED. To end the overlap sooner, revoke the rotated key: that
takes effect on the very next request.
            
Gated on the same permission as revoke, because it is the same decision about the same
credential. Refused for a key that has already been revoked or already been rotated.
            
Also refused for a suspended key, because a working replacement with the same access
would route around the suspension. Reinstate the key first, or revoke it and create a
new key.

**Operation ID:** `apiKeysRotate`

## Authorization

Requires: ApiKeyAuthorization.ApiKeys, merchant scope.

Requires API key scope: `admin`

Required permissions:
- `ApiKeyAuthorization.ApiKeys`

## Parameters

| Name | In | Required | Type | Description |
| --- | --- | --- | --- | --- |
| id | path | yes | string(uuid) |  |
| suppressNulls | query | no | boolean | If true, omit properties with null values. |

## Request Body

**Content type:** `application/json`

Schema: [`RotateApiKeyDto`](https://devportal.demo.winkpg.io/docs/api/models/RotateApiKeyDto.md)

Properties:
- `overlapHours` (integer(int32)): How many hours the replaced key should keep authenticating, or `null` for the configured  default (24 hours). (nullable, min 0)
- `expireAt` (string(date-time)): When the replacement should expire, or `null` to give it the same term the replaced key  was originally granted, measured from now. (nullable)
- `reason` (string): A reason recorded against the replaced key, used only when the rotation cuts over immediately  and therefore revokes it in the same operation. (nullable, max length 256)

_Example: Replace a leaked key and revoke it at once_

Creates a replacement owned by the same user and merchant and, because the overlap is zero hours, revokes the replaced key in the same operation, recording the reason against it. Send a positive overlapHours instead to keep the replaced key working while you deploy the new one. The replacement expires at the date sent; leave expireAt out to give it the replaced key's original term. The server generates the replacement's key value and returns it once in the response.

```json
{
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
}
```

**Content type:** `text/json`

Schema: [`RotateApiKeyDto`](https://devportal.demo.winkpg.io/docs/api/models/RotateApiKeyDto.md)

Properties:
- `overlapHours` (integer(int32)): How many hours the replaced key should keep authenticating, or `null` for the configured  default (24 hours). (nullable, min 0)
- `expireAt` (string(date-time)): When the replacement should expire, or `null` to give it the same term the replaced key  was originally granted, measured from now. (nullable)
- `reason` (string): A reason recorded against the replaced key, used only when the rotation cuts over immediately  and therefore revokes it in the same operation. (nullable, max length 256)

_Example: Replace a leaked key and revoke it at once_

Creates a replacement owned by the same user and merchant and, because the overlap is zero hours, revokes the replaced key in the same operation, recording the reason against it. Send a positive overlapHours instead to keep the replaced key working while you deploy the new one. The replacement expires at the date sent; leave expireAt out to give it the replaced key's original term. The server generates the replacement's key value and returns it once in the response.

```json
{
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
}
```

**Content type:** `application/*+json`

Schema: [`RotateApiKeyDto`](https://devportal.demo.winkpg.io/docs/api/models/RotateApiKeyDto.md)

Properties:
- `overlapHours` (integer(int32)): How many hours the replaced key should keep authenticating, or `null` for the configured  default (24 hours). (nullable, min 0)
- `expireAt` (string(date-time)): When the replacement should expire, or `null` to give it the same term the replaced key  was originally granted, measured from now. (nullable)
- `reason` (string): A reason recorded against the replaced key, used only when the rotation cuts over immediately  and therefore revokes it in the same operation. (nullable, max length 256)

_Example: Replace a leaked key and revoke it at once_

Creates a replacement owned by the same user and merchant and, because the overlap is zero hours, revokes the replaced key in the same operation, recording the reason against it. Send a positive overlapHours instead to keep the replaced key working while you deploy the new one. The replacement expires at the date sent; leave expireAt out to give it the replaced key's original term. The server generates the replacement's key value and returns it once in the response.

```json
{
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
}
```

## Responses

### 200

OK

**Content type:** `application/json`

Schema: [`ApiKeyRevealedDto`](https://devportal.demo.winkpg.io/docs/api/models/ApiKeyRevealedDto.md)

Properties:
- `id` (string(uuid))
- `name` (string): Gets or sets the display name of the API key. (nullable)
- `keyPrefix` (string): Gets or sets the leading characters of the key value, safe to display. `null` for a key  the rewrap backfill has not reached. (nullable)
- `last4` (string): Gets or sets the trailing characters of the key value, safe to display. `null` for a key  the rewrap backfill has not reached. (nullable)
- `environment` ([ApiKeyEnvironment](https://devportal.demo.winkpg.io/docs/api/models/ApiKeyEnvironment.md)): Gets or sets which world the key acts in, or `null` when it has never been stamped. (nullable)
  Values:
  - `Test`: The key acts against the processor's test host. No live money moves. Minted with the sk_test_ prefix.
  - `Live`: The key acts against the processor's live host. Minted with the sk_live_ prefix.
- `status` ([ApiKeyStatus](https://devportal.demo.winkpg.io/docs/api/models/ApiKeyStatus.md)): Gets or sets the key's administrative state.
  Values:
  - `Active`: The key is in service. Whether it is currently accepted also depends on its expiry.
  - `Revoked`: The key has been revoked and is rejected at authentication for good. Revoked keys are retained rather than deleted so the audit trail of what the key did survives it.
  - `Suspended`: The key has been put out of service temporarily, pending someone deciding whether the use that triggered it was legitimate. Rejected at authentication exactly as a revoked key is, and reinstatable, which is the whole reason it is not one.
- `maskedKey` (string): Gets the key's display form: its retained prefix, an ellipsis, and its last characters. This  is the only representation of the value any read path carries. (nullable, read only)
- `lastUsedAt` (string(date-time)): Gets or sets the UTC instant the key was last used to authenticate, or `null` when it  has no recorded use. (nullable)
- `creationTime` (string(date-time)): Gets or sets the UTC instant the key was created.
- `merchantId` (string(uuid)): Gets or sets the merchant the key was minted for, or `null` when it is not tied to one. (nullable)
- `active` (boolean): Gets or sets a value indicating whether the API key is active.
- `expireAt` (string(date-time)): Gets or sets the expiration date for the API key. Null indicates the key does not expire. (nullable)
- `userId` (string(uuid)): Gets or sets the user ID that owns this API key.
- `replacesKeyId` (string(uuid)): Gets or sets the key this one was minted to replace, or `null` when it was not created  by a rotation. (nullable)
- `replacedByKeyId` (string(uuid)): Gets or sets the key minted to replace this one, or `null` when it has not been rotated. (nullable)
- `overlapExpiresAt` (string(date-time)): Gets or sets when this key's rotation overlap closes and it stops authenticating, or  `null` when it is not in one. (nullable)
- `allowedCidrs` (array<string>): Gets or sets the source addresses this key may be used from, as CIDR ranges or bare  addresses, or `null` when it is not bound to any and may be used from anywhere. (nullable)
- `scopes` (array<string>): Gets or sets the capability scopes this key is restricted to, or `null` when it is  unrestricted and may reach everything its owner can. (nullable)
- `key` (string): Gets or sets the plaintext API key value. Shown once, at creation, and never again. (nullable)
- `replacedKeyOverlapExpiresAt` (string(date-time)): Gets or sets when the key this one replaced stops authenticating, or `null` when this key  was not created by a rotation, or was created by one that cut over immediately. (nullable)

### 403

Forbidden

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

### 401

Unauthorized

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

### 400

Bad Request

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

_Example: Request failed validation_

One or more fields were rejected before any rule ran. error.code is null on the envelope and the causes are in validationErrors, one entry per failure. An entry carries code when the validator declared a publishable one, and memberPaths when the full path says more than members does (an element inside a collection, for example). Both keys are omitted when they would add nothing.

```json
{
  "error": {
    "code": "null",
    "message": "Your request is not valid!",
    "details": "The following errors were detected during validation.",
    "data": {
      "correlationId": "0123456789abcdef0123456789abcdef"
    },
    "validationErrors": [
      {
        "message": "'Amount' must be greater than 0.",
        "members": [
          "amount"
        ]
      },
      {
        "message": "The card has expired.",
        "members": [
          "expirationDate"
        ],
        "code": "CardData:CardExpired"
      },
      {
        "message": "'Value' must not be empty.",
        "members": [
          "value"
        ],
        "memberPaths": [
          "customFields[2].value"
        ]
      }
    ]
  }
}
```

### 404

Not Found

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

_Example: Resource not found_

The id in the path names no record the caller can see. Most resources answer with a null error.code and a message naming the resource type and the id; a resource that publishes a not-found code in the catalog above carries it in error.code instead, so check for one before matching on the message.

```json
{
  "error": {
    "code": "null",
    "message": "There is no entity Transaction with id = 7d1f3a52-0c4e-4b8a-9e21-5a6b7c8d9e00!",
    "details": "null",
    "data": {
      "correlationId": "0123456789abcdef0123456789abcdef"
    },
    "validationErrors": "null"
  }
}
```

### 501

Not Implemented

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

### 500

Internal Server Error

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

### default

The request failed. The body carries the standard error envelope: a machine-readable `error.code`, a human-readable `error.message`, and `error.validationErrors` when the failure was a validation rejection. The [error reference](https://devportal.demo.winkpg.io/docs/errors.md) lists the values `error.code` can take.

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

_Example: Business rule refused the request_

The request was understood and rejected by a platform rule. This is the shape that carries a code from the catalog above, so branch on error.code rather than on the message text. The HTTP status is the one listed against the code.

```json
{
  "error": {
    "code": "Transactions:OperationNotAllowed",
    "message": "The operation 'Void' is not allowed on a Sale transaction with result 'Approved' and settlement state 'Settled'.",
    "details": "null",
    "data": {
      "correlationId": "0123456789abcdef0123456789abcdef"
    },
    "validationErrors": "null"
  }
}
```

### 429

The request was refused because a rate limit was exceeded, or because something a later retry can clear stopped it. A rate limit refusal carries an `application/problem+json` body: wait at least the interval `Retry-After` names before retrying, then back off. Limits are tuned per deployment, so read the allowance from the response headers rather than assuming a fixed ceiling. Any other refusal carries the standard error envelope as `application/json`, and its `error.code` names the cause.

**Content type:** `application/problem+json`

Schema: [`RateLimitProblemDetails`](https://devportal.demo.winkpg.io/docs/api/models/RateLimitProblemDetails.md)

Properties:
- `type` (string) required: The problem type identifier. Always the same value: the failure is the status code itself,  so there is no sub-type for a caller to branch on. (nullable)
- `title` (string) required: A short, human-readable summary of the problem type. (nullable)
- `status` (integer(int32)) required: The HTTP status code, repeated in the body as the problem-details format defines.
- `detail` (string) required: A human-readable explanation of this occurrence of the problem. (nullable)
- `retryAfterSeconds` (integer(int32)) required: How long to wait before retrying, in whole seconds, carrying the same figure as the  `Retry-After` header. Always at least one: a value of zero would invite an immediate  retry that is certain to be rejected again.

**Content type:** `application/json`

Schema: [`RemoteServiceErrorResponse`](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorResponse.md)

Properties:
- `error` ([RemoteServiceErrorInfo](https://devportal.demo.winkpg.io/docs/api/models/RemoteServiceErrorInfo.md))

## Example request

Every block below sends the same request. Replace {{BASE_URL}} with the address of the API you are calling and {{API_KEY}} with your own key.

The request body is a RotateApiKeyDto. See the Request body section below for its fields.

### cURL

```bash
curl -X POST "{{BASE_URL}}/api/api-keys/{id}/rotate" \
  -H "api-key: {{API_KEY}}" \
  -H "Content-Type: application/json" \
  -d '{
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
}'
```

### PowerShell

```powershell
$headers = @{
    'api-key' = '{{API_KEY}}'
}

$body = @'
{
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
}
'@

$response = Invoke-RestMethod -Method POST -Uri '{{BASE_URL}}/api/api-keys/{id}/rotate' `
    -Headers $headers -ContentType 'application/json' -Body $body
```

### TypeScript (SDK)

```bash
npm install @winkpg/winkpg-api
```

```typescript
import { Configuration, APIKeysApi } from '@winkpg/winkpg-api';

const api = new APIKeysApi(new Configuration({
  basePath: '{{BASE_URL}}',
  apiKey: '{{API_KEY}}',
}));

const { data } = await api.apiKeysRotate("3fa85f64-5717-4562-b3fc-2c963f66afa6", {
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
});
```

### TypeScript (raw HTTP)

```typescript
const response = await fetch('{{BASE_URL}}/api/api-keys/{id}/rotate', {
  method: 'POST',
  headers: {
    "api-key": "{{API_KEY}}",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "overlapHours": 0,
    "expireAt": "2030-12-31",
    "reason": "Key found in a public repository; replaced and revoked at once."
  }),
});

const data = await response.json();
```

### C# (SDK)

```bash
dotnet add package WinkPg.Api.Client
```

```csharp
using WinkPg.Api.Client.Api;
using WinkPg.Api.Client.Client;
using System.Text.Json;

var config = new Configuration { BasePath = "{{BASE_URL}}" };
config.AddApiKey("api-key", "{{API_KEY}}");

var api = new APIKeysApi(config);
var body = JsonSerializer.Deserialize<RotateApiKeyDto>("""
    {
      "overlapHours": 0,
      "expireAt": "2030-12-31",
      "reason": "Key found in a public repository; replaced and revoked at once."
    }
    """);

var result = await api.ApiKeysRotateAsync(Guid.Parse("3fa85f64-5717-4562-b3fc-2c963f66afa6"), body);
```

### C# (raw HTTP)

```csharp
using System.Text;

using var http = new HttpClient { BaseAddress = new Uri("{{BASE_URL}}") };

var request = new HttpRequestMessage(new HttpMethod("POST"), "/api/api-keys/{id}/rotate");
request.Headers.Add("api-key", "{{API_KEY}}");

request.Content = new StringContent("""
    {
      "overlapHours": 0,
      "expireAt": "2030-12-31",
      "reason": "Key found in a public repository; replaced and revoked at once."
    }
    """, Encoding.UTF8, "application/json");

var response = await http.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
```

### Python (SDK)

```bash
pip install winkpg-api
```

```python
import winkpg_api

configuration = winkpg_api.Configuration(host="{{BASE_URL}}")
configuration.api_key["ApiKey"] = "{{API_KEY}}"

with winkpg_api.ApiClient(configuration) as client:
    api = winkpg_api.APIKeysApi(client)
    body = winkpg_api.RotateApiKeyDto.from_dict({
      "overlapHours": 0,
      "expireAt": "2030-12-31",
      "reason": "Key found in a public repository; replaced and revoked at once."
    })
    result = api.api_keys_rotate("3fa85f64-5717-4562-b3fc-2c963f66afa6", body)
```

### Python (raw HTTP)

```bash
pip install requests
```

```python
import requests

headers = {
    "api-key": "{{API_KEY}}",
    "Content-Type": "application/json",
}

body = {
  "overlapHours": 0,
  "expireAt": "2030-12-31",
  "reason": "Key found in a public repository; replaced and revoked at once."
}

response = requests.request(
    "POST",
    "{{BASE_URL}}/api/api-keys/{id}/rotate",
    headers=headers,
    json=body,
)
response.raise_for_status()
data = response.json()
```

## See also

- [All documentation](https://devportal.demo.winkpg.io/llms.txt): the machine-readable index of every public page on this site.
