Skip to content
trending

Guides

What is an API? Explained with AI Examples and Your First curl

An API is a contract between two programs: one sends a request in an agreed format, the other sends back a response. Learn JSON, HTTP methods, error codes, and run your first AI query.

By 8 min read
What is an API? Explained with AI Examples and Your First curl

👁 123 reads

An API is a contract between two programs: one sends a request in an agreed format, the other sends back a response, also in an agreed format. When your script asks an AI model to summarize an email, it doesn’t click a chat window - it sends a packet of text over the internet in JSON format and gets JSON back. This text is the first step in the AI API from scratch path, where we show everything through real queries run on our computer.

API in Plain English: A Service Window

The simplest way to picture an API is as a service window at an office that only accepts filled-out forms. You don’t see the back office, you don’t know who handles your request or how. But you do know three things:

  • which window to approach - that’s the address, or endpoint, e.g. https://openrouter.ai/api/v1/chat/completions;
  • how to fill out the form - that’s the request format described in the documentation: which fields are required, which are optional;
  • what credentials to show - that’s the API key you attach to every request.

The clerk sends back either your completed request or a slip with an error code: “missing signature,” “too many requests today,” “system down.” In APIs, these are HTTP status codes, which we cover below.

The difference between chat and API is that chat (ChatGPT, Claude, Gemini) is a ready-made application for humans, while API is access to the same model for programs. Through the API, the model doesn’t remember your conversations, has no buttons or history. But you can call it a thousand times from a spreadsheet, a bot, or an automation that runs at night. You pay not by subscription but for tokens used - chunks of text - which we explain in AI Tokens: What They Are and What They Cost.

Request and Response

Every conversation with an API consists of two parts. A request contains:

  1. Method - what you want to do. For AI models you almost always send POST, because you’re passing content.
  2. Address - the endpoint of a specific function, e.g. text generation or model list.
  3. Headers - metadata: API key (Authorization: Bearer ...) and content type (Content-Type: application/json).
  4. Body - the actual data: which model, what messages, what parameters.

The response has a status code (e.g. 200, meaning all good) and content containing the generated text and a count of tokens used. Here’s a real response we received on October 4, 2026 from the GPT-6 Luna model through OpenRouter (we’ve shortened it to the most important fields):

{
  "id": "gen-1791114764-uKPpeyAgJg4GJmOQhMp4",
  "object": "chat.completion",
  "model": "openai/gpt-6-luna",
  "provider": "OpenAI",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "Kraków zachwyca zabytkowym Rynkiem Głównym, klimatycznymi uliczkami i bogatą historią."
      }
    }
  ],
  "usage": {
    "prompt_tokens": 16,
    "completion_tokens": 36,
    "total_tokens": 52,
    "cost": 0.0000196
  }
}

We read it like this: the model responded with a sentence about Krakow (content), finished normally (finish_reason: stop), used 16 tokens on input and 36 on output, and the entire query cost 0.0000196 USD, or less than two thousandths of a cent.

JSON in 2 Minutes

JSON (JavaScript Object Notation) is a text format for storing data that both humans and every programming language can read. You only need to know five elements:

  • { } - object, a collection of “key: value” pairs, e.g. {"model": "openai/gpt-6-luna"};
  • [ ] - array, e.g. a list of messages in a conversation;
  • "text" - string always in double quotes (single quotes are an error);
  • numbers without quotes: 0.7, 1024 - with a period, not a comma;
  • true, false, null - true, false, no value.

A query to an AI model is an object with a model field and a messages array. Each message has a role (system - instruction for the model, user - you, assistant - previous model responses) and content:

{
  "model": "openai/gpt-6-luna",
  "messages": [
    {"role": "user", "content": "Napisz jedno zdanie o Krakowie."}
  ]
}

The most common beginner mistake is a comma after the last element in an array or object. JSON doesn’t forgive this and the server will respond with code 400. When the model needs to return JSON, not just accept it, you’ll want the mode described in Structured Output: How to Force AI to Respond in JSON.

HTTP Methods: GET, POST and the Rest

Method Meaning Example in AI API
GET retrieve data, change nothing model list: GET /api/v1/models
POST send data for processing generate response: POST /api/v1/chat/completions
PATCH / PUT modify existing resource changing limit on a key through key management API
DELETE delete resource deleting a file or key

In practice, for the first few weeks you’ll use two: GET to check what’s available, and POST to generate.

Status Codes and Errors: 401, 429, 500 and Others

A status code is a three-digit number at the start of the response. The first digit tells you whose fault it is: 2xx - success, 4xx - error on your side, 5xx - error on the server side.

Code What It Means What to Do
200 OK, response is in the body nothing, read the result
400 bad request: JSON error, unknown model, bad parameter read the message, fix the request, don’t retry in a loop
401 missing key or invalid key check environment variable and whether the key was disabled
402 insufficient funds in account (OpenRouter) top up account or raise key limit
403 no permission, e.g. model unavailable in region or content blocked by moderation change model or content
404 no such address or model check for typo in address
429 too many requests in short time (rate limit) or quota exhausted wait and retry with increasing delay
500, 502, 503 failure or overload on provider side retry after a few seconds, possibly switch provider
529 overload (code used by Anthropic) same as 503

We checked what actually comes back when we forget the key. A request without the Authorization header to OpenRouter:

$ curl -s https://openrouter.ai/api/v1/chat/completions -H "Content-Type: application/json" -d '{"model":"openai/gpt-6-luna","messages":[{"role":"user","content":"hej"}]}'
{"error":{"message":"No cookie auth credentials found","code":401}}

And here are two errors caught by our Python script: bad key and nonexistent model. Interesting note: OpenRouter returns 400 for an unknown model, not 404, so don’t assume one number for one situation in your code.

401: check API key (Error code: 401 - {'error': {'message': 'User not found.', 'code': 401}})
400: fix request (Error code: 400 - {'error': {'message': 'openai/gpt-7-nie-istnieje is not a valid model ID', 'code': 400}})

How to handle these codes in code and automatically retry requests after 429 is shown in First API Query to AI in Python.

Your First curl: Query from the Terminal

curl is a program for sending HTTP requests from the command line. It’s built into Windows 10 and 11 (as curl.exe), macOS and Linux, so you don’t install anything. First, a GET query that doesn’t require a key - the model list at OpenRouter:

{"data":[{"id":"inclusionai/ling-3.1-flash","canonical_slug":"inclusionai/ling-3.1-flash-20261002","hugging_face_id":null,"name":"inclusionAI: Ling 3.1 Flash","created":1790950024,"description":"Ling 3.1 Flash is a hybrid reasoning mixture-of-experts model from inclusionAI, with 25B active parameters out of 560B total.","context

We got an object with a data array that on October 4 contained 466 models. Now POST, a real question to the model. First you need a key (instructions for four providers are in API Key: How to Get One and How Not to Burn It). In Git Bash, on Linux and on Mac:

#!/usr/bin/env bash
# First query through curl (Git Bash, Linux, macOS). First: export OPENROUTER_API_KEY=sk-or-v1-...
curl -s https://openrouter.ai/api/v1/chat/completions 
  -H "Authorization: Bearer $OPENROUTER_API_KEY" 
  -H "Content-Type: application/json" 
  -d '{
    "model": "openai/gpt-6-luna",
    "messages": [{"role": "user", "content": "Napisz jedno zdanie o Krakowie."}]
  }'

In PowerShell, quotes in JSON cause problems, so we keep the request body in a zapytanie.json file (shown above), and curl just sends it. Note curl.exe instead of curl - in older PowerShell, plain curl is an alias for a different command:

# Windows PowerShell: request body in zapytanie.json file (avoids quote problems)
# First in the same window: $env:OPENROUTER_API_KEY = "sk-or-v1-..."
curl.exe -s https://openrouter.ai/api/v1/chat/completions `
  -H "Authorization: Bearer $env:OPENROUTER_API_KEY" `
  -H "Content-Type: application/json" `
  -d "@zapytanie.json"

We ran both variants on Windows 11 (Git Bash with curl 8.22 and Windows PowerShell). The model responded in both cases with one sentence about Krakow, and each query cost about 0.00002 USD. Both files are in the ai-api-starter package.

What’s Next

  1. Create an account and key: API Key in OpenAI, Anthropic, Google AI Studio and OpenRouter.
  2. Write your first script: First API Query to AI in Python.
  3. Calculate costs: AI Tokens and Cost Calculator.
  4. When APIs hold no more secrets, move to automation and agents: AI Agents from Scratch.

Frequently Asked Questions

What is an API in simple terms?

It’s a way for one program to order something from another: it sends a request in an agreed format and gets a response in an agreed format. It doesn’t need to know how the other program works inside.

What does the acronym API stand for?

Application Programming Interface. Interface because it’s the “contact point” between two programs, just as a screen and buttons are an interface for humans.

Do you need to know how to code to use an API?

Not for your first query: curl and a copied command are enough. For something useful you’ll want basic Python or an automation tool like n8n or Zapier that send requests for you.

How is an API different from ChatGPT?

ChatGPT is an application with a subscription, history, and interface for humans. OpenAI’s API is access to models for programs, billed by tokens, with no conversation history and no chat window. A ChatGPT subscription doesn’t include API access - they’re separate accounts and separate payments.

What is a REST API?

It’s the most popular style of building APIs: resources have their own addresses, you choose operations with HTTP methods (GET, POST, DELETE), and you usually send data in JSON. AI model APIs are built in this style.

Google · Your sourcesQuantslant higher in your Google - one clickAdd to preferred sources →

Sources and Verification Date

We ran the queries on October 4, 2026 on Windows 11 through OpenRouter, total cost of examples in this text: below 0.0001 USD.

Kinetyra

// read next

More on this from QUANTSLANT

Piotr Olszewski

Editor and publisher · Quantslant

I edit and publish Quantslant. AI tools help with research, drafts and translation; choosing topics, running the tests, checking facts and the decision to publish are mine, and so is the responsibility for what appears here.

read nextAPI Key Guide: OpenAI, Claude, Gemini & OpenRouterguidesAPI Key Guide: OpenAI, Claude, Gemini & OpenRouterHow to get an API key from OpenAI, Anthropic, Google AI Studio and OpenRouter, store it securely in .env, set spending limits, and respond to a leak.

Most read

  1. 1Best AI Video Generator Apps for Your Phone (2026)
  2. 2Claude Opus 5.5 Motion Graphics: 60s Showreel from One Prompt
  3. 3Wan 2.2 on RTX 4090: timings, VRAM and four test clips
// site map

This page in other languages6

Quantslant in numbers 1,423posts in archive22news from the last 7 days18video models in the observatory
🎬 AI Video Benchmarks: Higgsfield DoP vs OpenAI Sora • Higgsfield vs Runway Gen-3 • AI Video Credit Calculator
× ‹ enlarge ›