Skip to content

Files

Upload a file

bash
curl https://api.fastapi.ai/v1/files \
  -H "Authorization: Bearer $FAST_API_KEY" \
  -F purpose="batch" \
  -F file="@input.jsonl"
javascript
import fs from "node:fs";

const form = new FormData();
form.append("purpose", "batch");
const file = new Blob([fs.readFileSync("input.jsonl")], { type: "application/jsonl" });
form.append("file", file, "input.jsonl");

const res = await fetch("https://api.fastapi.ai/v1/files", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.FAST_API_KEY}` },
  body: form,
});

console.log(await res.json());
python
import os
import requests

with open('input.jsonl', 'rb') as f:
  resp = requests.post(
    'https://api.fastapi.ai/v1/files',
    headers={'Authorization': f"Bearer {os.environ['FAST_API_KEY']}"},
    files={'file': f},
    data={'purpose': 'batch'},
  )

print(resp.json())
go
package main

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

func main() {
  var buf bytes.Buffer
  w := multipart.NewWriter(&buf)

  _ = w.WriteField("purpose", "batch")

  file, _ := os.Open("input.jsonl")
  defer file.Close()
  fw, _ := w.CreateFormFile("file", "input.jsonl")
  _, _ = io.Copy(fw, file)

  _ = w.Close()

  req, _ := http.NewRequest("POST", "https://api.fastapi.ai/v1/files", &buf)
  req.Header.Set("Authorization", "Bearer "+os.Getenv("FAST_API_KEY"))
  req.Header.Set("Content-Type", w.FormDataContentType())

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

  body, _ := io.ReadAll(resp.Body)
  fmt.Println(string(body))
}
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws Exception {
    String boundary = "----FastAPIBoundary";
    byte[] fileBytes = Files.readAllBytes(Path.of("input.jsonl"));

    String part1 =
      "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"purpose\"\r\n\r\n" +
      "batch\r\n";
    String part2Header =
      "--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"file\"; filename=\"input.jsonl\"\r\n" +
      "Content-Type: application/jsonl\r\n\r\n";
    String partEnd = "\r\n--" + boundary + "--\r\n";

    byte[] body = concat(
      part1.getBytes(),
      part2Header.getBytes(),
      fileBytes,
      partEnd.getBytes()
    );

    HttpRequest req = HttpRequest.newBuilder()
      .uri(URI.create("https://api.fastapi.ai/v1/files"))
      .header("Authorization", "Bearer " + System.getenv("FAST_API_KEY"))
      .header("Content-Type", "multipart/form-data; boundary=" + boundary)
      .POST(HttpRequest.BodyPublishers.ofByteArray(body))
      .build();

    HttpResponse<String> resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
    System.out.println(resp.body());
  }

  private static byte[] concat(byte[]... parts) {
    int len = 0;
    for (byte[] p : parts) len += p.length;
    byte[] out = new byte[len];
    int pos = 0;
    for (byte[] p : parts) {
      System.arraycopy(p, 0, out, pos, p.length);
      pos += p.length;
    }
    return out;
  }
}

那年我双手插兜, 让bug稳如老狗