An introduction to APIs

APIs in 8 minutes

An introduction to APIs

What is an API?

Imagine you are in a restaurant and a waiter approaches you to take your food order. You give the waiter your order and they go back to the kitchen and communicate your request to the chef. The waiter acts as a mediator between customer and the chef. The medium through which the requests, responses are communicated between the two parties.

Just like a waiter act as a go-between for customers and the chef in a restaurant, an API acts as a mediator between different software applications. When you use an app on your phone or computer, it might need information from another app or service, like fetching the latest weather forecast or getting your social media updates.

A formal definition for API

A set of rules and protocols that allows different software applications to communicate with each other. APIs define how software components should interact, making it easier to integrate different systems and services.

Types of APIs

Now, we know that there are different types of staff in a restaurant and each role has different responsibilities. Similarly, there are different types of APIs that perform specific functions.

Here is a list of the different types of APIs:

  1. Web APIs: Let's imagine you're in a fancy restaurant where they offer delivery services. Just like you can call the restaurant and place an order for delivery, web APIs are like the phone lines that connect different apps and services over the internet. They enable developers to interact with web services, just like customers interact with the restaurant to order food. So, when you use a weather app on your phone to check the forecast, it's like calling a weather API over the internet to get the latest weather information.

    These are APIs that are accessed over the internet using HTTP requests. They enable developers to interact with the web services and access their functionality such as retrieving data from a server or performing actions.

    When should we use Web APIs instead of RESTful or GraphQL APIs?

    We should only use Web APIs when we want our Apps to get information or do something with another app over the internet.

  2. RESTful APIs: Now, let's say you're dining in at a restaurant, and you want to order your favourite dish. RESTful APIs are like the menu in a restaurant that follows a certain structure and protocol. When you order from the menu, you're using the restaurant's predefined options to communicate your request. Similarly, RESTful APIs adhere to specific rules and guidelines known as REST principles. They use HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources, just like how you select items from the menu to place your order.

    Representational State Transfer (REST) is a software architectural style for building scalable web services. RESTful APIs adhere to REST principles and use HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources.

    When should we use RESTful APIs instead of Web APIs or GraphQL APIs?

    Use RESTful APIs when you're building a web service and want to make it easy for others to understand and use. It's like having a clear menu for ordering food.

  3. GraphQL APIs: Lastly, imagine you're at a buffet restaurant where you can customize your meal exactly the way you want it. GraphQL APIs are like a buffet where you can pick and choose exactly what you want to eat. Unlike traditional RESTful APIs where you get a fixed set of data, GraphQL allows clients (like your plate at the buffet) to specify exactly what data they need. It's like being able to ask the chef directly for the specific ingredients you want in your dish, instead of getting a pre-made meal. This reduces over-fetching (getting more data than you need) or under-fetching (not getting enough data) of information, making the dining experience more efficient and enjoyable.

    GraphQL is a query language and runtime for APIs developed by Facebook. It allows clients to specify the exact data they need, enabling more efficient data fetching and reducing over-fetching or under-fetching of data.

    When should we use RESTful APIs instead of Web APIs or GraphQL APIs?

    Use GraphQL APIs when you need more flexibility and control over the data you fetch from the server.


Type of APIDefinitionUse case
Web APIAPIs that use the internet as a medium of communication.General purpose use. Whenever we want our applications to access information on or through the internet
RESTful APIAPIs that adhere to certain rules and regulations set by the provider.Used when building APIs for SAAS or to fetch data from providers that have set parameters on their data.
GraphQL APIAPIs that allow users to specify exactly the data they need.Build GraphQL APIs when we need very specific information from a source

Where are most likely to find APIs: Use Cases

  • Fetching Data: APIs are commonly used to retrieve data from external sources, such as weather data, stock prices, news articles, etc.

  • Authentication and Authorization: APIs often handle user authentication and authorization, allowing users to securely access and interact with protected resources.

  • Building Microservices: APIs are foundational for building microservices architectures, where different parts of an application are developed and deployed independently as small, loosely coupled services.

The structure of an API

HTTP methods.

First, what is HTTP?

HTTP stands for Hypertext Transferer Protocol. It is a protocol (a set of rules) used for transferring data over the web. Think of it as the language that web browsers and servers use to communicate with each other.

When you type a website address into your browser and hit enter, your browser sends an HTTP request to the server hosting that website asking for the page you want to see. The server then responds with the requested webpage and your browser displays it for your to see.

Now HTTP methods, also known as HTTP verbs, are actions that indicate what the client wants to do with a resource on the server. These methods specify the type of request being made and the action to be performed on the resource.

These are the different HTTP methods:

These are the most important:

  • GET: The GET method is used to request data from a specified source. It’s like asking the server to “get” or retrieve some information without changing anything on the server. Get requests are commonly used for fetching web pages, images, or other resources from a server.

    Here is an example in JavaScript:

fetch('/api/posts')
  .then(response => response.json())
  .then(data => {
    console.log('GET response:', data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });
  • POST: The POST method is used to submit data to be processed to a specified resource. It's like sending a package to the server with some data inside. POST requests are commonly used for submitting form data, uploading files, or creating new resources on the server.

    Here is an example in JavaScript:

const postData = {
  title: 'New Post',
  body: 'This is the content of the new post.'
};

fetch('/api/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(postData)
})
  .then(response => response.json())
  .then(data => {
    console.log('POST response:', data);
  })
  .catch(error => {
    console.error('Error creating new post:', error);
  });
  • PUT: The PUT method is used to update or replace an existing resource with new data. It's like updating a file on the server with a new version. PUT requests are commonly used for updating existing records or resources on the server.

    Here is an example in JavaScript:

const updatedData = {
  title: 'Updated Post Title',
  body: 'This is the updated content of the post.'
};

fetch('/api/posts/123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(updatedData)
})
  .then(response => response.json())
  .then(data => {
    console.log('PUT response:', data);
  })
  .catch(error => {
    console.error('Error updating post:', error);
  });
  • DELETE: The DELETE method is used to delete a specified resource from the server. It's like asking the server to "delete" or remove something. DELETE requests are commonly used for removing records or resources from a database or file system.

    Here is an example in JavaScript:

      fetch('/api/posts/123', {
        method: 'DELETE'
      })
        .then(response => {
          if (response.ok) {
            console.log('Post deleted successfully');
          } else {
            throw new Error('Failed to delete post');
          }
        })
        .catch(error => {
          console.error('Error deleting post:', error);
        });
    

    Data Serialisation

    What is Data Serialisation?

    The process of converting complex data structures or objects into a format that can be easily transmitted over a network or stored in a file. Similarly, deserialization is the process of converting serialized data back into its original format. Serialization is important in web development and APIs because it allows data to be transmitted between clients and servers in a standardized format.

    We usually use JSON for data serialization. Most programming languages have serialization methods to handle conversion of data to and from its serialized form.

    This is what data serialization would look like in a JavaScript:

      // Example JavaScript object
      const person = {
        name: 'John Doe',
        age: 30,
        city: 'New York'
      };
    
      // Serialize JavaScript object to JSON string
      const jsonString = JSON.stringify(person);
      console.log(jsonString);
      // Output: {"name":"John Doe","age":30,"city":"New York"}
    
      // Deserialize JSON string to JavaScript object
      const parsedObject = JSON.parse(jsonString);
      console.log(parsedObject);
      // Output: { name: 'John Doe', age: 30, city: 'New York' }
    

Endpoints

Endpoints are specific URLs within an API that represent resources or functionalities offered by the API. They support HTTP methods like GET, POST, PUT, and DELETE for performing actions on resources. Each endpoint has a URL structure and may require authentication and authorization. Responses from endpoints are typically in JSON or XML format and include data, metadata, and status codes.

Good API documentation provides detailed information about each endpoint, helping developers understand how to interact with the API effectively. Understanding endpoints is crucial for working with APIs, as they define the interface for accessing an API's functionality and resources.

So, in conclusion,

APIs serve as the vital communication channels between software applications, much like the interaction between a diner and a waiter in a restaurant. We've explored their types, from Web APIs for internet-based interactions to RESTful APIs following structured protocols, and GraphQL APIs offering tailored data retrieval.

Understanding the backbone of APIs, including HTTP methods, data serialization, and the pivotal role of endpoints, is essential for effective development. With this knowledge, we're better equipped to harness APIs' power in building interconnected systems and driving innovation in the digital landscape.

Now go build some APIs !