APIs and JSON Explained: REST, HTTP and Calling an API
What is an API?
An API (application programming interface) is a defined way for one program to request data or actions from another. On the web, most APIs follow REST conventions: a client sends an HTTP request to a URL called an endpoint, and the server replies with a status code and data, usually formatted as JSON, a lightweight text format for structured data.
Key terms: endpoint, request, response and JSON
- Client: the program making the request, such as a Python script, a browser or a mobile app.
- Server: the program that receives the request and sends a response.
- Endpoint: a URL that represents a resource, such as
/users/42. - Headers: extra information sent with a request or response, such as
Content-TypeorAuthorization. - Body (payload): the data sent with a request or returned in a response.
- REST: an architectural style where resources are identified by URLs and manipulated with standard HTTP methods.
How REST uses HTTP methods and status codes
| Method | Purpose | Example |
|---|---|---|
| GET | Read a resource; must not change data | GET /courses/7 |
| POST | Create a resource or trigger an action | POST /courses with a JSON body |
| PUT | Replace a resource completely | PUT /courses/7 |
| PATCH | Update part of a resource | PATCH /courses/7 with only changed fields |
| DELETE | Remove a resource | DELETE /courses/7 |
The status code tells the client what happened before it reads the body. Codes in the 2xx range mean success, 4xx means the client made a mistake and 5xx means the server failed.
| Code | Meaning |
|---|---|
| 200 OK | Request succeeded and the body holds the result |
| 201 Created | A new resource was created, often with its URL in the Location header |
| 204 No Content | Success with no body, common after DELETE |
| 400 Bad Request | The request was malformed or failed validation |
| 401 Unauthorized / 403 Forbidden | Missing or invalid credentials / authenticated but not allowed |
| 404 Not Found | The resource does not exist |
| 429 Too Many Requests | You hit the rate limit |
| 500 / 503 | Server error / service temporarily unavailable |
The JSON format and its rules
JSON (JavaScript Object Notation, RFC 8259) supports six value types: objects in braces, arrays in square brackets, strings in double quotes, numbers, true/false and null. Keys must be double-quoted strings, and JSON allows no comments and no trailing commas.
{
"id": 7,
"title": "PHP Foundation",
"online": true,
"tags": ["php", "mysql"],
"mentor": null
}import json
course = json.loads('{"id": 7, "tags": ["php", "mysql"], "mentor": null}')
print(course["tags"][0], course["mentor"]) # php None
print(json.dumps(course, indent=2)) # back to a JSON stringIn PHP, json_decode($text, true, flags: JSON_THROW_ON_ERROR) returns an associative array and throws a JsonException on invalid input, and json_encode() goes the other way. The JSON guide for web developers covers parsing in JavaScript.
Calling an API with curl
curl ships with Windows 10 and later, macOS and most Linux distributions, which makes it the quickest way to try an endpoint. GitHub's public API is used below; httpbin.org simply echoes back what you send.
# GET a public resource; -s hides progress, -i shows status and headers
curl -s -i https://api.github.com/repos/python/cpython
# POST JSON and see it echoed back
curl -s -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-d '{"name": "Asha", "course": "php"}'On Windows PowerShell, call curl.exe rather than curl, and quote JSON carefully. To understand the HTTP layer underneath, read our guide to how web APIs work.
Calling an API from Python with requests and urllib
The third-party requests library (pip install requests) is the usual choice. Always set a timeout and check the status before reading the body.
import requests
response = requests.get(
"https://api.github.com/repos/python/cpython",
headers={"Accept": "application/vnd.github+json"},
timeout=10,
)
response.raise_for_status() # raises HTTPError for 4xx and 5xx
repo = response.json()
print(repo["full_name"], repo["default_branch"])
created = requests.post("https://httpbin.org/post", json={"name": "Asha"}, timeout=10)
print(created.status_code, created.json()["json"]) # 200 {'name': 'Asha'}With no extra packages, the standard library's urllib.request does the same job:
import json
from urllib.request import Request, urlopen
req = Request(
"https://api.github.com/repos/python/cpython",
headers={"Accept": "application/vnd.github+json"},
)
with urlopen(req, timeout=10) as resp: # raises HTTPError on 4xx and 5xx
repo = json.load(resp)
print(repo["full_name"]) Handling API keys and rate limits safely
- Store keys in environment variables or a
.envfile listed in.gitignore, never in source code or a commit. - Send keys in a header such as
Authorization: Bearer ...rather than in the URL, where they end up in server logs and browser history. - Never put a secret key in front-end JavaScript; call the API from your server instead.
- Give each key the narrowest permissions the provider allows, and revoke and replace any key that leaks.
import os
import time
import requests
API_KEY = os.environ["WEATHER_API_KEY"] # set outside the code
URL = "https://api.example.com/v1/forecast" # placeholder endpoint
def get_forecast(city: str, attempts: int = 4) -> dict:
for attempt in range(attempts):
response = requests.get(
URL,
params={"city": city},
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10,
)
if response.status_code != 429:
response.raise_for_status()
return response.json()
retry_after = response.headers.get("Retry-After", "")
time.sleep(int(retry_after) if retry_after.isdigit() else 2 ** attempt)
raise RuntimeError("Still rate limited; try again later")Rate limits cap how many requests you may send in a period. Respect the Retry-After header when present, back off exponentially otherwise, and cache responses that rarely change. Building your own endpoints is covered in REST API development.
Practical exercise: build a small API client
- Use curl with
-ito fetchhttps://api.github.com/users/octocatand note the status code and any rate-limit headers. - Write a Python function
get_user(username)usingrequestswith a timeout that returns the name, public repo count and creation date. - Handle a 404 for a username that does not exist by returning
Noneinstead of crashing. - Save the results for three users to
users.jsonwithjson.dump(..., indent=2), then load the file back and print it.
You are done when the script handles a missing user cleanly and the JSON file is valid. The Advanced PHP course covers consuming and building APIs in PHP.
Common mistakes
- Calling an API without a timeout, so a slow server hangs your program indefinitely.
- Reading the JSON body without checking the status code first.
- Committing API keys to Git or placing them in front-end JavaScript where anyone can read them.
- Retrying immediately in a tight loop after a 429 response, which extends the block.
- Writing JSON by hand with single quotes or trailing commas, which parsers reject.
Frequently asked questions
Is REST the same as an API?
No. An API is any defined interface between programs. REST is one style for web APIs; others include GraphQL, gRPC and SOAP.
What is the difference between JSON and a Python dictionary?
JSON is text in a standard format; a dictionary is an in-memory Python object. json.loads() converts text to Python objects and json.dumps() converts back. JSON uses true, false and null where Python uses True, False and None.
How do I call an API from JavaScript in the browser?
Use the fetch() function with async/await, as shown in our Fetch API guide. The server must allow cross-origin requests through CORS headers.