How can i make HTTP request from the browser to the API?

I need for my fun project the ability to send request from the browser, so all the parameters are in the URL including the api key and the prompt, Below is my URL that I using, but I keep getting errors that the API key is missing, although I’m adding the key.

URL:
https://api.openai.com/v1/completions?model=text-davinci-002&prompt=Hello&max_tokens=1024&stop=.&api_key=***************************
Error:

{
    "error": {
        "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://beta.openai.com.",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}
1 Like

The API key is part of the header, not the query parameters. You can probably find some extensions that allow you to craft HTTP requests in the browser. But you are probably better with something like Postman

It is quite simple if you translate the curl request into fetch:

fetch("https://api.openai.com/v1/completions", {
  method: "POST",
  headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      "model": "text-davinci-003",
      "prompt": "I am a highly intelligent question answering bot. If you ask me a  Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ: Where is the Valley of Kings?\nA:",
      "temperature": 0,
      "max_tokens": 100,
      "top_p": 1,
      "frequency_penalty": 0.0,
      "presence_penalty": 0.0,
      "stop": ["\n"]
    })
  }
).then(r=>console.log(r))

I made it such that you can place your api key and run the code from the browser dev console.

If you create a website this will show the API key to anyone that looks into the fetch function I believe.

So the way someone would do it is to set everything but the API key, and send it to your sever, and run the query from your server, and then return it (the text only actually.)

1 Like

Yeah, this isn’t a great idea as it would be available openly.

Welcome to the community!

Can we also add streaming option to this http request? May be with curl or fetch?