A Beginner’s Guide to Using APIs: How to Get Started

If you’re new to development, you’ve probably encountered the term API (Application Programming Interface). APIs are like a bridge, allowing different software applications to communicate with each other. However, if you’ve taken a look at API documentation, it can feel like you’re reading a foreign language!

This guide will break things down for you, explain how to approach API documentation, and provide simple examples in PHP and JavaScript to get you started.

What is an API?

Think of an API as a waiter in a restaurant. You (the client) tell the waiter what food you want, and the waiter (API) delivers your request to the kitchen (server). The kitchen (server) prepares your food (data) and the waiter brings it back to you.

In technical terms:

  • Client: Your application or code.
  • Server: The place that stores the data.
  • API: The intermediary system that delivers your request to the server and brings the response back to you.

API Architectures: REST vs SOAP

Before diving into examples, it’s important to understand two common types of API architectures: REST and SOAP. Most modern APIs use REST, but some older systems use SOAP.

REST (Representational State Transfer)

REST APIs follow a set of architectural principles, such as stateless communication and the use of standard HTTP methods like GET and POST. RESTful APIs are widely used because they are lightweight, scalable, and work over HTTP, which makes them ideal for web services.

Here’s what RESTful APIs commonly use:

  • GET to retrieve data.
  • POST to send or create data.
  • PUT to update existing data.
  • DELETE to remove data.

REST APIs usually return data in JSON format, which we’ll explain shortly.

SOAP (Simple Object Access Protocol)

SOAP is an older protocol that relies on XML for exchanging information between client and server. It’s more rigid and heavyweight compared to REST. SOAP has built-in error handling and is often used in enterprise-level services that require high security or complex transactions, like financial services.

Here’s what SOAP typically uses:

  • WSDL (Web Services Description Language) to define services and operations.
  • XML for formatting the request and response messages.

In general, unless you’re dealing with legacy systems, you’ll most likely work with REST APIs in your development.

Understanding API Documentation

API documentation often includes methods like GET and POST with very little explanation on how to use them. Let’s demystify this.

  • GET: Use this method when you want to retrieve data from the server.
  • POST: Use this method to send data to the server (like submitting a form).

Here’s an example from typical API documentation:


GET https://api.example.com/users
POST https://api.example.com/users
    

This means:

  • You’d use GET to fetch user data.
  • You’d use POST to send new user information.

When interacting with an API, you’ll usually:

  1. Make a request to a specific endpoint (e.g., /users).
  2. Send data (if needed) as part of the request.
  3. Receive a response, usually in JSON format.

What is JSON?

When you make a request to an API, the server typically responds with data in JSON format. JSON stands for JavaScript Object Notation. It’s a lightweight, easy-to-read data format that’s used to structure data. It’s the standard format for exchanging data between a server and a client.

Here’s what JSON looks like:


{
  "name": "John Doe",
  "email": "john@example.com",
  "age": 30
}
    

JSON is structured as:

  • Key-value pairs: Each piece of data has a key (e.g., "name") and a corresponding value (e.g., "John Doe").
  • Arrays: Collections of data, like lists (e.g., [1, 2, 3]).
  • Objects: Nested key-value pairs (e.g., another JSON object inside the current one).

JSON is widely used because it’s simple and works well with JavaScript. It’s also easy to convert between JSON and objects in most programming languages.

Using an API: Simple PHP and JavaScript Examples

PHP Example: Using GET to Fetch Data


<?php
// The API URL
$api_url = "https://api.example.com/users";

// Get the data
$response = file_get_contents($api_url);

// Decode the JSON response into an associative array
$data = json_decode($response, true);

// Output the data
print_r($data);
?>
    

Explanation:

  • file_get_contents() sends a GET request to the API URL.
  • The response is in JSON format, which we decode into an array using json_decode() so it’s easy to work with in PHP.
  • The data is then displayed using print_r().

JavaScript Example: Fetching Data with fetch()


<script>
// The API URL
const apiUrl = "https://api.example.com/users";

// Use fetch to get the data
fetch(apiUrl)
  .then(response => response.json()) // Parse JSON response
  .then(data => {
    console.log(data); // Log the data to the console
  })
  .catch(error => {
    console.error("Error:", error); // Handle errors
  });
</script>
    

Explanation:

  • fetch() sends a GET request to the API URL.
  • The response is converted to JSON using .json().
  • We log the data to the console for inspection.

Sending Data with a POST Request

Let’s see how you can send data using POST requests in both PHP and JavaScript.

PHP Example: Using POST to Send Data


<?php
// The API URL
$api_url = "https://api.example.com/users";

// The data to send
$data = array("name" => "John Doe", "email" => "john@example.com");

// Use cURL to send the POST request
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

// Get the response
$response = curl_exec($ch);
curl_close($ch);

// Output the response
echo $response;
?>
    

Explanation:

  • curl_setopt() is used to configure the cURL request to send a POST request with data.
  • The data is encoded into a query string using http_build_query().

JavaScript Example: Sending Data with POST


<script>
// The API URL
const apiUrl = "https://api.example.com/users";

// The data to send
const data = {
  name: "John Doe",
  email: "john@example.com"
};

// Send the POST request
fetch(apiUrl, {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(data) // Convert the data to JSON format
})
  .then(response => response.json()) // Parse the JSON response
  .then(data => {
    console.log("Success:", data);
  })
  .catch(error => {
    console.error("Error:", error);
  });
</script>
    

Explanation:

  • fetch() is used to send a POST request with data.
  • The data is converted to JSON format using JSON.stringify() and sent in the request body.
  • The server’s response is then logged to the console.

Conclusion

APIs are powerful tools that allow applications to communicate and share data. While API documentation can be confusing at first, once you understand the basics of making GET and POST requests, reading JSON data, and how to send data, you’ll be able to integrate with most APIs. Start small with simple API calls in PHP or JavaScript, and over time, you’ll be ready to tackle more complex API projects!

Get In Touch With Matt and the Team

Further Reading