I'm trying to add an API to my webpage and have never used any Flask server before, I have never used Javascript too so this is a completely brand new learning experience. My problem is that I keep receiving a 405 error code saying that the method is not allowed. I keep on using the POST method but it isn't working, I am banking that my issue may be with my HTML code more than my Flask server because the code is extremely generic and simple.
import openai
from flask import Flask, request, jsonify
app = Flask(__name__)
openai.api_key = '**my key is in here**'
@app.route('/', methods=['POST'])
def chat():
data = request.get_json()
message = data.get('message')
response = openai.Completion.create(
model="gpt-3.5-turbo",
prompt=message,
max_tokens=50
)
return {'response': response.choices[0].text.strip()}
if __name__ == '__main__':
app.run(port=5000)
async function sendMessage() {
const message = document.getElementById('message').value;
document.getElementById('chat-box').innerHTML += `<div>You: ${message}</div>`;
const response = await fetch('/', {
method: "POST",
body: JSON.stringify({ message }),
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
document.getElementById('chat-box').innerHTML += `<div>Bot: ${data.reply}</div>`;
document.getElementById('message').value = '';
}
I tried changing up the structure of the code, I uninstalled Flask and reinstalled it again. I've also extensively used chatgpt to try and come up with better code but it just kept taking me in circles. I'm hoping someone can help with this. I even tried a simple server that just said hello world which worked, but I truly think the issue might be with my javascript. Also, I am a beginner and this is supposed to be one of my first coding projects so please take it easy on me if possible. Thanks.
You have to add a route for '/' to serve the html file. I also fixed the way you call the OpenAI API because you're using a deprecated one.
import openai
from flask import Flask, request, jsonify, render_template
chat_client = OpenAI(api_key='....')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def chat():
data = request.get_json()
message = data.get('message')
response = chat_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": message}
],
max_tokens=50
)
return jsonify({'reply': response.choices[0].message.content.strip()})
if __name__ == '__main__':
app.run(port=5000, debug=True)
sample index.html that I tested with
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat app</title>
<script>
async function sendMessage() {
const message = document.getElementById('message').value;
document.getElementById('chat-box').innerHTML += `<div>You: ${message}</div>`;
const response = await fetch('/', {
method: "POST",
body: JSON.stringify({ message }),
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
document.getElementById('chat-box').innerHTML += `<div>Bot: ${data.reply}</div>`;
document.getElementById('message').value = '';
}
</script>
</head>
<body>
<div id="chat-box"></div>
<input type="text" id="message" placeholder="Type your message here...">
<button onclick="sendMessage()">Send</button>
</body>
</html>
Directory structure
- app.py
- templates/
- index.html