How to Make API Calls Using Python
Use Python to call a REST API directly with requests, verify what came back, and switch to a generated or official SDK when hand-written HTTP becomes repetitive. The workflow below uses an OpenAI chat completion as the concrete example, then shows how the same pattern applies to any documented API.
HTTP API Call vs Plain HTTP Call
An HTTP exchange is transport-level communication: the verb hints at intent, but payload shape is up to the parties. A REST API adds a documented contract on top, usually returning structured JSON, which makes integration predictable across services. In practice, 'API call' usually means a request to such a REST endpoint.
Set Up the Environment
Install Python and obtain an API key from the provider you intend to call. A virtual environment keeps interpreter and package versions isolated: create it with module code0001, activate it with module code0002, and only then install dependencies.
Authenticating with an API
Most services gate access with a token so usage can be tracked and rate limits enforced. The common pattern sends an Authorization header whose value is Bearer followed by your key. Keep that secret out of source code: read it from an environment variable as in module code0003, or load it from a .env file using python-dotenv as in modules code0004 and code0005. The variable name must match what the provider expects.
Python example
import os
openapi_token = os.getenv("OPEN_AI_API_KEY")Issuing Your First API Call
A minimal call needs four ingredients: a URL, headers declaring content type and credentials, a JSON payload, and a verb. Module code0006 posts a chat request with a model name, a user message and a temperature setting. The returned object carries status, headers and body, so receiving a response is only the start of handling it.
Handling the Response
Treat status ranges as a first filter: 2xx means success, 4xx means the client request was wrong, and 5xx means the server failed. Module code0007 branches on response.ok for the 2xx case, prints client errors for 4xx, and falls back to raw text otherwise. Two captured failures illustrate the split: a 429 insufficient-quota body in module code0008 and a 401 invalid-key body in module code0009. A successful payload, shown in module code0010, buries the useful text under choices, so extract the specific message content field rather than dumping everything. One caution: some APIs return 200 despite failing, so always cross-check the body against the provider documentation.
Generating an SDK from OpenAPI
When a provider publishes an OpenAPI document, that machine-readable description can be turned into a client library. Module code0011 shows a small fictitious Task API specification with list, create, fetch and delete operations. Module code0012 generates a Python client from it with openapi-generator, and module code0013 calls the generated high-level methods instead of assembling HTTP by hand. The fictitious endpoint will not connect, but the generation pattern transfers directly to real specifications.
Leveraging an SDK
Official SDKs wrap endpoints, authentication and serialization behind methods named after the operations you want. Module code0014 uses the OpenAI Python SDK to create a chat completion and read back the reply text, without manually choosing an endpoint or building headers; the SDK also picks up the key from its expected environment variable. Decision rule: prefer an official SDK, generate one from OpenAPI when none exists, and reserve raw requests for small or one-off calls. For a branded scraping SDK example, configure {{OWNER_PACKAGE}} and {{OWNER_API_KEY}} once an owned package is available.
Pre-Flight Checklist
Checklist before you ship a Python API client: credentials come from the environment, not code; every response branch handles 2xx, 4xx and 5xx; the body is checked even on 200; rate-limit and invalid-key errors have distinct messages; and you have considered an official or generated SDK before hand-writing requests.
| Approach | Best for | Trade-off |
|---|---|---|
| Raw requests | One-off calls, learning, custom payloads | You own headers, serialization and error parsing |
| Official SDK | Repeated use of a supported API | Depends on provider maintenance and release cadence |
| Generated SDK | APIs with an OpenAPI document but no SDK | Generated code needs regeneration when the spec changes |
Choose based on whether an official SDK or OpenAPI document exists.
Frequently asked questions
What distinguishes an HTTP API call from a plain HTTP call?
A plain HTTP call can use any payload shape the two sides agree on, while a REST API call follows a documented structure for requests and responses, commonly JSON. The method still signals intent, but the API contract defines fields, errors and semantics.
Is a 200 status always a success?
Check the status range first, then inspect the body. Some services return 200 even for failures, so documentation and body error fields are the deciding evidence.
Should I use requests or an SDK?
Look for an official SDK first. If none exists but an OpenAPI document is published, generate a client from it instead of hand-writing every request.