Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

APIs and JSON Explained: REST, HTTP and Calling an API

5 min read Updated By the SkillNewton team

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-Type or Authorization.
  • 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

MethodPurposeExample
GETRead a resource; must not change dataGET /courses/7
POSTCreate a resource or trigger an actionPOST /courses with a JSON body
PUTReplace a resource completelyPUT /courses/7
PATCHUpdate part of a resourcePATCH /courses/7 with only changed fields
DELETERemove a resourceDELETE /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.

CodeMeaning
200 OKRequest succeeded and the body holds the result
201 CreatedA new resource was created, often with its URL in the Location header
204 No ContentSuccess with no body, common after DELETE
400 Bad RequestThe request was malformed or failed validation
401 Unauthorized / 403 ForbiddenMissing or invalid credentials / authenticated but not allowed
404 Not FoundThe resource does not exist
429 Too Many RequestsYou hit the rate limit
500 / 503Server 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 string

In 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 .env file 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

  1. Use curl with -i to fetch https://api.github.com/users/octocat and note the status code and any rate-limit headers.
  2. Write a Python function get_user(username) using requests with a timeout that returns the name, public repo count and creation date.
  3. Handle a 404 for a username that does not exist by returning None instead of crashing.
  4. Save the results for three users to users.json with json.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.

Want to Learn This Properly?

The Advanced PHP Web Development & Full-Stack Application Development (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.