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

# File

> Carica e gestisci file JSON da utilizzare come contesto nelle richieste API

Attraverso l’endpoint Olostep `/v1/files` puoi caricare file JSON che possono essere utilizzati come contesto nelle tue richieste API. Questo ti permette di fornire dati strutturati per migliorare i tuoi scraping, risposte e altre operazioni.

* Carica file JSON fino a 200MB
* I file sono automaticamente validati per il corretto formato JSON
* Usa i file come contesto in scraping, risposte e altri endpoint
* I file scadono dopo 30 giorni
* Processo di caricamento sicuro tramite URL pre-firmato

Per i dettagli dell'API, consulta la [Documentazione dell'Endpoint File](/api-reference/files/create).

## Installazione

<CodeGroup>
  ```python Python theme={null}
  # pip install requests

  import requests
  ```

  ```js Node theme={null}
  // npm install node-fetch

  // ESM
  import fetch from 'node-fetch'

  // CommonJS
  const fetch = require('node-fetch')
  ```

  ```bash cURL theme={null}
  # macOS: il curl integrato va bene
  ```
</CodeGroup>

## Carica un file

Il processo di caricamento del file consiste in due passaggi:

1. **Crea URL di caricamento**: Richiedi un URL pre-firmato per caricare il tuo file
2. **Completa il caricamento**: Carica il tuo file all'URL pre-firmato, quindi chiama l'endpoint di completamento per validare e finalizzare

### Passaggio 1: Crea URL di caricamento

Per prima cosa, crea un URL di caricamento fornendo il nome del file e un eventuale scopo. Il parametro `purpose` supporta solo due valori: `"context"` (predefinito) o `"batch"`.

<CodeGroup>
  ```python Python theme={null}
  import requests
  import json

  API_KEY = "<YOUR_API_KEY>"
  API_URL = "https://api.olostep.com/v1"

  # Step 1: Create upload URL
  payload = {
      "filename": "my-data.json",
      "purpose": "context"  # Facoltativo, predefinito "context". Valori supportati: "context" o "batch"
  }

  headers = {
      "Authorization": f"Bearer {API_KEY}",
      "Content-Type": "application/json"
  }

  response = requests.post(f"{API_URL}/files", headers=headers, json=payload)
  upload_data = response.json()

  print(json.dumps(upload_data, indent=2))
  # La risposta include: id, upload_url, expires_in
  ```

  ```js Node theme={null}
  const API_URL = 'https://api.olostep.com/v1'

  const res = await fetch(`${API_URL}/files`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>', 'Content-Type': 'application/json' },
    body: JSON.stringify({
      filename: 'my-data.json',
      purpose: 'context'  // Facoltativo, predefinito "context". Valori supportati: "context" o "batch"
    })
  })
  const uploadData = await res.json()
  console.log(uploadData)
  ```

  ```bash cURL theme={null}
  curl -s -X POST "https://api.olostep.com/v1/files" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "filename": "my-data.json",
      "purpose": "context"
    }'

  # Esempio con scopo "batch":
  curl -s -X POST "https://api.olostep.com/v1/files" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "filename": "batch-data.json",
      "purpose": "batch"
    }'
  ```
</CodeGroup>

La risposta include un `upload_url` pre-firmato che scade in 10 minuti:

```json theme={null}
{
  "id": "file_abc123xyz789",
  "object": "file.upload",
  "created": 1760329882,
  "upload_url": "https://olostep-files.s3.amazonaws.com/files/...",
  "expires_in": 600
}
```

### Passaggio 2: Carica il file e completa

Carica il tuo file JSON all'URL pre-firmato, quindi chiama l'endpoint di completamento per validare e finalizzare il caricamento.

<CodeGroup>
  ```python Python theme={null}
  import requests
  import json

  API_KEY = "<YOUR_API_KEY>"
  API_URL = "https://api.olostep.com/v1"

  # Dopo aver ottenuto upload_url dal Passaggio 1
  file_id = upload_data["id"]
  upload_url = upload_data["upload_url"]

  # Prepara i tuoi dati JSON
  json_data = {
      "users": [
          {"name": "John Doe", "email": "john@example.com"},
          {"name": "Jane Smith", "email": "jane@example.com"}
      ]
  }

  # Step 2a: Carica il file all'URL pre-firmato
  upload_response = requests.put(
      upload_url,
      data=json.dumps(json_data),
      headers={"Content-Type": "application/json"}
  )
  upload_response.raise_for_status()

  # Step 2b: Completa il caricamento
  complete_response = requests.post(
      f"{API_URL}/files/{file_id}/complete",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  file_info = complete_response.json()

  print(json.dumps(file_info, indent=2))
  ```

  ```js Node theme={null}
  const API_URL = 'https://api.olostep.com/v1'

  // Dopo aver ottenuto upload_url dal Passaggio 1
  const fileId = uploadData.id
  const uploadUrl = uploadData.upload_url

  // Prepara i tuoi dati JSON
  const jsonData = {
    users: [
      { name: 'John Doe', email: 'john@example.com' },
      { name: 'Jane Smith', email: 'jane@example.com' }
    ]
  }

  // Step 2a: Carica il file all'URL pre-firmato
  await fetch(uploadUrl, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(jsonData)
  })

  // Step 2b: Completa il caricamento
  const completeRes = await fetch(`${API_URL}/files/${fileId}/complete`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const fileInfo = await completeRes.json()
  console.log(fileInfo)
  ```

  ```bash cURL theme={null}
  # Step 2a: Carica il file all'URL pre-firmato
  curl -X PUT "$UPLOAD_URL" \
    -H "Content-Type: application/json" \
    -d @my-data.json

  # Step 2b: Completa il caricamento
  curl -s -X POST "https://api.olostep.com/v1/files/$FILE_ID/complete" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"
  ```
</CodeGroup>

L'endpoint di completamento valida il file JSON e restituisce i metadati del file:

```json theme={null}
{
  "id": "file_abc123xyz789",
  "object": "file",
  "created": 1760329882,
  "filename": "my-data.json",
  "bytes": 1024,
  "purpose": "context",
  "status": "completed"
}
```

## Recupera i metadati del file tramite ID

Recupera i metadati di un file tramite il suo ID.

<CodeGroup>
  ```python Python theme={null}
  file_id = "file_abc123xyz789"
  response = requests.get(
      f"{API_URL}/files/{file_id}",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  file_info = response.json()
  print(json.dumps(file_info, indent=2))
  ```

  ```js Node theme={null}
  const fileId = 'file_abc123xyz789'
  const res = await fetch(`${API_URL}/files/${fileId}`, {
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const fileInfo = await res.json()
  console.log(fileInfo)
  ```

  ```bash cURL theme={null}
  curl -s -X GET "https://api.olostep.com/v1/files/$FILE_ID" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"
  ```
</CodeGroup>

## Recupera l'oggetto file tramite ID

Ottieni un URL pre-firmato per scaricare il contenuto JSON di un file completato. Specifica facoltativamente il tempo di scadenza per l'URL di download utilizzando il parametro di query `expires_in` (predefinito a 600 secondi / 10 minuti).

<CodeGroup>
  ```python Python theme={null}
  file_id = "file_abc123xyz789"
  # Ottieni URL di download (scadenza predefinita: 600 secondi)
  response = requests.get(
      f"{API_URL}/files/{file_id}/content",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  download_info = response.json()
  download_url = download_info["download_url"]

  # Scarica il contenuto del file utilizzando l'URL pre-firmato
  file_response = requests.get(download_url)
  file_content = file_response.json()
  print(json.dumps(file_content, indent=2))

  # Esempio con scadenza personalizzata (3600 secondi = 1 ora)
  response = requests.get(
      f"{API_URL}/files/{file_id}/content?expires_in=3600",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  download_info = response.json()
  print(f"URL di download scade in: {download_info['expires_in']} secondi")
  ```

  ```js Node theme={null}
  const fileId = 'file_abc123xyz789'

  // Ottieni URL di download (scadenza predefinita: 600 secondi)
  const res = await fetch(`${API_URL}/files/${fileId}/content`, {
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const downloadInfo = await res.json()
  const downloadUrl = downloadInfo.download_url

  // Scarica il contenuto del file utilizzando l'URL pre-firmato
  const fileRes = await fetch(downloadUrl)
  const fileContent = await fileRes.json()
  console.log(fileContent)

  // Esempio con scadenza personalizzata (3600 secondi = 1 ora)
  const customRes = await fetch(`${API_URL}/files/${fileId}/content?expires_in=3600`, {
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const customDownloadInfo = await customRes.json()
  console.log(`URL di download scade in: ${customDownloadInfo.expires_in} secondi`)
  ```

  ```bash cURL theme={null}
  # Ottieni URL di download (scadenza predefinita: 600 secondi)
  curl -s -X GET "https://api.olostep.com/v1/files/$FILE_ID/content" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"

  # Ottieni URL di download con scadenza personalizzata (3600 secondi = 1 ora)
  curl -s -X GET "https://api.olostep.com/v1/files/$FILE_ID/content?expires_in=3600" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"

  # Scarica il file utilizzando l'URL pre-firmato
  curl -s "$DOWNLOAD_URL"
  ```
</CodeGroup>

La risposta include un `download_url` pre-firmato che scade dopo il tempo specificato:

```json theme={null}
{
  "id": "file_abc123xyz789",
  "object": "file",
  "created": 1760329882,
  "filename": "my-data.json",
  "bytes": 1024,
  "download_url": "https://olostep-files.s3.amazonaws.com/files/...",
  "expires_in": 600
}
```

## Elenca i file

Elenca tutti i file completati per il tuo team. Filtra facoltativamente per scopo (valori supportati: `"context"` o `"batch"`).

<CodeGroup>
  ```python Python theme={null}
  # Elenca tutti i file
  response = requests.get(
      f"{API_URL}/files",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  files = response.json()
  print(json.dumps(files, indent=2))

  # Elenca i file filtrati per scopo
  response = requests.get(
      f"{API_URL}/files?purpose=context",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  context_files = response.json()
  print(json.dumps(context_files, indent=2))
  ```

  ```js Node theme={null}
  // Elenca tutti i file
  const res = await fetch(`${API_URL}/files`, {
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const files = await res.json()
  console.log(files)

  // Elenca i file filtrati per scopo
  const contextRes = await fetch(`${API_URL}/files?purpose=context`, {
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const contextFiles = await contextRes.json()
  console.log(contextFiles)
  ```

  ```bash cURL theme={null}
  # Elenca tutti i file
  curl -s -X GET "https://api.olostep.com/v1/files" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"

  # Elenca i file filtrati per scopo
  curl -s -X GET "https://api.olostep.com/v1/files?purpose=context" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"
  ```
</CodeGroup>

La risposta include un elenco di file:

```json theme={null}
{
  "object": "list",
  "data": [
    {
      "id": "file_abc123xyz789",
      "object": "file",
      "created": 1760329882,
      "filename": "my-data.json",
      "bytes": 1024,
      "purpose": "context",
      "status": "completed"
    }
  ]
}
```

## Elimina un file

Elimina un file e i suoi dati associati dallo storage.

<CodeGroup>
  ```python Python theme={null}
  file_id = "file_abc123xyz789"
  response = requests.delete(
      f"{API_URL}/files/{file_id}",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  result = response.json()
  print(json.dumps(result, indent=2))
  ```

  ```js Node theme={null}
  const fileId = 'file_abc123xyz789'
  const res = await fetch(`${API_URL}/files/${fileId}`, {
    method: 'DELETE',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const result = await res.json()
  console.log(result)
  ```

  ```bash cURL theme={null}
  curl -s -X DELETE "https://api.olostep.com/v1/files/$FILE_ID" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"
  ```
</CodeGroup>

## Esempio di completamento caricamento (scopo context)

Ecco un esempio completo che carica un file JSON con `purpose="context"`:

<CodeGroup>
  ```python Python theme={null}
  import requests
  import json

  API_KEY = "<YOUR_API_KEY>"
  API_URL = "https://api.olostep.com/v1"

  # Step 1: Create upload URL
  create_response = requests.post(
      f"{API_URL}/files",
      headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
      json={"filename": "user-data.json", "purpose": "context"}
  )
  upload_data = create_response.json()
  file_id = upload_data["id"]
  upload_url = upload_data["upload_url"]

  # Step 2: Prepara e carica i dati JSON
  json_data = {
      "users": [
          {"id": 1, "name": "Alice", "role": "admin"},
          {"id": 2, "name": "Bob", "role": "user"}
      ]
  }

  upload_response = requests.put(
      upload_url,
      data=json.dumps(json_data),
      headers={"Content-Type": "application/json"}
  )
  upload_response.raise_for_status()

  # Step 3: Completa il caricamento
  complete_response = requests.post(
      f"{API_URL}/files/{file_id}/complete",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  file_info = complete_response.json()

  print(f"File caricato con successo: {file_info['id']}")
  print(f"Dimensione del file: {file_info['bytes']} byte")
  ```

  ```js Node theme={null}
  const API_URL = 'https://api.olostep.com/v1'

  // Step 1: Create upload URL
  const createRes = await fetch(`${API_URL}/files`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>', 'Content-Type': 'application/json' },
    body: JSON.stringify({ filename: 'user-data.json', purpose: 'context' })
  })
  const uploadData = await createRes.json()
  const fileId = uploadData.id
  const uploadUrl = uploadData.upload_url

  // Step 2: Prepara e carica i dati JSON
  const jsonData = {
    users: [
      { id: 1, name: 'Alice', role: 'admin' },
      { id: 2, name: 'Bob', role: 'user' }
    ]
  }

  await fetch(uploadUrl, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(jsonData)
  })

  // Step 3: Completa il caricamento
  const completeRes = await fetch(`${API_URL}/files/${fileId}/complete`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const fileInfo = await completeRes.json()

  console.log(`File caricato con successo: ${fileInfo.id}`)
  console.log(`Dimensione del file: ${fileInfo.bytes} byte`)
  ```
</CodeGroup>

## Esempio di caricamento file batch

Ecco un esempio che carica un file JSON con `purpose="batch"` contenente dati batch validi che possono essere utilizzati con l'endpoint `/v1/batches`:

<CodeGroup>
  ```python Python theme={null}
  import requests
  import json

  API_KEY = "<YOUR_API_KEY>"
  API_URL = "https://api.olostep.com/v1"

  # Step 1: Create upload URL with purpose="batch"
  create_response = requests.post(
      f"{API_URL}/files",
      headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
      json={"filename": "batch-items.json", "purpose": "batch"}
  )
  upload_data = create_response.json()
  file_id = upload_data["id"]
  upload_url = upload_data["upload_url"]

  # Step 2: Prepara dati JSON batch (formato valido per l'endpoint /v1/batches)
  batch_data = {
      "items": [
          {"custom_id": "item-1", "url": "https://www.google.com/search?q=stripe&gl=us&hl=en"},
          {"custom_id": "item-2", "url": "https://www.google.com/search?q=paddle&gl=us&hl=en"},
          {"custom_id": "item-3", "url": "https://www.google.com/search?q=payment+gateway&gl=us&hl=en"}
      ],
      "parser": {"id": "@olostep/google-search"},
      "country": "US"
  }

  upload_response = requests.put(
      upload_url,
      data=json.dumps(batch_data),
      headers={"Content-Type": "application/json"}
  )
  upload_response.raise_for_status()

  # Step 3: Completa il caricamento
  complete_response = requests.post(
      f"{API_URL}/files/{file_id}/complete",
      headers={"Authorization": f"Bearer {API_KEY}"}
  )
  file_info = complete_response.json()

  print(f"File batch caricato con successo: {file_info['id']}")
  print(f"Dimensione del file: {file_info['bytes']} byte")
  print(f"Scopo: {file_info['purpose']}")
  ```

  ```js Node theme={null}
  const API_URL = 'https://api.olostep.com/v1'

  // Step 1: Create upload URL with purpose="batch"
  const createRes = await fetch(`${API_URL}/files`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>', 'Content-Type': 'application/json' },
    body: JSON.stringify({ filename: 'batch-items.json', purpose: 'batch' })
  })
  const uploadData = await createRes.json()
  const fileId = uploadData.id
  const uploadUrl = uploadData.upload_url

  // Step 2: Prepara dati JSON batch (formato valido per l'endpoint /v1/batches)
  const batchData = {
    items: [
      { custom_id: 'item-1', url: 'https://www.google.com/search?q=stripe&gl=us&hl=en' },
      { custom_id: 'item-2', url: 'https://www.google.com/search?q=paddle&gl=us&hl=en' },
      { custom_id: 'item-3', url: 'https://www.google.com/search?q=payment+gateway&gl=us&hl=en' }
    ],
    parser: { id: '@olostep/google-search' },
    country: 'US'
  }

  await fetch(uploadUrl, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(batchData)
  })

  // Step 3: Completa il caricamento
  const completeRes = await fetch(`${API_URL}/files/${fileId}/complete`, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer <YOUR_API_KEY>' }
  })
  const fileInfo = await completeRes.json()

  console.log(`File batch caricato con successo: ${fileInfo.id}`)
  console.log(`Dimensione del file: ${fileInfo.bytes} byte`)
  console.log(`Scopo: ${fileInfo.purpose}`)
  ```

  ```bash cURL theme={null}
  # Step 1: Create upload URL with purpose="batch"
  curl -s -X POST "https://api.olostep.com/v1/files" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "filename": "batch-items.json",
      "purpose": "batch"
    }'

  # Step 2: Carica dati JSON batch (salva prima in batch-items.json)
  # contenuto di batch-items.json:
  # {
  #   "items": [
  #     {"custom_id": "item-1", "url": "https://www.google.com/search?q=stripe&gl=us&hl=en"},
  #     {"custom_id": "item-2", "url": "https://www.google.com/search?q=paddle&gl=us&hl=en"},
  #     {"custom_id": "item-3", "url": "https://www.google.com/search?q=payment+gateway&gl=us&hl=en"}
  #   ],
  #   "parser": {"id": "@olostep/google-search"},
  #   "country": "US"
  # }

  curl -X PUT "$UPLOAD_URL" \
    -H "Content-Type: application/json" \
    -d @batch-items.json

  # Step 3: Completa il caricamento
  curl -s -X POST "https://api.olostep.com/v1/files/$FILE_ID/complete" \
    -H "Authorization: Bearer $OLOSTEP_API_KEY"
  ```
</CodeGroup>

Il file batch caricato contiene una struttura JSON valida che corrisponde al formato dell'endpoint `/v1/batches`:

* `items`: Array di oggetti con campi `custom_id` e `url`
* `parser`: Configurazione del parser opzionale
* `country`: Codice del paese opzionale

Questo file può essere utilizzato come input per operazioni di elaborazione batch.

## Requisiti del file

* **Formato del file**: Sono supportati solo file JSON (è richiesta l'estensione `.json`)
* **Dimensione del file**: Massimo 200MB per file
* **Scadenza**: I file scadono dopo 30 giorni
* **URL di caricamento**: Gli URL pre-firmati scadono dopo 10 minuti
* **Parametro purpose**: Supporta solo i valori `"context"` o `"batch"` (predefinito `"context"`)

## Prezzi

I caricamenti di file sono gratuiti. I file sono archiviati in modo sicuro e scadono automaticamente dopo 30 giorni.
