API Basics

How to use an API

APIs enable software teams to build advanced applications, connect their systems with internal and external services, and integrate with other solutions to enhance their capabilities. This article will discuss four methods of using an API: through a programming language, through an HTTP client, through a browser, and a terminal.

Written by Arman
Published On Mon Jun 14 2021
Last Updated Fri Feb 09 2024

Introduction

APIs are crucial for modern software development as they enable the exchange of data and functionality between different systems and services. With APIs, developers can use existing platforms’ capabilities without creating complex functionalities from scratch. APIs have become the preferred method for achieving compatibility between various digital technologies.

Understanding API Types and Architectures

Types of APIs

  • Public APIs: Open to developers and companies, allowing access to third-party services.
  • Private APIs: Restricted to internal use, enhancing productivity and collaboration within organizations.
  • Partner APIs: Shared between business partners, enabling integration of external services.
API TypeUse Cases
PublicSocial media integration, payment gateways
PrivateInternal data sharing, microservices
PartnerSupply chain management, B2B integrations

Architectural Styles

  • REST (Representational State Transfer): Leverages standard HTTP methods and is known for simplicity and scalability.
  • SOAP (Simple Object Access Protocol): Uses XML for message format, ensuring high levels of security and standardization.
  • GraphQL: Allows clients to request the exact data they need, providing efficiency and flexibility.
  • Webhooks: Enables applications to receive real-time information updates from other services automatically.
  • gRPC: Developed by Google, it uses HTTP/2 for transport, enabling streaming and fast communication.

Setting Up Your Development Environment

Selecting the right tools and understanding API documentation are crucial first steps in API integration. Tools like Testfully and Postman not only facilitate testing but also offer environments to simulate and debug API requests and responses effectively.

Making Your First API Request

Here’s a diagram illustrating the API request-response cycle, from initiating a request using HTTP methods (GET, POST, PUT, DELETE) to receiving a response from the server:

A diagram illustrating the API request-response cycle

Making your first API request is foundational in understanding how APIs work. This process typically involves:

  1. Choosing an Endpoint: An endpoint is a specific URL representing an API’s function. For example, an endpoint might provide the current weather conditions for a specific location if you’re using a weather API.
  2. Selecting an HTTP Method: The common HTTP methods are GET (retrieve data), POST (submit data), PUT (update data), and DELETE (remove data). The method you choose depends on what you want to do.
  3. Adding Parameters and Headers: Parameters specify the data you want to request or submit. Headers can provide additional information about the request, such as content type or authentication tokens.
  4. Sending the Request: You can send your API request to the endpoint using tools like Postman or programming languages such as Python with libraries like requests.
  5. Receiving the Response: The API will respond with data (typically in JSON or XML format) and HTTP status codes showing the success or failure of your request.

Handling Responses and Errors

Understanding how to handle API responses and errors is crucial for developing resilient applications.

  • Interpreting HTTP Status Codes: When making an API request, a response is received with a status code. When the code falls within the 200 range, the request is successful. If the code is in the 400 range, it indicates a client error (e.g., 404 for “Not Found”). On the other hand, if the code is in the 500 range, it means there was a server error.
  • Parsing the Response Body: Successful requests return data in a structured format, commonly JSON. You’ll need to parse this data to use it in your application.
  • Error Handling: It’s essential to implement error handling to manage issues like network problems, invalid responses, or rate limiting. Error handling might involve retrying requests, logging errors, or providing users with helpful feedback.

Authenticating Your Requests

API authentication is a mechanism to ensure that only authorized users can access the API. Common methods include:

  • API Keys: A simple token passed along with the request, often in the header.
  • OAuth: A more secure method that provides tokens after a user or application is authenticated, suitable for scenarios where you need to access user data without exposing their credentials.
  • JWT (JSON Web Tokens): A compact, URL-safe method for transferring claims between parties, commonly used in single sign-on (SSO) scenarios.

Use APIs via a Programming Language

Using an API via a programming language involves making HTTP requests to the API’s endpoints and handling the responses. This goal can be achieved through various libraries or frameworks specific to your programming language. For example:

  • Python has libraries like requests for making HTTP calls and handling responses.
  • Ruby users might leverage Net::HTTP or the rest-client gem for similar purposes.
  • Java developers can use the HttpClient class from the Java.net package or external libraries like OkHttp.

The general steps to use an API in a programming language are:

  1. Import the necessary libraries: Include the libraries or modules allowing your program to make HTTP requests.
  2. Set up the API request: This involves specifying the endpoint URL, the HTTP method (GET, POST, PUT, DELETE), and any headers or parameters the API requires.
  3. Make the request: Use the functions provided by the library to send the request to the API.
  4. Handle the response: The API will send back a response, which your program will need to parse and process. This step often involves converting from JSON or XML format into the native data structures of your programming language.

Here’s how you can use Axios in JavaScript to fetch data from the Rick and Morty API:

const axios = require("axios");

axios
  .get("https://rickandmortyapi.com/api/character/")
  .then(function (response) {
    // Handle success
    console.log(response.data);
  })
  .catch(function (error) {
    // Handle error
    console.log(error);
  });

This code snippet retrieves a list of characters from the Rick and Morty series. Axios automatically parses the JSON response, making the data easily accessible within the .then callback.

Use APIs via an HTTP Client

HTTP clients like Postman are tools designed to simplify making HTTP requests to APIs without writing any code. They are instrumental in testing and debugging API endpoints. Using Postman, you can send a request to the Rick and Morty API by:

  1. Opening Postman and creating a new request.
  2. Setting the HTTP method to GET.
  3. Entering the URL https://rickandmortyapi.com/api/character/.
  4. Hitting send to view the response.

Postman displays both the request and the parsed response, allowing easy inspection and troubleshooting.

Postman app

Use APIs via Command-line

The command line or terminal provides a direct way to make API calls using tools like curl. It’s a powerful method many developers prefer for its speed and simplicity. Here’s a curl command to fetch the first page of characters from the Rick and Morty API:

curl -X GET "https://rickandmortyapi.com/api/character/"

Executing this command in your terminal will return a JSON response with data about the characters, which you can then process as needed.

Use APIs via browser console

You can use the JavaScript fetch API to make an HTTP request from the browser console. Here’s a step-by-step guide on how to do it:

  1. Open the Browser Console: Begin by opening your browser’s developer tools by right-clicking on any part of a webpage and choosing “Inspect” or “Inspect Element.” Then, proceed to the “Console” tab. Alternatively, you can use keyboard shortcuts in Chrome and Firefox, such as Ctrl+Shift+J (or Cmd+Option+J on Mac).
  2. Use the fetch Function: In the console, you can make a simple HTTP GET request using the fetch function. For example, to request data from the Rick and Morty API, you would enter:
fetch("https://rickandmortyapi.com/api/character/")
  .then((response) => response.json())
  .then((data) => console.log(data));

This code snippet sends a GET request to the specified URL, parses the JSON response, and logs it to the console.

The following result will be printed for you:

use API via browser console

  1. Handling Responses: The fetch function returns a Promise that resolves to the Response object representing the response to your request. You can use the .then() method to handle the response. The first .then() call is used to read and parse the response as JSON with response.json(). The second .then() call receives the parsed data.
  2. Error Handling: To catch any errors that occur during the fetch operation, you can chain a .catch() method at the end of your fetch calls:
fetch("https://rickandmortyapi.com/api/character/")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));
  1. Making POST Requests: If you want to make a POST request (or other types of requests like PUT, DELETE, etc.), you need to add an options object parameter to the fetch call, specifying the method and body of your request:
fetch("https://example.com/api/data", {
  method: "POST", // or 'PUT'
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    key: "value",
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

This method lets you interact with APIs directly from your browser, making it a helpful tool for testing, debugging, and learning about web APIs.

Remember, while the browser console is a powerful tool for making API requests, it’s primarily used for development and debugging. For production applications, you’ll integrate API requests within your application’s codebase using JavaScript or other programming languages.

Conclusion

APIs are crucial in modern software development as they offer countless possibilities to enhance and extend application functionalities. You can easily use an API by following the guidelines outlined in this blog post.

Comments, Questions, or Feedback? Post it here!

0 comments

Testfully is a bootstrapped startup from Sydney, Australia.
We're funded by our supportive & amazing customers.

The word `testfully` is a registered trademark of Testfully Pty Ltd.