# Files

`POST /v1/files` keeps a file on your account, to send to a model by its id; five routes upload,
list, read, fetch and delete your files.

## Request

Send them with an API key. Every route is free, and a file you keep never expires. [Files and
storage](/docs/files-and-storage) sends one to a model, step by step.

| Route | Does |
|---|---|
| `POST /v1/files` | uploads one file |
| `GET /v1/files` | lists your files, oldest first |
| `GET /v1/files/{id}` | answers one file's details |
| `GET /v1/files/{id}/content` | answers the file's bytes |
| `DELETE /v1/files/{id}` | deletes it |

### Upload

`POST /v1/files` takes a `multipart/form-data` form. It answers once the file is kept.

| Field | Needed | You send |
|---|---|---|
| `file` | yes | the file, up to 100 MB: a picture (PNG, JPEG, WebP, GIF), audio (MP3, WAV, FLAC, M4A, OGG, AAC, WebM), a PDF, a Word, Excel or PowerPoint file, or plain text such as CSV, JSON or Markdown. Its kind is read from its bytes, not its name |
| `purpose` | no | a word of your own for what the file is for, up to 64 characters; absent, `user_data` |

The samples upload a small catalogue written in the code itself, then print its id.

```python
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/files"

boundary = "opendunes-upload"
catalogue = (
    "sku,name\n"
    "burnous-01,Burnous en laine\n"
    "tapis-07,Tapis berbère 200 × 300\n"
).encode()

body = (
    (
        f"--{boundary}\r\n"
        'Content-Disposition: form-data; name="file"; '
        'filename="catalogue.csv"\r\n'
        "Content-Type: text/csv\r\n\r\n"
    ).encode()
    + catalogue
    + f"\r\n--{boundary}--\r\n".encode()
)

request = urllib.request.Request(
    ADDRESS,
    data=body,
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "multipart/form-data; boundary=" + boundary,
    },
)
with urllib.request.urlopen(request) as response:
    uploaded = json.load(response)

print(uploaded["id"], uploaded["size_bytes"], uploaded["downloadable"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/files";

const catalogue =
  "sku,name\n" +
  "burnous-01,Burnous en laine\n" +
  "tapis-07,Tapis berbère 200 × 300\n";

const csv = new Blob([catalogue], { type: "text/csv" });
const form = new FormData();
form.append("file", csv, "catalogue.csv");

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: { Authorization: `Bearer ${API_KEY}` },
  body: form,
});
const uploaded = await response.json();

console.log(uploaded.id, uploaded.size_bytes, uploaded.downloadable);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"mime/multipart"
	"net/http"
	"os"
)

const address = "https://opendunes.com/v1/files"

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	catalogue := "sku,name\n" +
		"burnous-01,Burnous en laine\n" +
		"tapis-07,Tapis berbère 200 × 300\n"

	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	part, err := form.CreateFormFile("file", "catalogue.csv")
	if err != nil {
		panic(err)
	}
	part.Write([]byte(catalogue))
	form.Close()

	req, err := http.NewRequest("POST", address, &body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", form.FormDataContentType())

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var uploaded struct {
		ID           string `json:"id"`
		SizeBytes    int64  `json:"size_bytes"`
		Downloadable bool   `json:"downloadable"`
	}
	if err := json.NewDecoder(res.Body).Decode(&uploaded); err != nil {
		panic(err)
	}
	fmt.Println(uploaded.ID, uploaded.SizeBytes, uploaded.Downloadable)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/files"

printf '%s\n' \
  'sku,name' \
  'burnous-01,Burnous en laine' \
  'tapis-07,Tapis berbère 200 × 300' > catalogue.csv

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -F "file=@catalogue.csv"
```

### List

`GET /v1/files` takes its fields in the address, after `?`.

| Field | Needed | You send |
|---|---|---|
| `limit` | no | how many files one page holds, 1 to 1000; absent, 20 |
| `cursor` | no | the `cursor` the previous page answered, for the next page |
| `after` | no | a file's `id`: the page starts after it. An `id` that matches no file of yours is not refused: the page holds your files whose ids sort after it, an empty page when none does |

### One file, its bytes, deleting it

`GET /v1/files/{id}`, `GET /v1/files/{id}/content` and `DELETE /v1/files/{id}` take the file's
`id` in the address, and nothing else.

## Response

`POST /v1/files` answers `201 Created` with the file; `GET /v1/files/{id}` answers `200 OK` with
the same object.

| Field | Holds |
|---|---|
| `id` | the file's id: send it as `file_id` in a request's file part |
| `type` | `file` |
| `filename` | the name it was sent with |
| `mime_type` | what the file is, read from its bytes |
| `size_bytes` | its size, in bytes |
| `created_at` | when it was kept, in UTC |
| `downloadable` | `true` once its copy is kept; until then `/content` answers 400 |

`GET /v1/files` answers `200 OK` with a page of files.

| Field | Holds |
|---|---|
| `data` | the files on this page, each the object above |
| `has_more` | `true` when another page follows |
| `first_id` | the `id` of the first file on this page |
| `last_id` | the `id` of the last one |
| `cursor` | what to send as `cursor` for the next page |

`GET /v1/files/{id}/content` answers the bytes themselves, as an attachment, in the file's own
type. `DELETE /v1/files/{id}` answers `200 OK`:

| Field | Holds |
|---|---|
| `id` | the file deleted |
| `type` | `file_deleted` |

## What it cost

Free. Uploading, listing, reading, fetching and deleting a file are never charged, and a kept file
costs nothing to keep. A request that reads a file is charged as that request.

A file is kept byte for byte until you delete it, whatever the key's storage setting. Deleting it
removes it from your list; the receipts of the requests that used it stay.

## Errors

`error.code` carries the status, and `error.message` says why.

| Status | When |
|---|---|
| 400 | `file` is missing, `purpose` is over 64 characters, `limit` is out of range, `after` is not shaped like a file's `id`, the `cursor` is not one a page answered, or `/content` is asked for a file whose copy is not kept yet |
| 401 | the key is missing, wrong, disabled or expired |
| 403 | the key is kept to other addresses |
| 404 | no file of yours has that `id` |
| 413 | the file is over 100 MB |
| 422 | the file is of a kind no model reads |
| 429 | too many downloads of your files at once; wait and ask again |
| 502 | the file could not be kept; send it again |
