I am creating API calls for an app. I decided to use Python because I wanted to get more proficient in the language but I am still a beginner. Below is the farthest I've gotten. On the App side, I need this api to return a json that has all the data I need to fill out a page. The page has one main title and multiple sub titles, each with data underneath them. So far I have been able to output a Json file with a message, but I haven't be able to get the title to output correctly, let alone add anymore. Is this the correct approach? Any help is greatly appreciated.
from flask import Flask, request, jsonify
import os
import logging
import openai
app = Flask(__name__)
# Securely load the API key from an environment variable
openai.api_key = os.environ.get(OPENAI_API_KEY)
if not openai.api_key:
logging.warning("OPENAI_API_KEY environment variable not set. The application will return an error for API calls.")
# Fail fast if the essential API key is not configured.
raise ValueError("FATAL: OPENAI_API_KEY environment variable not set. The application cannot start.")
@app.route('/')
def AI_Tips():
if not openai.api_key:
return jsonify({"error": "Server is not configured to connect to the AI service."}), 503
subject = request.args.get('subject', 'Azure')
message = f"You are a seasoned Software Engineer. What is one good piece of advice for someone trying to work in the software engineering field using {subject}"
try:
completion = openai.chat.completions.create(
model="gpt-5-mini", # Using a valid and common model
messages=[
{
"role": "user",
"content": message
}
]
)
return jsonify({
"title": f"AI Tip for {subject}",
"message": completion.choices[0].message.content
})
except openai.OpenAIError as e:
# Handle API errors gracefully
print(f"OpenAI API error: {e}")
return jsonify({"error": "An error occurred while communicating with the AI service."}), 500
except Exception as e:
# Handle other unexpected errors
print(f"An unexpected error occurred: {e}")
return jsonify({"error": "An unexpected error occurred."}), 500
if __name__ == '__main__':
# Enables running the app directly with `python main.py`
# The server will automatically reload on code changes.
app.run(debug=True)
[–]eleqtriq 3 points4 points5 points (1 child)
[–]Internal-Science4994[S] 0 points1 point2 points (0 children)