
September 09, 2026
12 min read
By Kokil Thapa | Last reviewed: September 2026
You need a working OpenAI API call in minutes, not after reading fifty pages of docs. OpenAI API: A Developer Quickstart is written for engineers who already ship web apps and want a straight path from API key to production-ready integration. If you build on Laravel or PHP, the patterns here mirror what I use on client projects that add AI to booking flows, document summarisation, and support chat. For a deeper Laravel-specific walkthrough, see the OpenAI API integration in Laravel guide.
What is the OpenAI API and how does a developer get started?
The OpenAI API is a REST interface to hosted language, vision, audio, and embedding models. You send JSON over HTTPS. The API returns structured JSON with generated text, tool calls, or vector embeddings. Most quickstarts begin with chat completions because that one endpoint covers drafting, classification, extraction, and simple agents.
Before you write code, create an account at the OpenAI platform, add billing, and generate a secret key. Store that key in environment variables on your server. Treat it like a database password. A common mistake is pasting the key into JavaScript bundles or committing it to Git.
Create your API key and set environment variables
Add the key to your local .env file and your production secrets store. On Ubuntu servers I maintain, the variable lives beside database credentials and payment gateway keys.
# .env
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxx
OPENAI_ORG_ID=org-xxxxxxxx # optional
OPENAI_DEFAULT_MODEL=gpt-4o-mini Official reference docs live at OpenAI API reference. Read the authentication section once. You will reuse the same Bearer header pattern across every endpoint.
How do you make your first OpenAI API request?
The Chat Completions endpoint accepts a model name and a messages array. Each message has a role (system, user, or assistant) and content. The API returns a choices array. Index zero holds the assistant reply.
Start with cURL to confirm your key works. Then move the call into your application layer. I often test payloads with the JSON formatter tool before pasting them into Postman or code.
cURL example
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain webhooks in one paragraph."}
],
"temperature": 0.2
}' PHP example with Guzzle
Most Laravel apps already ship Guzzle through HTTP client facades. Pure PHP projects can require it via Composer 2.10. Target PHP 8.3 or higher if you run Laravel 13. Laravel 12 needs only PHP 8.2.
<?php
declare(strict_types=1);
require 'vendor/autoload.php';
$client = new GuzzleHttp\Client([
'base_uri' => 'https://api.openai.com/v1/',
'timeout' => 30,
]);
$response = $client->post('chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . getenv('OPENAI_API_KEY'),
'Content-Type' => 'application/json',
],
'json' => [
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'Reply in plain English.'],
['role' => 'user', 'content' => 'Summarise REST idempotency.'],
],
'temperature' => 0.3,
],
]);
$data = json_decode($response->getBody()->getContents(), true);
echo $data['choices'][0]['message']['content']; The response includes a usage block with prompt and completion token counts. Log those numbers from day one. They drive cost forecasts and help you catch runaway prompts early.
Which OpenAI API models should developers choose in 2026?
Model choice is a trade-off between quality, latency, and price. For classification, extraction, and internal tools, a small model often suffices. For long-form drafting or complex reasoning, step up to a flagship model only on routes that need it.
Compare OpenAI with alternatives when content quality and cost both matter. The Gemini API vs OpenAI API comparison walks through that decision with real criteria.
| Model tier | Typical use | Latency | Cost |
|---|---|---|---|
| Small / mini | Classification, tagging, short replies | Low | Lowest |
| Standard multimodal | Chat, vision on images, mixed tasks | Medium | Mid |
| Flagship | Long analysis, hard reasoning | Higher | Highest |
| Embeddings | Semantic search, RAG pipelines | Low | Per token |
Pin model names in config, not hard-coded strings scattered across controllers. When OpenAI deprecates a model, you update one config value and redeploy. That pattern matches how I handle third-party API versioning on production apps.
How do you integrate the OpenAI API into a Laravel application?
Never call OpenAI directly from Blade views or Vue components. Route user input through a controller or job. Validate input with a Form Request. Call a dedicated service class that wraps HTTP, retries, and logging.
On legal-tech portals and booking systems I have shipped, AI features sit behind the same auth and rate-limit middleware as payment endpoints. That keeps abuse surface small. For architecture patterns around versioned endpoints, read Laravel API best practices.
Minimal service class pattern
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class OpenAiChatService
{
public function reply(string $system, string $user): string
{
$response = Http::withToken(config('services.openai.key'))
->timeout(30)
->post('https://api.openai.com/v1/chat/completions', [
'model' => config('services.openai.model'),
'messages' => [
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
],
'temperature' => 0.2,
]);
if ($response->failed()) {
throw new RuntimeException($response->body());
}
return $response->json('choices.0.message.content');
}
} Queue long-running calls
HTTP requests above two seconds belong in a queued job. Return a job ID or pollable status to the browser. Users on mobile networks in Nepal tolerate async UX better than a spinning form that times out at 30 seconds.
- Add
config/services.phpentries for key, model, and timeout. - Wrap the HTTP call in a service class with typed return values.
- Dispatch a job for summaries, document review, or batch tagging.
- Store prompts and responses if audit trails matter for your domain.
- Expose a thin JSON endpoint that never forwards raw API keys.
Need someone to wire this into an existing product? That is exactly what AI integration and automation services cover — server-side wrappers, queue workers, and cost guardrails included.
How do you handle streaming, tools, and structured output?
Streaming sends partial tokens over Server-Sent Events. Your backend opens a streaming request to OpenAI, then forwards chunks to the client. The client still never holds the secret key. Official streaming guidance is in the OpenAI text generation guide.
Structured output lets you set response_format to JSON mode or supply a JSON schema. That is useful when the next step is database insertion or a typed DTO in PHP 8.5. Validate the decoded JSON against your own rules before you trust it.
Function and tool calling
Tool calling lets the model request named functions with arguments. Your app executes the function, then sends the result back as a new message. This is how you connect LLMs to order lookups, calendar slots, or internal CRM APIs without giving the model direct SQL access.
Keep tool handlers idempotent where possible. Log every tool invocation. On eCommerce and booking codebases, I treat tool calls like webhook handlers — verify inputs, enforce authorisation, and return minimal data.
What production practices keep OpenAI API integrations safe and affordable?
Production work starts when the demo works. Rate-limit public endpoints. Cap tokens per request and per user per day. Cache deterministic prompts when inputs repeat. Monitor error rates and latency percentiles the same way you monitor payment callbacks.
Security basics overlap with general API hardening. The API security checklist applies directly — auth, input validation, logging, and secret rotation. If you expose your own REST layer to mobile clients, pair AI routes with Sanctum or Passport tokens rather than session cookies alone.
Cost control checklist
- Set hard
max_tokenslimits on every call path. - Log
usagefields to Redis or your analytics DB. - Reject oversized uploads before they hit the model.
- Use smaller models for draft passes; escalate only when confidence is low.
- Alert when daily spend crosses a threshold you define in NPR or USD.
For retrieval-augmented generation, store embeddings in PostgreSQL 18 with pgvector or a dedicated vector store. The vector databases guide for PHP developers compares practical options without over-engineering day one.
When AI features ship inside a client portal — document Q&A, draft replies, intake summarisation — audit logs matter. On platforms like Mijar Law Associates client portal, every automated suggestion should trace back to a user, timestamp, and source prompt hash.
Errors you will see in the wild
401 Unauthorized means a missing or revoked key. 429 Too Many Requests signals rate limits — back off with exponential delay. 400 Bad Request often means malformed JSON or an unsupported parameter combo. Retry idempotent reads. Do not blindly retry writes that insert duplicate rows.
Compare error-handling styles with other providers if you run multi-vendor AI. The Anthropic Claude API developer guide uses similar HTTP patterns with different model names and headers.
If your product exposes a public REST surface around these features, document it properly. Teams I work with often generate OpenAPI specs and follow patterns from building RESTful APIs with Laravel. Gateways like Kong or Traefik can add global rate limits — see the Kong API gateway guide when traffic grows beyond a single app server.
New to LLM concepts before you scale? Start with what is AI — a practical guide for developers. It frames vocabulary without hype.
For broader backend ownership — design, deployment, and hardening — API development services and custom software development cover the full stack, not just the OpenAI call itself. You can also review how AI-adjacent content sites were built on Court Marriage In Nepal and Notary Nepal.
Debug messy model output with the regex tester when you parse semi-structured replies. Prototype prompts in English first; localise later with your Nepali unicode workflows if the product serves bilingual users.
Key Takeaways
- Store OpenAI keys server-side only and rotate them when staff or contractors change.
- Start with Chat Completions, log token usage, and pin model names in config files.
- Wrap HTTP calls in a service class; queue anything that might exceed two seconds.
- Use smaller models by default; escalate to flagship models only where quality demands it.
- Add rate limits, max_tokens caps, and budget alerts before you expose AI to public forms.
- Validate structured JSON output before it touches your database or business logic.
People Also Ask
Do I need a credit card to use the OpenAI API?
Yes for production usage. OpenAI bills per token across models. Free tiers change over time, so check the current platform pricing page when you estimate costs. Set billing alerts early — a runaway loop in a public form can burn through budget in hours.
Can I call the OpenAI API directly from JavaScript?
You should not expose secret keys in browser code. Anyone can extract them from bundled assets. Instead, call your own backend endpoint. Let Laravel or PHP hold the key and enforce auth, validation, and rate limits on every request.
What is the difference between Chat Completions and the Assistants API?
Chat Completions is stateless — you send the full message history each call. Assistants API adds persisted threads, built-in tools, and file handling managed by OpenAI. For most Laravel apps I maintain, Chat Completions plus my own database state is simpler and cheaper to reason about.
How do I reduce OpenAI API costs in production?
Shorten prompts, trim message history, choose smaller models, cache repeated queries, and cap max_tokens. Pre-filter junk input before it reaches the model. Track usage per feature so you know which route actually earns its keep.
Ship your first OpenAI API feature with confidence
OpenAI API: A Developer Quickstart boils down to a few habits: server-side keys, typed service wrappers, queued long jobs, and logged token usage. Get one endpoint working end to end this week. Harden it the week after. If you want help wiring AI into an existing Laravel product — intake summarisation, document drafts, or support assist — contact us or explore AI integration services. Read more on the blog, browse the portfolio, or learn about the developer behind these guides.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

