# Uploading a Case

The full API for file uploads is documented here: <https://api.digicust.com/upload/api-docs/>

{% tabs %}
{% tab title="CURL" %}

```bash
curl -X POST https://api.digicust.com/upload/api/{customerId}/{projectId}/new \
     -H "Content-Type: multipart/form-data" \
     -H "Authorization: Bearer {access_token}" \
     -F "files[]=@/path/to/file1.pdf" \
     -F "files[]=@/path/to/file2.pdf" \
     -F "classifications=[{\"fileName\":\"file1.pdf\",\"documentType\":\"invoice\"},{\"fileName\":\"file2.pdf\",\"documentType\":\"waybill\"}]" \
     -F "executionStrategyId={executionStrategyId}" \
     -F "reference={reference}" \
     -F "documents=[{\"priority\":\"afterNormalization\",\"annotatedAggregated\":{}}]"

```

{% endtab %}

{% tab title="JavaScript (fetch)" %}

```javascript
const file1 = new File(['content1'], 'filename1.pdf');
const file2 = new File(['content2'], 'filename2.pdf');

const files = [file1, file2];

const classifications = [
  { fileName: 'filename1.pdf', documentType: 'invoice' },
  { fileName: 'filename2.pdf', documentType: 'waybill' },
];

const executionStrategyId = 'strategyId123';
const reference = 'reference123';
const documents = [{ priority: 'afterNormalization', annotatedAggregated: {} }];

const uploadCase = async (customerId, projectId, files, classifications, executionStrategyId, reference, documents) => {
  const url = `https://api.digicust.com/upload/api/${customerId}/${projectId}/new`;

  const formData = new FormData();

  files.forEach((file, index) => {
    formData.append('files[]', file, classifications[index].fileName);
  });

  formData.append('classifications', JSON.stringify(classifications));
  formData.append('executionStrategyId', executionStrategyId);

  if (reference) formData.append('reference', reference);
  if (documents) formData.append('documents', JSON.stringify(documents));

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`
      },
      body: formData,
    });

    const data = await response.json();
    console.log(data);
  } catch (err) {
    console.error('Error:', err);
  }
};

uploadCase(
  'customerId123',
  'projectId123',
  files,
  classifications,
  executionStrategyId,
  reference,
  documents
);

```

{% endtab %}

{% tab title="JavaScript (axios)" %}

```javascript
const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');

// Assuming that we've authenticated and saved the access token
const accessToken = '<YOUR ACCESS TOKEN>';

const uploadCase = async (customerId, projectId, files, classifications, executionStrategyId, reference, documents) => {
  const url = `https://api.digicust.com/upload/api/${customerId}/${projectId}/new`;

  const form = new FormData();

  // Attaching files
  files.forEach(file => {
    form.append('files[]', fs.createReadStream(file));
  });

  // Attaching other parameters
  form.append('classifications', JSON.stringify(classifications));
  form.append('executionStrategyId', executionStrategyId);

  if (reference) form.append('reference', reference);
  if (documents) form.append('documents', JSON.stringify(documents));

  try {
    const response = await axios.post(url, form, {
      headers: {
        ...form.getHeaders(),  // Important, this sets the correct multipart boundary
        'Authorization': `Bearer ${accessToken}`
      }
    });

    console.log(response.data);
  } catch (err) {
    console.error('Error:', err);
  }
};

// Example usage:
uploadCase(
  'customerId123',
  'projectId123',
  ['./file1.pdf', './file2.pdf'],
  [
    { fileName: 'file1.pdf', documentType: 'invoice' },
    { fileName: 'file2.pdf', documentType: 'waybill' }
  ],
  'strategyId123',
  'reference123',
  [{ priority: 'afterNormalization', annotatedAggregated: {} }]
);

```

{% endtab %}

{% tab title="Visual Basic.NET" %}

```visual-basic
Imports System.Net.Http
Imports Newtonsoft.Json

' Your authentication code goes here
Dim accessToken As String = "<YOUR ACCESS TOKEN>"

' Create an HttpClient and set the authorization header
Dim client As New HttpClient()
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", accessToken)

' URL parameters
Dim customerId As String = "<YOUR CUSTOMER ID>"
Dim projectId As String = "<YOUR PROJECT ID>"
Dim url As String = $"https://api.digicust.com/upload/api/{customerId}/{projectId}/new"

' Create a MultipartFormDataContent
Dim form As New MultipartFormDataContent()

' Adding files
Dim files() As String = {"./file1.pdf", "./file2.pdf"}
For Each file In files
    Dim fileContent As New ByteArrayContent(System.IO.File.ReadAllBytes(file))
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream")
    form.Add(fileContent, "files[]", System.IO.Path.GetFileName(file))
Next

' Adding other parameters
Dim classifications As New List(Of Object) From {
    New With {.fileName = "file1.pdf", .documentType = "invoice"},
    New With {.fileName = "file2.pdf", .documentType = "waybill"}
}
form.Add(New StringContent(JsonConvert.SerializeObject(classifications)), "classifications")

Dim executionStrategyId As String = "<YOUR STRATEGY ID>"
form.Add(New StringContent(executionStrategyId), "executionStrategyId")

Dim reference As String = "<YOUR REFERENCE>"
form.Add(New StringContent(reference), "reference")

Dim documents As New List(Of Object) From {
    New With {.priority = "afterNormalization", .annotatedAggregated = New Object()}
}
form.Add(New StringContent(JsonConvert.SerializeObject(documents)), "documents")

' Send the request and get the response
Dim response As HttpResponseMessage = client.PostAsync(url, form).Result

' Output the result
Console.WriteLine(response.Content.ReadAsStringAsync().Result)
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import json
import requests

# Assuming that we've authenticated and saved the access token
access_token = "<YOUR ACCESS TOKEN>"

def upload_case(customer_id, project_id, files, classifications, execution_strategy_id, reference=None, documents=None):
    url = f"https://api.digicust.com/upload/api/{customer_id}/{project_id}/new"

    headers = {
        'Authorization': f'Bearer {access_token}'
    }

    data = {
        'classifications': json.dumps(classifications),
        'executionStrategyId': execution_strategy_id
    }

    if reference:
        data['reference'] = reference
    if documents:
        data['documents'] = json.dumps(documents)

    file_data = [(os.path.basename(file), open(file, 'rb')) for file in files]

    response = requests.post(url, headers=headers, files=file_data, data=data)

    print(response.json())

# Example usage:
upload_case(
    'customerId123',
    'projectId123',
    ['./file1.pdf', './file2.pdf'],
    [
        { 'fileName': 'file1.pdf', 'documentType': 'invoice' },
        { 'fileName': 'file2.pdf', 'documentType': 'waybill' }
    ],
    'strategyId123',
    'reference123',
    [
        { 'priority': 'afterNormalization', 'annotatedAggregated': {} }
    ]
)

```

{% endtab %}
{% endtabs %}

### Endpoint: `https://api.digicust.com/upload/api/{customerId}/{projectId}/new`

This endpoint is used for uploading new cases.

#### HTTP Method

POST

#### Headers

| Header        | Description            |
| ------------- | ---------------------- |
| Content-Type  | multipart/form-data    |
| Authorization | Bearer {access\_token} |

#### URL Parameters

| Parameter  | Type   | Description                            |
| ---------- | ------ | -------------------------------------- |
| customerId | string | The unique identifier of the customer. |
| projectId  | string | The unique identifier of the project.  |

#### Request Body

The request body should be of type `multipart/form-data` with the following parameters:

| Parameter           | Type                   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| files\[]            | file                   | The file to be uploaded.                                                                                                                                                                                                                                                                                                                                                                                                                             |
| classifications     | stringified JSON array | A JSON stringified array of objects where each object contains the fileName and the documentType.                                                                                                                                                                                                                                                                                                                                                    |
| executionStrategyId | string                 | The execution strategy identifier.                                                                                                                                                                                                                                                                                                                                                                                                                   |
| reference           | string                 | The case reference. (optional)                                                                                                                                                                                                                                                                                                                                                                                                                       |
| documents           | stringified JSON array | A JSON stringified array of document information (e.g. [emails](https://types.api.digicust.com/interfaces/EmailDocument.html), [invoices](https://types.api.digicust.com/interfaces/InvoiceModel.html), [waybills](https://types.api.digicust.com/interfaces/WaybillModel.html), or most commonly, [UserInput ](https://types.api.digicust.com/interfaces/UserInput.html)objects). Each UserInput object represents raw case information. (optional) |

The [UserInput ](https://types.api.digicust.com/interfaces/UserInput.html)object can have the following properties:

| Property                   | Type                                                                                              | Description                                                                                                                                                                                                                                                                              |
| -------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| priority                   | string                                                                                            | This can take one of the following values: `beforeNormalization` (fallback), `afterNormalization` (overwrite). It indicates the priority of the UserInput object.                                                                                                                        |
| annotatedAggregated        | [AggregatedCaseDataModel](https://types.api.digicust.com/interfaces/AggregatedCaseDataModel.html) | The aggregated case data. This contains the relevant information about the case. For more information about the properties of the AggregatedCaseDataModel, refer to [the AggregatedCaseDataModel specification](https://types.api.digicust.com/interfaces/AggregatedCaseDataModel.html). |
| annotatedExecutionStrategy | [ExecutionStrategy](https://types.api.digicust.com/interfaces/ExecutionStrategy.html)             | If you want to modify, how a customs case is being processed, you can overwrite properties of the [Execution Strategy](https://types.api.digicust.com/interfaces/ExecutionStrategy.html).                                                                                                |
| customValidationMessages   | [ValidationError](https://types.api.digicust.com/interfaces/ValidationError.html)\[]              | You can add error, warning or information messages.                                                                                                                                                                                                                                      |

#### Responses

**Success**

| Code | Description                                                    |
| ---- | -------------------------------------------------------------- |
| 200  | The file has been successfully uploaded and is being processed |

This will return a newly initiated case. Use its `id` for further reference. The case will automatically be processed.
