How to integrate OpenAI GPT API in Django REST Framework project?

I’m building a Django REST Framework (DRF) project and I want to integrate OpenAI GPT API to provide AI-powered responses to users.

I’ve tried setting up the API call using Python’s requests library and also with the official openai Python package, but I’m running into issues with authentication and response handling.

Here’s my current code snippet:

import openai

openai.api_key = "os.environ["OPENAI_API_KEY"]"

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello, can you help me with Django?"}
    ]
)

print(response['choices'][0]['message']['content'])

Problem:

Sometimes I get an authentication error: "Invalid API key"

Other times the API call works but I’m not sure how to integrate it properly into a DRF view so that it returns a JSON response to the frontend.

What I want:

A clear way to call OpenAI GPT from a Django REST API endpoint

Return the GPT response in JSON format to a React frontend

What I’ve tried:

Adding API key in .env and using os.environ

Wrapping the call inside a DRF APIView — but facing serialization issues

Any advice or working example would be highly appreciated 🙏

I tried calling the OpenAI GPT API inside a Django REST Framework APIView using the official openai Python package. I expected to get the AI’s response as JSON and return it to my React frontend. However, I’m getting either an authentication error (Invalid API key) or issues with serializing the response in DRF.

Вернуться на верх