> ## Documentation Index
> Fetch the complete documentation index at: https://developer.notchpay.co/llms.txt
> Use this file to discover all available pages before exploring further.

# API Response Format

> Understand the structure of Notch Pay API responses

Understanding the structure of Notch Pay API responses is essential for properly integrating with our API. This guide explains the standard response format, common fields, and how to interpret different types of responses.

## Standard Response Format

All Notch Pay API responses follow a consistent JSON format:

```json theme={null}
{
  "code": 200,
  "status": "OK",
  "message": "Descriptive message about the response",
  "data": {
    // Response data specific to the endpoint
  }
}
```

### Response Properties

| Property  | Type         | Description                                           |
| --------- | ------------ | ----------------------------------------------------- |
| `code`    | number       | HTTP status code indicating the result of the request |
| `status`  | string       | Text representation of the HTTP status code           |
| `message` | string       | Human-readable description of the response            |
| `data`    | object/array | The main response data (varies by endpoint)           |

## Success Responses

### Single Resource Response

When retrieving a single resource (like a payment or customer), the response typically looks like this:

```json theme={null}
{
  "code": 200,
  "status": "OK",
  "message": "Payment retrieved",
  "data": {
    "id": "pay_123456789",
    "reference": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "complete",
    "customer": "cus_123456789",
    "created_at": "2023-01-01T12:00:00Z"
  }
}
```

### Collection Response

When retrieving a collection of resources (like a list of payments), the response includes pagination information:

```json theme={null}
{
  "code": 200,
  "status": "OK",
  "message": "Payments retrieved",
  "totals": 50,
  "last_page": 2,
  "current_page": 1,
  "selected": 30,
  "items": [
    {
      "id": "pay_123456789",
      "reference": "order_123",
      "amount": 5000,
      "currency": "XAF",
      "status": "complete"
    },
    // More items...
  ]
}
```

### Pagination Properties

| Property       | Type   | Description                            |
| -------------- | ------ | -------------------------------------- |
| `totals`       | number | Total number of items across all pages |
| `last_page`    | number | Number of the last page                |
| `current_page` | number | Number of the current page             |
| `selected`     | number | Number of items on the current page    |
| `items`        | array  | Array of items on the current page     |

### Creation Response

When creating a new resource, the response typically includes the created resource and a 201 status code:

```json theme={null}
{
  "code": 201,
  "status": "Created",
  "message": "Payment created",
  "data": {
    "id": "pay_123456789",
    "reference": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "pending",
    "created_at": "2023-01-01T12:00:00Z",
    "authorization_url": "https://pay.notchpay.co/pay_123456789"
  }
}
```

### Update Response

When updating a resource, the response typically includes the updated resource:

```json theme={null}
{
  "code": 200,
  "status": "OK",
  "message": "Customer updated",
  "data": {
    "id": "cus_123456789",
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+237600000000",
    "updated_at": "2023-01-01T12:00:00Z"
  }
}
```

### Deletion Response

When deleting a resource, the response typically confirms the deletion:

```json theme={null}
{
  "code": 200,
  "status": "OK",
  "message": "Customer deleted"
}
```

## Error Responses

When an error occurs, the response includes information about what went wrong:

```json theme={null}
{
  "code": 400,
  "status": "Bad Request",
  "message": "Error message describing what went wrong",
  "errors": {
    "field_name": ["Error description for this field"]
  }
}
```

For more information about error responses, see the [Error Handling](/get-started/errors) guide.

## Response Formats for Specific Endpoints

### Payments API

#### Create Payment

```json theme={null}
{
  "code": 201,
  "status": "Created",
  "message": "Payment initialized",
  "data": {
    "id": "pay_123456789",
    "reference": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "pending",
    "customer": "cus_123456789",
    "created_at": "2023-01-01T12:00:00Z",
    "authorization_url": "https://pay.notchpay.co/pay_123456789"
  }
}
```

#### Retrieve Payment

```json theme={null}
{
  "code": 200,
  "status": "OK",
  "message": "Payment retrieved",
  "data": {
    "id": "pay_123456789",
    "reference": "order_123",
    "amount": 5000,
    "currency": "XAF",
    "status": "complete",
    "customer": "cus_123456789",
    "payment_method": "pm.ndzAfIh555VCPML1",
    "created_at": "2023-01-01T12:00:00Z",
    "completed_at": "2023-01-01T12:05:00Z"
  }
}
```

### Transfers API

#### Create Transfer

```json theme={null}
{
  "code": 201,
  "status": "Created",
  "message": "Transfer initiated",
  "data": {
    "id": "trf_123456789",
    "reference": "salary_jan_2023",
    "amount": 5000,
    "currency": "XAF",
    "status": "pending",
    "beneficiary": "ben_123456789",
    "channel": "cm.mtn",
    "description": "Salary payment",
    "created_at": "2023-01-01T12:00:00Z"
  }
}
```

### Customers API

#### Create Customer

```json theme={null}
{
  "code": 201,
  "status": "Created",
  "message": "Customer created",
  "data": {
    "id": "cus_123456789",
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+237600000000",
    "created_at": "2023-01-01T12:00:00Z"
  }
}
```

## Response Fields

### Common Fields

These fields appear in most resource objects:

| Field        | Type   | Description                                           |
| ------------ | ------ | ----------------------------------------------------- |
| `id`         | string | Unique identifier for the resource                    |
| `created_at` | string | ISO 8601 timestamp when the resource was created      |
| `updated_at` | string | ISO 8601 timestamp when the resource was last updated |

### Timestamps

All timestamps in Notch Pay API responses are in ISO 8601 format with UTC timezone:

```
YYYY-MM-DDTHH:MM:SSZ
```

Example: `2023-01-01T12:00:00Z`

## Handling Responses in Different Programming Languages

### JavaScript

```javascript theme={null}
fetch('https://api.notchpay.co/payments', {
  method: 'POST',
  headers: {
    'Authorization': 'YOUR_PUBLIC_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    amount: 5000,
    currency: 'XAF',
    customer: {
      email: 'customer@example.com'
    }
  })
})
.then(response => response.json())
.then(data => {
  if (data.code >= 200 && data.code < 300) {
    // Success
    console.log('Success:', data.message);
    console.log('Payment ID:', data.data.id);
    console.log('Authorization URL:', data.data.authorization_url);
  } else {
    // Error
    console.error('Error:', data.message);
    if (data.errors) {
      console.error('Validation errors:', data.errors);
    }
  }
})
.catch(error => {
  console.error('Request failed:', error);
});
```

### PHP

```php theme={null}
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.notchpay.co/payments');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'amount' => 5000,
    'currency' => 'XAF',
    'customer' => [
        'email' => 'customer@example.com'
    ]
]));

$headers = [
    'Authorization: YOUR_PUBLIC_KEY',
    'Content-Type: application/json'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if ($data['code'] >= 200 && $data['code'] < 300) {
    // Success
    echo "Success: " . $data['message'] . "\n";
    echo "Payment ID: " . $data['data']['id'] . "\n";
    echo "Authorization URL: " . $data['data']['authorization_url'] . "\n";
} else {
    // Error
    echo "Error: " . $data['message'] . "\n";
    if (isset($data['errors'])) {
        echo "Validation errors:\n";
        foreach ($data['errors'] as $field => $errors) {
            echo "- $field: " . implode(', ', $errors) . "\n";
        }
    }
}
```

### Python

```python theme={null}
import requests
import json

url = "https://api.notchpay.co/payments"
payload = {
    "amount": 5000,
    "currency": "XAF",
    "customer": {
        "email": "customer@example.com"
    }
}
headers = {
    "Authorization": "YOUR_PUBLIC_KEY",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()

if 200 <= data['code'] < 300:
    # Success
    print("Success:", data['message'])
    print("Payment ID:", data['data']['id'])
    print("Authorization URL:", data['data']['authorization_url'])
else:
    # Error
    print("Error:", data['message'])
    if 'errors' in data:
        print("Validation errors:")
        for field, errors in data['errors'].items():
            print(f"- {field}: {', '.join(errors)}")
```

## Best Practices

1. **Check the Status Code**: Always check the `code` field to determine if the request was successful.

2. **Handle Pagination**: When working with collection endpoints, implement pagination to retrieve all results.

```javascript theme={null}
// Example of handling pagination in JavaScript
async function getAllPayments() {
  let page = 1;
  let allPayments = [];
  let hasMorePages = true;
  
  while (hasMorePages) {
    const response = await fetch(`https://api.notchpay.co/payments?page=${page}`, {
      headers: {
        'Authorization': 'YOUR_PUBLIC_KEY'
      }
    });
    
    const data = await response.json();
    
    if (data.code === 200) {
      allPayments = allPayments.concat(data.items);
      
      if (data.current_page < data.last_page) {
        page++;
      } else {
        hasMorePages = false;
      }
    } else {
      throw new Error(data.message);
    }
  }
  
  return allPayments;
}
```

3. **Parse Timestamps**: Convert timestamp strings to Date objects for easier manipulation.

```javascript theme={null}
const createdAt = new Date(payment.created_at);
console.log('Payment created on:', createdAt.toLocaleDateString());
```

4. **Handle Empty Collections**: When retrieving collections, check if the `items` array is empty.

```javascript theme={null}
if (data.items.length === 0) {
  console.log('No payments found.');
} else {
  console.log(`Found ${data.totals} payments.`);
}
```

5. **Extract Relevant Data**: Only extract the data you need from the response to simplify your code.

```javascript theme={null}
const { id, amount, currency, status } = data.data;
console.log(`Payment ${id}: ${amount} ${currency} (${status})`);
```

## Next Steps

* [API Reference](/api-reference/index) - Explore the complete API documentation
* [Authentication](/get-started/authentication) - Learn about authentication methods
* [Error Handling](/get-started/errors) - Understand how to handle API errors
