What an API Is, and Your First Integration
Understand what an API is and what integration means, read an API's documentation as a contract, call a shipping-rates API with a key and query parameters, and check the answer against the documented price formula and with curl.
In this lesson you will
- Explain what an API and an integration are
- Read an API description as a contract
- Make an authenticated GET with parameters
- Verify the response independently
About 28 minutes
Noor’s plant shop wants to stop doing things by hand
Noor sells houseplants online. Every order means three chores: asking a courier what delivery costs, taking a payment, and emailing the customer. She does them by hand, in three websites. An API, an application programming interface, is a way for one program to ask another to do something, using agreed rules. Many companies offer one: a courier lets your program ask for rates and book shipments, a payment provider lets it create charges, an email service lets it send messages. Integration means connecting your system to those services, so that an order triggers everything automatically.
Most web APIs work over HTTP and speak JSON, as you saw in the Back-end course. The provider publishes documentation that is a contract: the address of each endpoint, the method, the parameters, how to authenticate, what the response looks like, and the error codes. Your code must follow the contract exactly, and must also be ready for what the contract does not promise: slowness, outages, changes and mistakes. In this course the services are simulated by small programs on your own computer, so that every example runs and can be checked, but the rules are the same as for the real ones, and you must always read the current documentation of the real API you use.
| Part of the contract | Example (a simulated shipping API) |
|---|---|
| Base URL | https://shipping.example/v1 |
| Endpoint | GET /rates |
| Parameters | weight (grams), country (ISO code) |
| Authentication | Header X-Api-Key |
| Response | JSON: a list of rates |
| Errors | 401 bad key, 422 bad parameters |
import json, threading, urllib.request, urllib.parse, math, subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
API_KEY = "demo-key-123"
DAYS = {"DE": (2, 1), "FR": (3, 2), "US": (7, 3)}
class Shipping(BaseHTTPRequestHandler):
def reply(self, code, obj):
b = json.dumps(obj).encode()
self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b))); self.send_header("X-RateLimit-Limit", "60"); self.end_headers(); self.wfile.write(b)
def do_GET(self):
url = urllib.parse.urlparse(self.path); q = urllib.parse.parse_qs(url.query)
if url.path != "/v1/rates": return self.reply(404, {"error": "not_found"})
if self.headers.get("X-Api-Key") != API_KEY: return self.reply(401, {"error": "invalid_api_key"})
try:
grams = int(q["weight"][0]); country = q["country"][0]
assert grams > 0 and country in DAYS
except Exception:
return self.reply(422, {"error": "invalid_parameters"})
blocks = math.ceil(grams / 100)
std_days, exp_days = DAYS[country]
self.reply(200, {"currency": "EUR", "rates": [{"service": "standard", "price_cents": 450 + 12 * blocks, "days": std_days + 3}, {"service": "express", "price_cents": 900 + 30 * blocks, "days": exp_days}]})
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Shipping); base = "http://127.0.0.1:%d" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
def get_rates(grams, country, key=API_KEY):
req = urllib.request.Request(base + "/v1/rates?" + urllib.parse.urlencode({"weight": grams, "country": country}), headers={"X-Api-Key": key, "Accept": "application/json"})
try:
r = urllib.request.urlopen(req, timeout=5)
except urllib.error.HTTPError as e:
r = e
return r.status, r.headers.get("Content-Type"), r.headers.get("X-RateLimit-Limit"), json.loads(r.read())
status, ctype, limit, body = get_rates(1250, "DE")
print("status:", status, "| content type:", ctype, "| rate limit header:", limit)
for r in body["rates"]: print(" ", r["service"].ljust(9), "%.2f %s" % (r["price_cents"] / 100, body["currency"]), "in", r["days"], "days")
cheapest = min(body["rates"], key=lambda r: r["price_cents"])
print("cheapest:", cheapest["service"])
bad_key = get_rates(1250, "DE", key="wrong")
bad_args = get_rates(0, "XX")
print("wrong key ->", bad_key[0], bad_key[3], "| bad parameters ->", bad_args[0], bad_args[3])
out = subprocess.run(["curl", "-s", "-H", "X-Api-Key: " + API_KEY, base + "/v1/rates?weight=1250&country=DE"], capture_output=True, text=True).stdout
print("curl returns the same JSON:", json.loads(out) == body)
print("DATA " + json.dumps({"status": status, "body": body, "bad": [bad_key[0], bad_args[0]], "same": json.loads(out) == body}))
srv.shutdown()
status: 200 | content type: application/json | rate limit header: 60
standard 6.06 EUR in 5 days
express 12.90 EUR in 1 days
cheapest: standard
wrong key -> 401 {'error': 'invalid_api_key'} | bad parameters -> 422 {'error': 'invalid_parameters'}
curl returns the same JSON: True
The program starts a small simulated shipping API on a free local port and calls it, as it would call a real one. The request is a GET to /v1/rates with two query parameters, the weight in grams and the country, built with urlencode so that special characters are escaped correctly, and an X-Api-Key header that identifies the account. The reply has status 200 and a JSON body with a currency and a list of rates: standard at 6.06 euros in 5 days and express at 12.90 euros in 1 day. The server also sent a header, X-RateLimit-Limit, telling the client that it may make 60 requests per window, which lesson 5 will use.
The error cases are part of the contract too. A wrong key gets 401 with the body {“error”: “invalid_api_key”}, and a request with a weight of 0 and an unknown country gets 422. Notice that the Python code did not crash on these: urllib raises an exception for error statuses, and the client caught it and read the body from the exception, because the body of an error response explains what went wrong. An integration that only handles success is not finished.
Independent check: the prices were recomputed from the formula in the “documentation” that the simulated API follows: standard shipping is 450 cents plus 12 cents per started 100 grams, and 1,250 grams is 13 started hundreds, so 450 + 12 x 13 = 606. Express is 900 + 30 x 13 = 1290. Both match the response. A second client, curl, a separate program, sent the same request and got exactly the same JSON (True), so the answer does not depend on how the Python code builds the request.
Check by hand: 1,250 grams is 12.5 hundreds, which rounds up to 13 blocks. Standard is 450 + 12 x 13 = 606 cents, 6.06 euros, and express is 900 + 30 x 13 = 1,290 cents, 12.90 euros. The cheapest of the two is the standard service.
Anyone who can read the code can use the key, and it may end up in a public repository. Read keys from environment variables or a secrets manager, as lesson 3 and lesson 11 show.
Before you write the happy path, list the errors the API can return and decide what your code will do for each. The unhappy paths take more time than the happy one.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use.
Practice
Call the simulated API for 3,000 grams to the US and check the prices by hand. Send the key as a query parameter instead of a header and see what the server does. Write down, for each status code in the table, what your program should do.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is an API?
- A kind of database
- A way for one program to ask another to do something
- A web design tool
- A programming language
Using agreed rules.
What does the documentation of an API describe?
- The contract: endpoints, parameters, authentication, responses and errors
- Only the price
- The colour scheme
- The company history
Your code must follow it.
Why use urlencode for query parameters?
- It escapes special characters correctly
- It encrypts them
- It speeds up requests
- It adds a key
Never join them by hand.
Why read the body of an error response?
- It is empty
- It contains the key
- It is always HTML
- It explains what went wrong
Machine-readable errors.
Why verify with curl?
- curl is faster
- It is required
- It adds security
- A second client confirms the response
An independent check.
Summary
- An API lets programs ask other programs to do things under agreed rules.
- The documentation is a contract; follow it, and handle what it does not promise.
- Handle error responses as carefully as successes.
- Verify with an independent client such as curl.
Questions
Do I need to know a lot of programming to integrate an API?
Basic programming and an understanding of HTTP are enough to begin. The harder parts are error handling, security and testing, which this course covers.
What is the difference between an API and a website?
A website returns pages for people, and an API returns data for programs, usually JSON, in a predictable format.
Are all APIs REST?
No. REST over HTTP with JSON is the most common style. Others include GraphQL, gRPC and SOAP. Check the documentation of the service.
