Learn how to integrate GPT-5.2 API into a Next.js application to create a dynamic medical quiz app.
Prerequisites
- Node.js v18.0 or higher
- Next.js v13.0 or higher
- OpenAI API key
- Basic knowledge of React and Next.js
What We’re Building
In this tutorial, we will build a medical quiz application using Next.js and the GPT-5.2 API from OpenAI. This application will dynamically generate medical quiz questions and provide real-time feedback to users based on their responses. The application will leverage the latest capabilities of GPT-5.2 to formulate questions and analyze user answers, providing an engaging and educational experience.
The final application will allow users to test their medical knowledge with a variety of questions pulled from a large dataset of medical information. Each interaction with the quiz will involve real-time API calls to generate new questions and validate answers, ensuring a unique experience every time.
Setup and Installation
To get started, we need to set up a new Next.js project and install the necessary dependencies. We will also configure environment variables to securely manage our API key.
npx create-next-app@latest medical-quiz-app --ts
cd medical-quiz-app
npm install openai
Next, we need to set up environment variables to store our OpenAI API key securely. Create a new file named .env.local in the root directory of your project and add your API key like so:
OPENAI_API_KEY=your_openai_api_key_here
Step 1: Setting Up the API Route
In this step, we’ll set up an API route in our Next.js application to handle requests to the GPT-5.2 API. This will be used to fetch quiz questions and validate answers.
import { OpenAI } from 'openai';
const client = new OpenAI(process.env.OPENAI_API_KEY);
export async function POST(request: Request) {
try {
const { question } = await request.json();
const response = await client.chat.completions.create({
model: "gpt-5.2",
messages: [{ role: "system", content: "You are a medical quiz generator." }, { role: "user", content: question }],
});
return new Response(JSON.stringify({ answer: response.choices[0].message.content }), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response(JSON.stringify({ error: 'Failed to fetch data from OpenAI' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
This code defines a POST method for our API route, which receives a question from the client, sends it to the GPT-5.2 API, and returns the generated response. We handle errors gracefully by returning a 500 status code with an error message if the API call fails.
Step 2: Creating the Quiz Interface
Now that we have our API route set up, let’s create a user interface for our quiz application. We’ll use React components to build a simple interface where users can submit questions and receive feedback.
import { useState } from 'react';
export default function Quiz() {
const [question, setQuestion] = useState('');
const [answer, setAnswer] = useState('');
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question }),
});
const data = await response.json();
setAnswer(data.answer);
};
return (
<div>
<h1>Medical Quiz</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder="Enter your question"
/>
<button type="submit">Submit</button>
</form>
{answer && <p>Answer: {answer}</p>}
</div>
);
}
This component maintains state for the user’s question and the answer returned from the API. When the form is submitted, it sends the question to our API route and updates the answer state with the response.
Step 3: Enhancing User Experience
To improve the user experience, let’s add some error handling and loading states to our application. This will inform users when data is being fetched and handle any errors that occur during the process.
import { useState } from 'react';
export default function Quiz() {
const [question, setQuestion] = useState('');
const [answer, setAnswer] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
setLoading(true);
setError('');
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question }),
});
const data = await response.json();
setAnswer(data.answer);
} catch (err) {
setError('Failed to fetch data. Please try again.');
} finally {
setLoading(false);
}
};
return (
<div>
<h1>Medical Quiz</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder="Enter your question"
/>
<button type="submit" disabled={loading}>Submit</button>
</form>
{loading && <p>Loading...</p>}
{answer && <p>Answer: {answer}</p>}
{error && <p style={{ color: 'red' }}>{error}</p>}
</div>
);
}
We’ve added a loading state to indicate when the API call is in progress and an error state to display any issues that arise. This ensures users are kept informed throughout their interaction with the application.
Testing Your Implementation
To verify that everything is working correctly, start your Next.js development server and interact with the quiz application. Ensure that questions are being sent to the API and answers are returned correctly. Watch for any error messages and check the console for potential issues.
npm run dev
Open your browser and navigate to http://localhost:3000 to interact with your quiz application. Enter a question and submit it to see the response. Ensure the loading and error states behave as expected.
What to Build Next
- Enhance the quiz with multiple-choice questions and validate user selections against the correct answers.
- Integrate a scoring system to track user performance over multiple quiz sessions.
- Add user authentication to save quiz results and track progress over time.
Consider how this application could be adapted for use in GCC countries, aligning with initiatives like Saudi Vision 2030 or the UAE’s National Strategy for AI. Collaborations with regional healthcare providers or educational institutions could enhance the app’s impact and reach.