Menu

Working with APIs

8. Working with APIs

a. What is an API?

An API (Application Programming Interface) is a way for two pieces of software to talk to each other. You can think of it as a menu in a restaurant: it tells you what you can ask for and how to ask, without showing how the kitchen works.

In web development, APIs often expose endpoints (URLs) that allow you to fetch or send data. For example, a weather API can give you the current temperature if you call it with the correct request.

APIs help developers reuse existing services instead of building everything from scratch. They are a core part of modern web, mobile, and backend applications.

b. Sending Requests

To use a web API, your program sends an HTTP request. This request includes:

  • A method (like GET, POST, PUT, DELETE)
  • A URL (the endpoint)
  • Optional headers and body data

A GET request usually asks for data, while POST sends new data to the server. Depending on the API, you may need to include an API key or token for authentication.

Libraries in most languages make sending requests easier by handling the underlying details. You usually call a function, pass the URL and options, and get a response object back.

c. Handling Responses

When the server receives your request, it sends back a response that includes:

  • A status code (like 200 for success, 404 for not found)
  • Headers (metadata about the response)
  • A body (often JSON or another format)

Your program must check the status code to decide what to do. If the code indicates success, you can parse the body and use the data. If it indicates an error, you may log it, retry, or show a message.

Handling responses well means not assuming everything worked. You always check codes and handle edge cases, like rate limits or invalid inputs.

d. Parsing JSON Data

JSON (JavaScript Object Notation) is a common data format used in APIs. It represents data as nested objects and arrays, which map naturally to dictionaries and lists in many languages.

When you receive a JSON response, you usually:

  • Convert the JSON string into native data structures
  • Access fields by key or index
  • Map the data into your own models or variables

Being comfortable with JSON is essential for working with modern APIs. It allows you to navigate complex responses like user profiles, lists of products, or nested configuration data.

REST-style API vs Simple HTTP Endpoint (Concept)

Aspect

REST-style API

Simple HTTP Endpoint

StructureOrganized around resources (e.g., /users)May be a single custom endpoint
MethodsUses standard methods (GET, POST, etc.)May use fewer conventions
Data formatCommonly JSONCould be JSON, XML, or plain text
Usage patternDesigned for general reuseOften built for a specific purpose