skip to Main Content

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


  1. Chosen as BEST ANSWER

    The solution is to use json.dumps() on the data before sending it to the request.

    Working Code

    url = "https://api.tiktokenizer.dev/openai"
    headers = {"Authorization": "Bearer <OPENAI_API_KEY>"}
    data = json.dumps({
        "email": "<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())
    

    Returns

    {'message': 'The capital city of Portugal is Lisbon.', 'usage':{'totalTokensUsed': 27}, 'newUserCreated': False}
    

  2. After the code

    response = requests.post(url, headers=headers, json=data)
    

    You can print the raw response if the JSON is not valid.

    if response.status_code == 200:
        try:
            response_data = response.json()
            print(response_data)
        except json.JSONDecodeError:
            print("Response is not valid JSON:")
            print(response.content)
    else:
        print("Error:", response.status_code)
    

    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 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search