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

# Delete Expense

> Delete an expense record with proper validation and soft delete functionality

## Overview

The Delete Expense endpoint allows you to remove an expense from your records. The system performs a soft delete, which means the expense is marked as deleted but preserved in the database for audit and compliance purposes.

<Warning>
  Deletion is permanent from the user perspective and cannot be undone through the API. Ensure you really want to delete the expense before calling this endpoint.
</Warning>

## Path Parameters

<ParamField path="id" type="string" required>
  The CzUid of the expense to delete
</ParamField>

## Business Rules

The system will validate that the expense can be safely deleted:

* **Accounting periods**: Expenses in closed accounting periods may not be deletable
* **Integration locks**: Expenses that have been synchronized with external systems may be protected
* **Audit requirements**: Some expenses may be required to be kept for compliance reasons

If an expense cannot be deleted due to business rules, the API will return an appropriate error message.

## Response

<ResponseField name="message" type="string">
  Confirmation message that the expense has been deleted
</ResponseField>

<ResponseField name="id" type="string">
  The CzUid of the deleted expense for reference
</ResponseField>

## Soft Delete Behavior

When an expense is deleted:

1. **Status Update**: The expense is marked as deleted in the database
2. **Timestamp**: A deletion timestamp is recorded
3. **List Exclusion**: The expense will no longer appear in standard list endpoints
4. **Audit Trail**: The deletion is logged for audit purposes
5. **Data Preservation**: All expense data is preserved for compliance and reporting

## Impact on Related Data

Deleting an expense affects related data:

* **Statistics**: The expense is excluded from future statistics calculations
* **Totals**: List totals will be recalculated without this expense
* **Reports**: The expense will not appear in standard reports
* **Attachments**: Any attached files remain in the system but are marked as orphaned

<RequestExample>
  ```bash cURL theme={null}
  curl -X DELETE "https://api.contazen.ro/v1/expenses/exp_abc123" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json"
  ```

  ```javascript JavaScript theme={null}
  const expenseId = 'exp_abc123';

  const response = await fetch(`https://api.contazen.ro/v1/expenses/${expenseId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    }
  });

  const data = await response.json();
  if (data.success) {
    console.log('Expense deleted successfully:', data.id);
  } else {
    console.error('Failed to delete expense:', data.error.message);
  }
  ```

  ```php PHP theme={null}
  $expenseId = 'exp_abc123';

  $curl = curl_init();

  curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.contazen.ro/v1/expenses/{$expenseId}",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_CUSTOMREQUEST => 'DELETE',
      CURLOPT_HTTPHEADER => [
          'Authorization: Bearer YOUR_API_KEY',
          'Content-Type: application/json'
      ]
  ]);

  $response = curl_exec($curl);
  $data = json_decode($response, true);
  curl_close($curl);

  if ($data['success']) {
      echo 'Expense deleted successfully: ' . $data['id'];
  } else {
      echo 'Error: ' . $data['error']['message'];
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 - Success theme={null}
  {
    "success": true,
    "message": "Expense deleted successfully",
    "id": "exp_abc123"
  }
  ```

  ```json 404 - Not Found theme={null}
  {
    "success": false,
    "error": {
      "message": "Expense not found",
      "type": "invalid_request_error",
      "code": "resource_missing",
      "param": "id"
    }
  }
  ```

  ```json 403 - Cannot Delete theme={null}
  {
    "success": false,
    "error": {
      "message": "Expense cannot be deleted due to business rules",
      "type": "invalid_request_error", 
      "code": "delete_restricted",
      "details": "This expense is in a closed accounting period and cannot be modified or deleted"
    }
  }
  ```

  ```json 500 - Delete Failed theme={null}
  {
    "success": false,
    "error": {
      "message": "Failed to delete expense",
      "type": "api_error",
      "code": "delete_failed",
      "details": "An internal error occurred while processing the deletion"
    }
  }
  ```
</ResponseExample>

## Best Practices

### Before Deleting

1. **Verify the expense**: Use the [Retrieve Expense](/api-reference/endpoints/expenses/retrieve) endpoint to confirm you have the correct expense
2. **Check dependencies**: Ensure the expense is not referenced by other records
3. **Consider alternatives**: Sometimes updating an expense to mark it as cancelled is preferable to deletion

### After Deletion

1. **Update local records**: Remove the expense from any local caches or displays
2. **Refresh totals**: Update any calculated totals in your application
3. **Notify users**: Inform relevant users that the expense has been removed

### Error Handling

Always handle potential errors gracefully:

* **404 errors**: The expense may have already been deleted or the ID is incorrect
* **403 errors**: Business rules prevent deletion - inform the user why
* **500 errors**: Technical issues - retry or contact support

### Alternative Actions

Consider these alternatives to deletion:

* **Void the expense**: Mark it as cancelled while preserving the record
* **Reduce amount to zero**: Keep the expense but remove its financial impact
* **Archive**: Move to an archived status instead of deleting


## OpenAPI

````yaml DELETE /expenses/{id}
openapi: 3.1.0
info:
  title: Contazen API
  version: 1.2.0
  description: >
    Build powerful integrations with the Contazen invoicing platform. The
    Contazen API is organized around REST, 

    has predictable resource-oriented URLs, accepts JSON request bodies, returns
    JSON-encoded responses, 

    and uses standard HTTP response codes, authentication, and verbs.


    ## Authentication

    The API uses Bearer token authentication. Include your API key in the
    Authorization header.


    ### Getting your API Key

    1. Log in to your Contazen account

    2. Navigate to Settings > API

    3. Generate or copy your API key (starts with `sk_live_` for production or
    `sk_test_` for testing)


    ### Using the API Key

    Include your API key in the Authorization header:

    ```

    Authorization: Bearer sk_live_YOUR_API_KEY

    ```


    ### Example Request with cURL

    ```bash

    curl --request GET \
      --url https://api.contazen.ro/v1/clients \
      --header 'Authorization: Bearer sk_live_YOUR_API_KEY' \
      --header 'Accept: application/json'
    ```


    ## Rate Limiting

    - 1000 requests per hour per API key

    - 100 create operations per minute per API key


    Rate limit information is included in response headers:

    - `X-RateLimit-Limit`: Maximum requests allowed

    - `X-RateLimit-Remaining`: Requests remaining

    - `X-RateLimit-Reset`: Reset time (Unix timestamp)


    ## Pagination

    All list endpoints return paginated results with the following format:

    ```json

    {
      "success": true,
      "data": {
        "object": "list",
        "data": [...],
        "has_more": true,
        "total": 245,
        "page": 1,
        "per_page": 50,
        "total_pages": 5
      },
      "meta": {
        "version": "v1",
        "request_id": "req_1a2b3c4d",
        "response_time": "23.45ms"
      }
    }

    ```


    ## Multi-Work-Point Access

    API keys belong to a specific work point but can access data from all work
    points

    within the same parent company.


    ## Error Handling

    The API uses conventional HTTP response codes to indicate success or
    failure. 

    In general: 2xx codes indicate success, 4xx codes indicate an error due to
    the 

    information provided, and 5xx codes indicate an error with Contazen's
    servers.


    ## Expanding Nested Objects

    Many endpoints support the `expand` parameter to include related objects in
    the response.

    This follows the Stripe API pattern. For example:

    - `expand[]=lines` - Include invoice line items

    - `expand[]=payments` - Include payment records

    - `expand[]=client` - Include full client object


    ## Localization

    The API supports multiple languages through:

    - `locale` query parameter (en, ro)

    - `Accept-Language` header

    - Default: English
  contact:
    name: Contazen Support
    email: support@contazen.ro
    url: https://contazen.ro
  license:
    name: Proprietary
    url: https://www.contazen.ro/termeni-si-conditii-de-utilizare/
servers:
  - url: https://api.contazen.ro/v1
    description: Production API server
security:
  - bearerAuth: []
tags:
  - name: Authentication
    description: API authentication and test endpoints
  - name: Clients
    description: Manage your customers (B2B and B2C)
  - name: Invoices
    description: Create and manage invoices, proformas, and receipts
  - name: Products
    description: Manage your product and service catalog
  - name: Expenses
    description: Track and manage business expenses
  - name: Expense Categories
    description: Organize expenses with categories
  - name: Suppliers
    description: Manage expense suppliers and vendors
  - name: Settings
    description: API settings and configuration
  - name: Payments
    description: Payments received against invoices
  - name: Receipts
    description: Cash receipts (chitanțe) — standalone or paired with an invoice
  - name: Company Lookup
    description: Romanian company lookup (ANAF / VIES)
  - name: Invoice Series
    description: Manage invoice numbering series
  - name: Bank Accounts
    description: Manage IBAN bank accounts
  - name: E-Factura
    description: Romanian e-invoicing status and configuration
  - name: Supplier Bills
    description: Supplier invoices imported from the ANAF SPV inbox
  - name: VAT Rates
    description: Firm-scoped custom VAT rates on top of the Romanian catalog
  - name: Currencies
    description: Currencies enabled for the firm's bill templates
  - name: Languages
    description: Languages enabled for the firm's bill templates
  - name: Conta
    description: |
      Public ANAF data for the firm's CUI: fiscal profile (TVA scope, RTVAI,
      split TVA, status, e-Factura registration, CAEN) and annual balance
      sheets (cifra de afaceri, profit, capitaluri, datorii, salariați).

      Powered by the public ANAF webservices (no OAuth required for these
      endpoints). The data is cached locally and refreshed on demand via
      the `/sync` actions.
paths:
  /expenses/{id}:
    delete:
      tags:
        - Expenses
      summary: Delete an expense
      description: >
        Permanently deletes an expense (hard delete, not soft delete).


        ## Important Notes

        - This is a HARD delete operation - the expense is permanently removed

        - Unlike other entities that use soft delete, expenses are completely
        removed from the database

        - Cannot be undone once deleted
      operationId: deleteExpense
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      responses:
        '200':
          description: Expense deleted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          $ref: '#/components/responses/NotFoundError'
components:
  schemas:
    ResponseMeta:
      type: object
      properties:
        version:
          type: string
          default: v1
        request_id:
          type: string
          format: uuid
          description: Unique request identifier for debugging
        response_time:
          type: string
          example: 23.45ms
    ErrorResponse:
      type: object
      required:
        - success
        - error
      properties:
        success:
          type: boolean
          default: false
        error:
          type: object
          required:
            - message
            - type
            - code
          properties:
            message:
              type: string
              description: Human-readable error message
            type:
              type: string
              enum:
                - api_error
                - authentication_error
                - invalid_request_error
                - rate_limit_error
                - permission_error
                - validation_error
            code:
              type: string
              description: Machine-readable error code
            param:
              type: string
              description: The parameter that caused the error
            doc_url:
              type: string
              format: uri
              description: URL to relevant documentation
        meta:
          $ref: '#/components/schemas/ResponseMeta'
  responses:
    UnauthorizedError:
      description: API key is missing or invalid
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFoundError:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Use your API key (sk_live_xxx or sk_test_xxx)

````