First API request
First API request
This lesson covers first HTTP call to OpenAI in the context of PHP web apps using OpenAI and similar APIs. The focus is practical understanding of how the feature affects architecture, cost, and user experience in production.
Through the BrainTech AI Developer course you build modular integration from the first API call to RAG, agents, and local models. Examples use PHP 8, .env for secrets, and clear frontend/backend separation without exposing API keys to the client.
In depth
We explain first HTTP call to OpenAI in depth: when to apply it, which parameters to tune, and how to test before production. In PHP use a service class (e.g. AiClient) encapsulating HTTP calls, error logging, and token metering. Document expected inputs/outputs and define fallback behavior when the model fails or the API returns rate limits.
Key points
- Understand the core concept: first HTTP call to OpenAI.
- Integrate in PHP 8 backend without exposing secrets.
- Test on sandbox API keys before production.
- Measure tokens and cost per request.
- Validate and sanitize AI output before showing users.
- Error logging and retry strategy for reliability.
Practical example
Sample PHP code for this lesson.
<?php
declare(strict_types=1);
$apiKey = getenv('OPENAI_API_KEY');
$payload = [
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'user', 'content' => 'Objasni u jednoj rečenici šta je REST API.'],
],
'temperature' => 0.3,
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode((string) $response, true, 512, JSON_THROW_ON_ERROR);
echo $data['choices'][0]['message']['content'] ?? '';Common mistake
A common mistake with first HTTP call to OpenAI is hardcoding API keys in the repo, sending secrets to the browser, or trusting AI output without validation. In production always use server-side calls, restrict user permissions, and log for audit.
Summary
After this lesson you understand first HTTP call to OpenAI in your PHP stack and know the next course step. Practice on a small example before embedding in ERP, CRM, or internal portals — measure tokens and latency from day one.
