import os
import requests
url = "https://api.openai.com/v1/files"
headers = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "multipart/form-data"
}
files = {
"file": open("example.json", "rb"),
"purpose": (None, "fine-tune")
}
response = requests.post(url, headers=headers, files=files)
response.raise_for_status()
print(response.json())
import os
import httpx
url = "https://api.openai.com/v1/files"
headers = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "multipart/form-data"
}
files = {
"file": open("example.json", "rb"),
"purpose": (None, "fine-tune")
}
with httpx.Client() as client:
response = client.post(url, headers=headers, files=files)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import fs from 'fs';
import { Buffer } from 'buffer';
const url = 'https://api.openai.com/v1/files';
const headers = {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'multipart/form-data'
};
const formData = new FormData();
formData.append('file', fs.createReadStream('example.json'));
formData.append('purpose', 'fine-tune');
fetch(url, {
method: 'POST',
headers: headers,
body: formData
})
.then(res => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
import axios from 'axios';
import fs from 'fs';
import FormData from 'form-data';
const url = 'https://api.openai.com/v1/files';
const headers = {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
};
const form = new FormData();
form.append('file', fs.createReadStream('example.json'));
form.append('purpose', 'fine-tune');
axios.post(url, form, { headers: { ...headers, ...form.getHeaders() } })
.then(res => {
if (res.status !== 200) throw new Error(`HTTP error! status: ${res.status}`);
console.log(res.data);
})
.catch(err => console.error(err));
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
url := "https://api.openai.com/v1/files"
apiKey := os.Getenv("OPENAI_API_KEY")
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
file, err := os.Open("example.json")
if err != nil {
panic(err)
}
defer file.Close()
part, err := writer.CreateFormFile("file", "example.json")
if err != nil {
panic(err)
}
_, err = io.Copy(part, file)
if err != nil {
panic(err)
}
_ = writer.WriteField("purpose", "fine-tune")
writer.Close()
req, err := http.NewRequest("POST", url, body)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic(fmt.Sprintf("HTTP error! status: %s", resp.Status))
}
bodyBytes, _ := io.ReadAll(resp.Body)
fmt.Println(string(bodyBytes))
}
<?php
$url = 'https://api.openai.com/v1/files';
$apiKey = getenv('OPENAI_API_KEY');
$boundary = uniqid();
$headers = [
'Authorization: Bearer ' . $apiKey,
'Content-Type: multipart/form-data; boundary=' . $boundary
];
$body = '';
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Disposition: form-data; name="file"; filename="example.json"' . "\r\n";
$body .= "\r\n";
$body .= file_get_contents('example.json') . "\r\n";
$body .= '--' . $boundary . "\r\n";
$body .= 'Content-Disposition: form-data; name="purpose"' . "\r\n";
$body .= "\r\n";
$body .= 'fine-tune' . "\r\n";
$body .= '--' . $boundary . '--' . "\r\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
die('Error: ' . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
die("HTTP error! status: $httpCode");
}
print_r(json_decode($response, true));
?>
require 'net/http'
require 'uri'
require 'mime/types'
url = URI.parse('https://api.openai.com/v1/files')
api_key = ENV['OPENAI_API_KEY']
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post::Multipart.new(url.path, {
file: UploadIO.new(File.open('example.json'), 'application/json'),
purpose: 'fine-tune'
})
request['Authorization'] = "Bearer #{api_key}"
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error! status: #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
let url = URL(string: "https://api.openai.com/v1/files")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
// Add file part
let fileData = try Data(contentsOf: URL(fileURLWithPath: "example.json"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"example.json\"\r\n".data(using: .utf8)!)
body.append("Content-Type: application/json\r\n\r\n".data(using: .utf8)!)
body.append(fileData)
body.append("\r\n".data(using: .utf8)!)
// Add purpose part
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"purpose\"\r\n\r\n".data(using: .utf8)!)
body.append("fine-tune".data(using: .utf8)!)
body.append("\r\n".data(using: .utf8)!)
// Close boundary
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse else {
print("Invalid response")
return
}
guard (200...299).contains(httpResponse.statusCode) else {
print("HTTP error! status: \(httpResponse.statusCode)")
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::env;
use std::fs;
use reqwest::multipart;
use reqwest::blocking::Client;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://api.openai.com/v1/files";
let api_key = env::var("OPENAI_API_KEY")?;
let file_data = fs::read("example.json")?;
let form = multipart::Form::new()
.file("file", "example.json")?
.text("purpose", "fine-tune");
let client = Client::new();
let response = client
.post(url)
.header("Authorization", format!("Bearer {}", api_key))
.multipart(form)
.send()?;
if !response.status().is_success() {
return Err(format!("HTTP error! status: {}", response.status()).into());
}
let body = response.json::<serde_json::Value>()?;
println!("{:?}", body);
Ok(())
}
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var url = "https://api.openai.com/v1/files";
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
using var client = new HttpClient();
using var form = new MultipartFormDataContent();
var fileContent = new StreamContent(File.OpenRead("example.json"));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
form.Add(fileContent, "file", "example.json");
form.Add(new StringContent("fine-tune"), "purpose");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var response = await client.PostAsync(url, form);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTTP error! status: {response.StatusCode}");
}
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}