import os
import requests
url = "https://api.openai.com/v1/images/variations"
headers = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "multipart/form-data"
}
files = {
"image": open("/path/to/image.png", "rb"),
"n": (None, "1"),
"size": (None, "1024x1024")
}
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/images/variations"
headers = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "multipart/form-data"
}
files = {
"image": open("/path/to/image.png", "rb"),
"n": (None, "1"),
"size": (None, "1024x1024")
}
with httpx.Client() as client:
response = client.post(url, headers=headers, files=files)
response.raise_for_status()
print(response.json())
const fetch = require('node-fetch');
const FormData = require('form-data');
const fs = require('fs');
const url = 'https://api.openai.com/v1/images/variations';
const form = new FormData();
form.append('image', fs.createReadStream('/path/to/image.png'));
form.append('n', '1');
form.append('size', '1024x1024');
fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
...form.getHeaders()
},
body: form
})
.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));
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const url = 'https://api.openai.com/v1/images/variations';
const form = new FormData();
form.append('image', fs.createReadStream('/path/to/image.png'));
form.append('n', '1');
form.append('size', '1024x1024');
axios.post(url, form, {
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
...form.getHeaders()
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
url := "https://api.openai.com/v1/images/variations"
apiKey := os.Getenv("OPENAI_API_KEY")
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
file, err := os.Open("/path/to/image.png")
if err != nil {
panic(err)
}
defer file.Close()
part, err := writer.CreateFormFile("image", file.Name())
if err != nil {
panic(err)
}
_, err = io.Copy(part, file)
if err != nil {
panic(err)
}
_ = writer.WriteField("n", "1")
_ = writer.WriteField("size", "1024x1024")
writer.Close()
req, err := http.NewRequest("POST", url, body)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+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("request failed with status: %s", resp.Status))
}
bodyBytes, _ := io.ReadAll(resp.Body)
fmt.Println(string(bodyBytes))
}
<?php
$url = 'https://api.openai.com/v1/images/variations';
$apiKey = getenv('OPENAI_API_KEY');
$client = new CURLClient();
$client->setOption(CURLOPT_URL, $url);
$client->setOption(CURLOPT_POST, true);
$client->setOption(CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
]);
$boundary = uniqid();
$client->setOption(CURLOPT_HTTPHEADER, array_merge(
$client->getInfo(CURLINFO_HEADER_OUT, true),
['Content-Type: multipart/form-data; boundary=' . $boundary]
));
$postFields = [
'image' => new CURLFile('/path/to/image.png', 'image/png'),
'n' => '1',
'size' => '1024x1024'
];
$client->setOption(CURLOPT_POSTFIELDS, $postFields);
$response = $client->execute();
if ($response === false) {
die('Error: ' . $client->getError());
}
$httpCode = $client->getInfo(CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
die("HTTP error: $httpCode");
}
$responseData = json_decode($response, true);
print_r($responseData);
$client->close();
class CURLClient {
private $ch;
public function __construct() {
$this->ch = curl_init();
}
public function setOption($option, $value) {
curl_setopt($this->ch, $option, $value);
}
public function getInfo($option) {
return curl_getinfo($this->ch, $option);
}
public function execute() {
return curl_exec($this->ch);
}
public function getError() {
return curl_error($this->ch);
}
public function close() {
curl_close($this->ch);
}
}
?>
require 'net/http'
require 'uri'
require 'mimemagic'
url = URI.parse('https://api.openai.com/v1/images/variations')
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, {
'image' => UploadIO.new(File.open('/path/to/image.png'), 'image/png'),
'n' => '1',
'size' => '1024x1024'
})
request['Authorization'] = "Bearer #{api_key}"
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error: #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
let url = URL(string: "https://api.openai.com/v1/images/variations")!
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()
let imageData = try Data(contentsOf: URL(fileURLWithPath: "/path/to/image.png"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
body.append(imageData)
body.append("\r\n".data(using: .utf8)!)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"n\"\r\n\r\n".data(using: .utf8)!)
body.append("1\r\n".data(using: .utf8)!)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"size\"\r\n\r\n".data(using: .utf8)!)
body.append("1024x1024\r\n".data(using: .utf8)!)
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, httpResponse.statusCode == 200 else {
print("HTTP error: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
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::File;
use std::io::Read;
use reqwest::multipart;
use reqwest::blocking::Client;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://api.openai.com/v1/images/variations";
let api_key = env::var("OPENAI_API_KEY")?;
let client = Client::new();
let file = File::open("/path/to/image.png")?;
let form = multipart::Form::new()
.file("image", "/path/to/image.png")?
.text("n", "1")
.text("size", "1024x1024");
let response = client
.post(url)
.header("Authorization", format!("Bearer {}", api_key))
.multipart(form)
.send()?;
if !response.status().is_success() {
return Err(format!("HTTP error: {}", response.status()).into());
}
let body = response.text()?;
println!("{}", body);
Ok(())
}
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var url = "https://api.openai.com/v1/images/variations";
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
using var client = new HttpClient();
using var form = new MultipartFormDataContent();
var fileStream = File.OpenRead("/path/to/image.png");
var streamContent = new StreamContent(fileStream);
var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());
form.Add(fileContent, "image", "image.png");
form.Add(new StringContent("1"), "n");
form.Add(new StringContent("1024x1024"), "size");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
var response = await client.PostAsync(url, form);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"HTTP error: {response.StatusCode}");
}
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}