python-openaiHow to make a request to OpenAI's API in Python?
Making a request to OpenAI's API in Python is easy and straightforward. The following example code block shows how to make a request to the API using the requests
library:
import requests
url = 'https://api.openai.com/v1/engines/davinci/completions'
data = {
"prompt": "The quick brown fox",
"max_tokens": 50
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer <YOUR_API_KEY>"
}
response = requests.post(url, json=data, headers=headers)
print(response.json())
The output of the example code is:
{
"id": "davinci_<SOME_ID>",
"object": "text_completion",
"choices": [
{
"text": "The quick brown fox jumped over the lazy dog.",
"index": 0,
"logprobs": [
-4.945,
-4.945,
-4.945,
-4.945,
-4.945,
-4.945,
-4.945,
-4.945,
-4.945,
-4.945
]
}
]
}
Code explanation
import requests
: This imports therequests
library which is used to make the API request.url = 'https://api.openai.com/v1/engines/davinci/completions'
: This sets the URL of the API endpoint.data = { "prompt": "The quick brown fox", "max_tokens": 50 }
: This sets the data to be sent in the request body.headers = { "Content-Type": "application/json", "Authorization": "Bearer <YOUR_API_KEY>" }
: This sets the headers of the request.response = requests.post(url, json=data, headers=headers)
: This makes the API request using therequests.post()
method.print(response.json())
: This prints the response from the API.
For more information, please refer to the OpenAI API documentation. Also check Quick start guide for OpenAI API and Python.