I am trying to use an API but all the examples are in JS, and my project is in python.
Here is the sample code they gave me.
const request = await fetch("https://api.tiktokenizer.dev/openai", {
headers: { Authorization: "Bearer <OPENAI_API_KEY>" },
method: "POST",
body: JSON.stringify({
email: "<APP_USER_EMAIL>",
appId: "<APPID>",
developerKey: "<KEY>",
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: "Hey ChatGPT, what's the capital of Portugal?",
},
],
}),
});
const response = await request.json();
I tried to solve this on my own with this code.
import requests
url = "https://api.tiktokenizer.dev/openai"
headers = {"Authorization": "Bearer <OPENAI_API_KEY>"}
data = {
"email": "<APP_USER_EMAIL>",
"appId": "<APPID>",
"developerKey": "<KEY>",
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "Hey ChatGPT, what's the capital of Portugal?",
},
],
}
response = requests.post(url=url, headers=headers, json=data)
print(response.json())
With the above code I filled in all the needed info but I got this error.
{'error': 'Unexpected token o in JSON at position 1'}
What should happen is I get something like this back.
{
message: "The capital of Portugal is Lisbon.",
usage: {
totalTokens: 25,
},
newUserCreated: false,
}
2
Answers
The solution is to use json.dumps() on the data before sending it to the request.
Working Code
Returns
After the code
You can print the raw response if the JSON is not valid.
This should help you diagnose the issue and understand what the server is returning.
You can then adjust your code accordingly based on the actual response content.
Hope this helps! Happy coding 🙂