Skip to content

API Fundamentals: Understanding "Conversations Between Programs" from Scratch

🎯 Core Question

What is an API? It's like asking: how should a restaurant design its menu so guests can understand it at a glance? How should waiters take orders without making mistakes? APIs solve the problem of "how programs communicate with each other." You've been using APIs since your first day of coding — you just might not have realized it.


0. Three Common Confusions for Beginners

Confusion 1: Are APIs something advanced?

Many people think APIs are only for senior engineers. But you've already used APIs:

python
len("hello")        # This is a Python API
open("file.txt")    # This is also an API
requests.get(url)   # This is still an API

Confusion 2: What's the difference between Web APIs and regular APIs?

TypeTargetCommunication MethodTypical Scenario
Function APILocal codeFunction calllen(), open()
OS APIOperating systemSystem callFile I/O, process creation
Web APIRemote serverHTTP requestCalling AI models, getting weather

Confusion 3: Should I use HTTP or SDK?

python
# HTTP approach: handle all details yourself
import requests
response = requests.post(
    "https://api.deepseek.com/v1/chat/completions",
    headers={"Authorization": "Bearer sk-xxx"},
    json={"model": "deepseek-chat", "messages": [...]}
)
result = response.json()["choices"][0]["message"]["content"]

# SDK approach: let the butler handle it
from openai import OpenAI
client = OpenAI(api_key="sk-xxx")
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[...]
)
result = response.choices[0].message.content

1. The Essence of APIs: Plugs and Sockets

API (Application Programming Interface) is simply the "agreement for communication between programs."

1.1 Appliance Analogy

ConceptAppliance AnalogyAPI Equivalent
InterfaceSocket shapeFunction signature / URL
InputElectrical current inputFunction parameters / Request body
OutputAppliance operatesReturn value / Response body

1.2 Three Types of API Comparison

TargetLocal code library
CommunicationFunction call
LatencyNanoseconds
Typical scenariosData processing, file operations
Function API example
len("hello")           # returns 5
max([1, 5, 3])         # returns 5
open("file.txt").read() # reads a file

1.3 Function API vs HTTP API: What's the Difference?

Many beginners wonder: what's the real difference between function APIs and HTTP APIs? How to tell them apart when reading documentation?

📚 Function API vs HTTP APILocal calls vs network requests: how should you read the docs?
📦Function API
Call styleDirect function call
ParametersArguments inside parentheses
Return valueReturn value directly
Error handlingException or return value
Python example
# Call a built-in function
length = len("hello")      # returns 5

# Call a library function
import math
result = math.sqrt(16)     # returns 4.0

# Call a custom function
def add(a, b):
    return a + b
sum = add(3, 5)            # returns 8
VS
🌐HTTP API
Call styleNetwork request
ParametersURL / body / headers
Return valueJSON/XML response
Error handlingStatus code checks
HTTP request example
POST /v1/chat/completions HTTP/1.1
Host: api.deepseek.com
Authorization: Bearer sk-xxx
Content-Type: application/json

{
  "model": "deepseek-chat",
  "messages": [
    {"role": "user", "content": "Hello"}
  ]
}
Core point:A function API works locally; an HTTP API communicates remotely. Function docs focus on parameters and return values, while HTTP API docs focus on endpoint, authentication, and request/response formats.

1.4 How to Read Different Types of API Documentation

Different types of API documentation have different focus areas:

📋 How to Read Different Doc TypesFunction docs, REST API docs, and SDK docs each emphasize different things
Doc typeFunction docs
Best forUsing standard library or third-party functions
Difficulty⭐⭐
🔍 What to focus on
Function signatureParameter typesReturn valueExceptionsExample code
📝Doc example
### json.loads(s, *, cls=None, object_hook=None...)

Parse a JSON string into a Python object.

**Parameters:**
- s (str): JSON string to parse
- cls (JSONDecoder): Custom decoder class
- object_hook (callable): Optional conversion function

**Returns:**
- dict | list: Parsed Python object

**Raises:**
- JSONDecodeError: The string is invalid JSON

**Example:**
>>> import json
>>> json.loads('{"name": "Alice"}')
{'name': 'Alice'}
💡Reading tips
  • Read the function signature first to see what parameters are needed.
  • Check parameter types and whether each parameter is required.
  • Check the return type so later code can handle it correctly.
  • Notice possible exceptions and prepare error handling.
📊Quick comparison of three doc types
Item
Function docs
REST API docs
SDK docs
Core focus
Parameters, return values
Endpoint, request body
Initialization, method chain
Code example
Function call
HTTP request
Object method
Error handling
Exceptions/return values
Status codes
Exception objects
Read first
Function signature
Base URL + Auth
Quick Start
Reading advice:For function docs, read the signature. For API docs, read the request format. For SDK docs, read examples first. When stuck, look for Quick Start or Getting Started.

2. A Complete API Call

👇 Try it out: Click the button below to observe a complete API request-response flow:

API Request Demo
// Click a command below to simulate API requests
>
💻ClientSends request
Waiting for request...
HTTP Request
🖥️ServerHandles request
Waiting...
HTTP Response
📦ResponseReturns result
Waiting for response...
💡 Click a command button to observe a complete API request-response flow.

2.1 Four Stages of an API Call

StageWhat HappensAppliance Analogy
RequestClient sends request to serverPressing a switch
TransmissionRequest travels through network to serverCurrent flows through wires
ProcessingServer processes request and returns dataAppliance starts working
ResponseClient receives and processes the resultLight bulb lights up

2.2 Restaurant Analogy

Restaurant RoleAPI EquivalentDescription
MenuAPI DocumentationTells you what "dishes" are available
WaiterHTTP ProtocolStandardized "way of communicating"
KitchenServerProcesses requests based on "orders"
Serving FoodResponseReturns results to the "guest"

3. HTTP Methods: Are You "Asking" or "Doing"?

When calling a Web API, you need to tell the server what you want to do. That's where HTTP methods come in.

3.1 Restaurant Ordering Analogy

ScenarioWhat would you say in real life?HTTP Method
You want to see today's menu"Waiter, let me see the menu"GET - Pure "asking", doesn't modify data
You want to order Kung Pao Chicken"I'll have the Kung Pao Chicken"POST - "Doing" something, creates data
You want to change your dish"Change Kung Pao Chicken to Sweet and Sour Pork"PUT - Replace data
You want to change the flavor"No peanuts in the Kung Pao Chicken"PATCH - Partial modification
You don't want it anymore"Never mind, cancel that dish"DELETE - Delete data
get
Read
Query data
Idempotent
post
Create
Add data
Not idempotent
put
Full update
Replace resource
Idempotent
patch
Partial update
Modify fields
Not idempotent
delete
Delete
Remove resource
Idempotent
getRead - Query data
Fetch resources from the server without changing data
Restaurant analogy:"Waiter, show me the menu"
GET /api/users           # fetch user list
GET /api/users/123       # fetch one user
GET /api/products?cat=phone  # query phone products

About Idempotency

Idempotency: Do multiple executions produce the same result?

  • Idempotent operations (GET/PUT/DELETE): Clicking 10 times produces the same result as clicking once
  • Non-idempotent operations (POST): Clicking 10 times might create 10 orders

Solution: Use unique IDs for POST operations to prevent duplicate processing.

3.2 HTTP Methods Quick Reference

MethodPurposeIdempotentSafeTypical Scenario
GETRetrieve resourceYesYesQuery lists, view details
POSTCreate resourceNoNoAdd user, submit order
PUTFull updateYesNoReplace entire user profile
PATCHPartial updateNoNoOnly modify nickname
DELETEDelete resourceYesNoDelete user, cancel order

4. HTTP Status Codes: What Is the Server Telling You?

When the server responds, it first returns a status code telling you whether the request was successful.

4.1 Status Code Categories

2xxSuccess
The request was received, understood, and processed successfully
200 OK201 Created204 No Content
3xxRedirect
More action is needed to complete the request
301 Moved Permanently304 Not Modified307 Temporary Redirect
4xxClient error
The request has an error or cannot be completed
400 Bad Request401 Unauthorized403 Forbidden404 Not Found
5xxServer error
The server failed to handle a valid request
500 Internal Error502 Bad Gateway503 Unavailable
💡Memory tip:2️⃣ Success3️⃣ Redirect4️⃣ Client error5️⃣ Server error

4.2 Common Status Codes Explained

Status CodeMeaningTypical ScenarioClient Handling
200 OKSuccessRequest processed normallyDisplay data
201 CreatedCreated successfullyPOST request successfully created resourceRedirect to new resource
400 Bad RequestRequest format errorMissing or malformed parametersCheck parameters
401 UnauthorizedUnauthenticatedNo valid API Key providedGuide user to login
403 ForbiddenNo permissionAPI Key doesn't have access to this resourceShow insufficient permissions
404 Not FoundNot foundRequested address or resource doesn't existCheck URL
429 Too Many RequestsToo many requestsExceeded rate limitRetry later
500 Internal Server ErrorServer errorServer-side problemTell user to retry later

👇 Try it out: Click the button below to learn about common status codes:

HTTP Status Code Demo
// Click a button to inspect status code meanings
>
2xx Success
200OKRequest succeeded
201CreatedResource created
204No ContentSucceeded with no response body
⚠️4xx Client errors
400Bad RequestMalformed request
401UnauthorizedNot authenticated
403ForbiddenNo permission
404Not FoundResource missing
422UnprocessableSemantic validation error
429Too ManyToo many requests
🔴5xx Server errors
500Server ErrorInternal server error
502Bad GatewayGateway error
503UnavailableService unavailable
💡 Click a command button to learn common HTTP status codes.

5. HTTP vs SDK: Run Errands Yourself or Let the Butler Handle It?

5.1 Two Calling Methods Compared

🏃 HTTP API🤵 SDK
AnalogyRunning errands yourselfButler handles it
Pros✓ Works with any language
✓ Full control over request details
✓ No additional dependencies
✓ Clean, readable code
✓ Automatic authentication
✓ Built-in error retry
Cons✗ Need to handle all details
✗ Verbose and error-prone code
✗ Need to install dependencies
✗ May have version issues
Code Examplerequests.post(url, json=..., headers={...})client.chat.completions.create(...)

5.2 How to Choose?

ScenarioRecommended ApproachReason
Rapid developmentSDKHandles authentication, errors, and retries automatically
Learning principlesHTTPUnderstand underlying mechanisms
Unsupported languageHTTPWorks with any language
Need customizationHTTPFlexible control over every detail

💡 Recommendation

Use SDK when available. Leave the hassle to the library, save time for yourself.


6. How to Read API Documentation?

API documentation is like a combination of a manual and a menu. You don't need to read it cover to cover — just learn how to "look things up in a dictionary."

6.1 Documentation Reading Checklist

Open any API documentation (like OpenAI or DeepSeek), and you only need to find these things:

📖API Document Translator
Base URL
https://api.deepseek.com
Endpoint
POST /v1/chat/completions
Headers
Authorization: Bearer sk-xxx
Content-Type: application/json
Body parameters
modelRequiredModel name
messagesRequiredConversation messages
temperatureOptional0-2, default 1
Translate into code
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://api.deepseek.com"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Hello"}]
)
Core idea:When reading docs, find three things: address (Base URL), authentication (Authorization), and parameters.
ItemDescriptionExample
Base URLRoot address of the APIhttps://api.deepseek.com
AuthenticationHow to prove your identityAuthorization: Bearer sk-xxx
EndpointsSpecific endpoint list/v1/chat/completions
ParametersRequired/optional parametersmodel (required), temperature (optional)
ResponseReturn data structure{"choices": [...]}

6.2 Steps to Read Documentation

  1. Find the Base URL - This is the prefix for all requests
  2. Understand the authentication method - Is the API Key in the Header or Query?
  3. Find the Endpoint you need - The specific endpoint you want to call
  4. Check request parameters - Which are required? Which are optional?
  5. Understand the response format - How is the data organized?

7. Hands-on Practice: Simulate API Calls

Practice makes perfect. Here's a simulated API where you can fill in any parameters and change any address to see what happens.

🧪API PlaygroundTry calls without touching a real server
Send a request to see the response
Quick tries:

Try triggering these scenarios:

  • Successful request: Enter the correct Endpoint and API Key
  • 401 Error: Don't enter an API Key and see how the server rejects you
  • 404 Error: Enter a non-existent address

8. Summary

Key Takeaways

  1. APIs are like megaphones, helping you pass messages to other code or remote servers
  2. You've already used APIs, from len() to open(), they're all APIs
  3. Web APIs are superpowers, letting you call supercomputers thousands of miles away
  4. SDKs are good butlers, use SDKs when available instead of running errands yourself
  5. Look for three things in documentation: address, authentication, and parameters

In the era of AI programming, you only need to remember these core concepts. The rest of the details will be handled by your IDE and AI assistant.


Glossary

TermFull NameExplanation
APIApplication Programming InterfaceApplication programming interface, defines how software interacts
Web API-HTTP-based API for network communication
Endpoint-Endpoint, the specific address of an API
HTTPHyperText Transfer ProtocolCommunication protocol used by Web APIs
GET-Method for retrieving resources
POST-Method for submitting data
SDKSoftware Development KitSoftware development kit that wraps underlying API calls
URLUniform Resource LocatorNetwork address of an API
JSONJavaScript Object NotationCommonly used data format
Authentication-Process of verifying identity
Status Code-Status code in HTTP responses
Request-Request
Response-Response
Header-HTTP header containing metadata
Payload-Actual data in a request or response
Rate Limit-Rate limiting
Idempotent-Idempotent, multiple executions produce the same result
RESTRepresentational State TransferAn API architectural style
RPCRemote Procedure CallRemote procedure call
GraphQL-A query language API
gRPC-High-performance RPC framework developed by Google