How to implement curl -F API call with URLConnection

I’m trying to send Data with URLConnection to implement an OpenAI API command defined like this:

curl https://api.openai.com/v1/files
-H “Authorization: Bearer $OPENAI_API_KEY”
-F purpose=“fine-tune”
-F file=“@mydata.jsonl

The code below returns a Response error indicating it cannot find expected “file” parameter.

dim Response as String
dim Connect as new URLConnection
Connect.RequestHeader(“Authorization”) = "Bearer " + APIKey
Connect.RequestHeader(“Content-Type”) = “multipart/form-data”
Connect.SetRequestContent(“purpose=fine-tune&file=”+Data, “application/x-www-form-urlencoded”)
Response = Connect.SendSync(“POST”, “https://api.openai.com/v1/files”, 30)

Any suggestion on how to implement this API command in Xojo?

To POST a file upload you will need to generate a multipart/form-data encoded payload containing the file data, but your code is actually generating a application/x-www-form-urlencoded payload.

You can use this open source code to generate the correct form type: GitHub - einhugur/MultipartFormDataContent: MultipartFormDataContent class for Xojo

Example:

Dim f as FolderItem = GetOpenFolderItem("*.*") ' the file to upload
Dim connect as New URLConnection()
connect.RequestHeader(“Authorization”) = "Bearer " + APIKey
Dim multipartContent as MultipartFormDataContent = new MultipartFormDataContent()
multipartContent.Add("purpose", "fine-tune")
multipartContent.Add("file", f)
multipartContent.SetURLConnectionMultipartContent(connect)
Dim response as String = connect.SendSync("POST", "https://api.openai.com/v1/files")

See also my OpenAI wrapper which supports uploading fine-tuning files to the v1/files endpoint: OpenAI.File · charonn0/Xojo-OpenAI Wiki · GitHub

Example:

 OpenAI.APIKey = "YOUR API KEY"
 Dim f as FolderItem = GetOpenFolderItem("*.*") ' the file to upload
 Dim file As OpenAI.File = OpenAI.File.Create(f, "fine-tune") ' upload

@Andrew_Lambert - there’s no MultiPartFormDataContent object in Xojo.

It’s from the first link

4 Likes