Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

OpenAI API: A Developer Quickstart

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.

OpenAI API Quickstart FlowAccountBilling + keyEnv varsServer onlyHTTP POSTChat endpointResponseJSON outputNever Do ThisExpose keys in browser JavaScriptCommit .env files to GitSkip rate limits on public formsProxy through your backend instead
OpenAI API: A Developer Quickstart — account setup, server-side key storage, and first HTTP call

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 tierTypical useLatencyCost
Small / miniClassification, tagging, short repliesLowLowest
Standard multimodalChat, vision on images, mixed tasksMediumMid
FlagshipLong analysis, hard reasoningHigherHighest
EmbeddingsSemantic search, RAG pipelinesLowPer 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.

Chat Completions PayloadRequest JSONmodel: gpt-4o-minimessages: [system, user, assistanttemperature: 0.2max_tokens: optionalresponse_format: jsontools / functions optionalResponse JSONid, model, createdchoices[0].messagerole: assistantcontent: text or tool_callsusage.prompt_tokensusage.completion_tokensfinish_reason: stop / lengthHTTPS
Request and response shape for OpenAI API chat completions calls

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.

  1. Add config/services.php entries for key, model, and timeout.
  2. Wrap the HTTP call in a service class with typed return values.
  3. Dispatch a job for summaries, document review, or batch tagging.
  4. Store prompts and responses if audit trails matter for your domain.
  5. 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.

Tool Calling LoopYour Laravel appOpenAI APImodel + toolsYour databaseor internal APIuser messagetool_callExecute tool handlerReturn tool resultFinal assistant message
Tool-calling loop: model requests a function, your app executes it, then the model completes the reply

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_tokens limits on every call path.
  • Log usage fields 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.

Production OpenAI API ArchitectureBrowserLaravel APIauth + limitsQueueRedis driverOpenAI APIchat + embedShared InfrastructureMySQL / PostgresRedis cacheLogs + metricsKeys in .env only — rotate on staff changeBudget alerts before month-end surprises
Production OpenAI API setup: Laravel backend, queue workers, Redis, and observability

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

A REST interface over HTTPS to OpenAI's hosted language, vision, audio, and embedding models. You send JSON and receive structured JSON with generated text, tool calls, or vector embeddings.

Yes for production usage. OpenAI bills per token across models. Set billing alerts early—a runaway loop in a public form can burn through budget in hours.

No. Never expose secret keys in browser bundles or frontend code. Call your own backend endpoint instead and let Laravel or PHP hold the key while enforcing auth, validation, and rate limits.

Create an account at the OpenAI platform, add billing, and generate a secret key stored in environment variables. Test with cURL against the Chat Completions endpoint at api.openai.com/v1/chat/completions using a Bearer token and Content-Type application/json header. Send a model name such as gpt-4o-mini and a messages array with system, user, and assistant roles. The response returns a choices array where index zero holds the assistant reply. Once cURL confirms your key works, move the same payload into Guzzle or Laravel's HTTP client with a 30-second timeout.

Treat the key like a database password. Add OPENAI_API_KEY to your local .env file and production secrets store alongside database and payment gateway credentials. Optionally set OPENAI_ORG_ID and OPENAI_DEFAULT_MODEL in the same file. Never paste the key into JavaScript bundles, Blade views, Vue components, or Git commits. On Ubuntu servers I maintain, the variable lives server-side only. Rotate keys when staff or contractors change. Read OpenAI's authentication section once—you reuse the same Bearer header pattern across every endpoint.

Never call OpenAI directly from Blade views or Vue components. Route user input through a controller or job, validate with a Form Request, and call a dedicated service class wrapping HTTP, retries, and logging. Add key, model, and timeout entries in config/services.php and read them via config() instead of hard-coded strings. Use Laravel's Http facade with withToken(), timeout(30), and post to the chat/completions URL. On legal-tech portals and booking systems I've shipped, AI features sit behind the same auth and rate-limit middleware as payment endpoints. Dispatch queued jobs for summaries or document review and expose a thin JSON endpoint that never forwards raw API keys.

Model choice balances quality, latency, and price. For classification, extraction, and internal tools, a small or mini model such as gpt-4o-mini often suffices. Standard multimodal models suit chat and vision on images at medium latency and cost. Flagship models fit long analysis and hard reasoning but carry higher latency and expense. Embeddings power semantic search and RAG pipelines at low latency with per-token pricing. Pin model names in config files, not scattered strings across controllers. When OpenAI deprecates a model, update one config value and redeploy—a pattern I use for third-party API versioning on production apps.

Shorten prompts, trim message history, choose smaller models by default, and set hard max_tokens limits on every call path. Cache deterministic prompts when inputs repeat and pre-filter junk input before it reaches the model. Use smaller models for draft passes and escalate to flagship models only when quality demands it. Log usage fields from API responses to Redis or your analytics database so you know which route earns its keep. Alert when daily spend crosses a threshold you define in NPR or USD. Without these guardrails, a runaway loop in a public form can burn through budget in hours.

Chat Completions is stateless—you send the full message history on each call and manage conversation state in your own database. The 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. You control prompts, logging, and cost caps directly without an extra abstraction layer. Start with Chat Completions for drafting, classification, extraction, and simple agents, then evaluate Assistants only if managed threads and OpenAI-hosted tooling clearly reduce your backend work.

HTTP requests above two seconds belong in a queued job. Return a job ID or pollable status to the browser instead of holding the connection open on a spinning form. Users on mobile networks in Nepal tolerate async UX better than a request that times out at 30 seconds. Summaries, document review, and batch tagging are typical queue candidates. Keep a 30-second timeout on shorter synchronous calls. Pair queued jobs with logged token usage so you can forecast costs and catch runaway prompts even when work runs in the background.

Streaming sends partial tokens over Server-Sent Events. Your backend opens a streaming request to OpenAI, then forwards chunks to the client—the client never holds the secret key. Structured output uses response_format JSON mode or a supplied JSON schema, useful when the next step is database insertion or a typed DTO in PHP 8.5. Validate decoded JSON against your own rules before trusting it. Tool calling lets the model request named functions with arguments; your app executes them and sends results back. Treat tool handlers like webhook handlers—verify inputs, enforce authorisation, keep them idempotent, and log every invocation.

Rate-limit public endpoints and cap tokens per request and per user per day. Monitor error rates and latency percentiles the same way you monitor payment callbacks. Pair AI routes with Sanctum or Passport tokens if you expose REST to mobile clients. Reject oversized uploads before they hit the model. For client portals with document Q&A or intake summarisation, store audit logs linking every automated suggestion to a user, timestamp, and source prompt hash. Apply general API security basics—auth, input validation, logging, and secret rotation. Gateways like Kong or Traefik can add global rate limits as traffic grows beyond a single app server.

401 Unauthorized means a missing or revoked key—check OPENAI_API_KEY in your environment and confirm the Bearer header format. 429 Too Many Requests signals rate limits; back off with exponential delay before retrying. 400 Bad Request often means malformed JSON or an unsupported parameter combination—test payloads with a JSON formatter before pasting into Postman or code. Retry idempotent reads, but do not blindly retry writes that could insert duplicate rows. If you run multi-vendor AI, compare error-handling with other providers; Anthropic Claude uses similar HTTP patterns with different model names and headers.

Every Chat Completions response includes a usage block with prompt and completion token counts. Log those numbers from your first successful call, not after launch. They drive cost forecasts and help you catch runaway prompts early. Store usage per feature route so you know which endpoint actually earns its keep. Write counts to Redis or your analytics database alongside request metadata. When daily spend crosses a threshold you define, alerts prevent surprise bills. OpenAI bills per token across models, so usage logs are your primary tool for deciding when to escalate from a small model to a flagship model on each route.

Embeddings endpoints produce vector representations for semantic search and RAG pipelines at low latency with per-token pricing. Store embeddings in PostgreSQL 18 with pgvector or a dedicated vector store depending on scale—compare practical options without over-engineering day one. Retrieve relevant chunks, inject them into your messages array, then call Chat Completions with a model pinned in config. Keep retrieval and generation in a server-side service class with timeouts and logged usage. Validate any structured JSON output before database insertion. Rate-limit the public endpoint that triggers RAG queries to control both abuse and spend.

Share this article

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.

Quick Contact Options
Choose how you want to connect me: