Trouble with OpenAI API call in MQL5 – “You didn’t provide an API key” error

 

Hi everyone,

I'm trying to send a POST request to the OpenAI API from a MetaTrader 5 script using WebRequest , but I'm getting this response:

"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys."

#property script_show_inputs

void OnStart()
{
   // OpenAI API key (replace with your own)
   string apiKey = "sk-APIKEY";

   // Prepare JSON body for ChatGPT request
   string requestBody = 
      "{\"model\":\"gpt-3.5-turbo\","
      "\"messages\":[{\"role\":\"user\",\"content\":\"Hello!\"}],"
      "\"max_tokens\":50}";

   // Convert JSON string to UTF-8 encoded char array
   char payload[];
   int len = StringToCharArray(requestBody, payload, 0, StringLen(requestBody), CP_UTF8);
   ArrayResize(payload, len + 1);
   payload[len] = '\0'; // Ensure null-termination

   // Set HTTP headers including the Authorization
   string httpHeaders = 
      "Content-Type: application/json\r\n" +
      "Authorization: Bearer " + apiKey + "\r\n\r\n";

   // Define request parameters
   string endpoint = "https://api.openai.com/v1/chat/completions";
   char responseBuffer[];
   string cookies;
   int timeout = 10000;

   // Make the POST request to OpenAI API
   int status = WebRequest(
      "POST",
      endpoint,
      httpHeaders,
      "",         // No additional parameters
      timeout,
      payload,
      len,
      responseBuffer,
      cookies
   );

   Print("WebRequest result = ", status);
   if(status == -1)
   {
      Print("Error code: ", GetLastError());
   }
   else
   {
      // Output the response from the server
      string serverReply = CharArrayToString(responseBuffer, 0, -1);
      Print("OpenAI response: ", serverReply);
   }
}

The request seems to go through (WebRequest returns 200), but the API says the key is missing. I've triple-checked the key and the header format.

Has anyone successfully connected to OpenAI's API from MT5? Is there anything specific about how MT5 handles headers that could be causing this?


Any help would be greatly appreciated!

 
emei:

Hi everyone,

I'm trying to send a POST request to the OpenAI API from a MetaTrader 5 script using WebRequest , but I'm getting this response:

"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys."

The request seems to go through (WebRequest returns 200), but the API says the key is missing. I've triple-checked the key and the header format.

Has anyone successfully connected to OpenAI's API from MT5? Is there anything specific about how MT5 handles headers that could be causing this?


Any help would be greatly appreciated!

Your header looks correct. I've been using deep seek api the past week and the header format is the same in mql5 and it's been working.
string Headers = 
        "Content-Type: application/json\r\n" +
        "Authorization: Bearer " + APIKey + "\r\n";
 
Connor Michael Woodson #:
Your header looks correct. I've been using deep seek api the past week and the header format is the same in mql5 and it's been working.

Hi Connor,


Thanks for replying. Indeed, I am also using the header with:


string Headers = 
        "Content-Type: application/json\r\n" +
        "Authorization: Bearer " + APIKey + "\r\n";

But I still get the message:

"You didn't provide an API key..."
Have you tested with the OpenAI endpoint specifically from MT5, or just with other APIs? If you have any working examples with OpenAI, could you share them?

Thanks in advance!

 
emei:

I'm trying to send a POST request to the OpenAI API from a MetaTrader 5 script using WebRequest , but I'm getting this response:

"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys."

The request seems to go through (WebRequest returns 200), but the API says the key is missing. I've triple-checked the key and the header format.

Has anyone successfully connected to OpenAI's API from MT5? Is there anything specific about how MT5 handles headers that could be causing this?


Your WebRequest call is incorrect. The function provides 2 variants:

int WebRequest(const string method, const string url, const string cookie, const string referer, int timeout, const char &data[], int size, char &result[], string &response)

int WebRequest(const string method, const string url, const string headers, int timeout, const char &data[], char &result[], string &response)

You can choose either one of them, but you mixed their prototypes in the call, hence no headers have been passed to the service - the string was interpreted as cookies.

 
Stanislav Korotky #:

Your WebRequest call is incorrect. The function provides 2 variants:

You can choose either one of them, but you mixed their prototypes in the call, hence no headers have been passed to the service - the string was interpreted as cookies.

Hi again,


Thanks @Stanislav for the clarification on WebRequest overloads — that was indeed part of the problem in the original post. I corrected the function call to use the proper overload that includes the custom headers, like this:


int status = WebRequest(
   "POST",
   endpoint,
   httpHeaders, // now correctly passed as headers, not cookies
   timeout,
   payload,
   responseBuffer,
   responseHeaders
);

Now the request reaches the OpenAI API, but I'm facing a new issue. I consistently receive a 400 Bad Request response, with the following message: 

"message": "We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON...)"

Example of my code (simplified):

string requestBody = "{\"model\":\"gpt-3.5-turbo\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello!\"}],\"max_tokens\":50}";
uchar payload[];
int len = StringToCharArray(requestBody, payload, 0, CP_UTF8);
if(len > 0 && payload[len - 1] == 0) len--;

string headers =
   "Content-Type: application/json; charset=utf-8\r\n" +
   "Authorization: Bearer " + apiKey + "\r\n";

int status = WebRequest(
   "POST",
   "https://api.openai.com/v1/chat/completions",
   headers,
   10000,
   payload,
   responseBuffer,
   responseHeaders
);

Despite all these precautions, OpenAI keeps returning the same error, indicating that the JSON was not correctly received.

Has anyone managed to successfully send JSON to OpenAI from MQL5 using WebRequest ? I’d appreciate a working example or any insight into what MT5 might be doing to the payload under the hood.

Thanks again for any suggestions!

 
emei #:

Thanks @Stanislav for the clarification on WebRequest overloads — that was indeed part of the problem in the original post. I corrected the function call to use the proper overload that includes the custom headers, like this:

Now the request reaches the OpenAI API, but I'm facing a new issue. I consistently receive a 400 Bad Request response, with the following message: 

"message": "We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON...)"

Example of my code (simplified):

Despite all these precautions, OpenAI keeps returning the same error, indicating that the JSON was not correctly received.

Has anyone managed to successfully send JSON to OpenAI from MQL5 using WebRequest ? I’d appreciate a working example or any insight into what MT5 might be doing to the payload under the hood.

You're doing it wrong again, this time with StringToCharArray function - input agruments are incorrect, and decrementing len variable is useless. Look at HTTPRequest::POST method (from the algotrading book) as an example:

class HTTPRequest
{
   ...
   int POST(const string address, const string payload,
      uchar &result[], string &response, const string custom_headers = NULL)
   {
      uchar bytes[];
      const int n = StringToCharArray(payload, bytes, 0, -1, CP_UTF8);
      ArrayResize(bytes, n - 1); // remove terminal zero
      return request("POST", address, custom_headers, bytes, result, response);
   }
   ...
};
PS. Please, don't use ChatGPT for programming!
MQL5 Book: Advanced language tools / Network functions / Data exchange with a web server via HTTP/HTTPS
MQL5 Book: Advanced language tools / Network functions / Data exchange with a web server via HTTP/HTTPS
  • www.mql5.com
MQL5 allows you to integrate programs with web services and request data from the Internet. Data can be sent and received via HTTP/HTTPS protocols...
 
Stanislav Korotky #:

You're doing it wrong again, this time with StringToCharArray function - input agruments are incorrect, and decrementing len variable is useless. Look at HTTPRequest::POST method (from the algotrading book) as an example:

PS. Please, don't use ChatGPT for programming!

Thank you very much, fixed! 


After many attempts and errors using WebRequest() to connect to the OpenAI API from an MQL5 script, I finally managed to solve the problems. I share here what I was doing wrong and how to fix it, as it may help others.

Problem 1: Incorrect use of WebRequest overloading:

WebRequest() has two versions. If you misuse the parameters, your HTTP headers are not sent correctly. This was my mistake:
int status = WebRequest(
   "POST",
   url,
   headers,    
   "",        
   timeout,
   payload,
   len,
   responseBuffer,
   cookies
);
The function thought that headers was the cookie, so the Authorization: Bearer header never reached the server, and OpenAI responded with --> "You didn't provide an API key."

Problem 2: JSON miscoded by StringToCharArray():


I was generating the message body like this:

char payload[];
int len = StringToCharArray(json, payload, 0, StringLen(json), CP_UTF8);
ArrayResize(payload, len + 1);
payload[len] = '\0';

This added a null character (\0) to the end of the JSON, which causes OpenAI to return --> "We could not parse the JSON body of your request..."