APIs Unwrapped: 'A Beginner's Overview'

APIs Unwrapped: 'A Beginner's Overview'

·

12 min read

Introduction

Are you curious about APIs? You may have heard the term "API" thrown around in tech circles, but what does it really mean? API stands for Application Programming Interface, and it's a way for software applications to communicate with each other.

Don't worry if that sounds a bit technical. APIs are much simpler than they may seem. In this blog post, we'll take a high-level overview of the different types of APIs and how they work.

First, let's talk about why APIs are important. In today's interconnected world, software applications need to be able to share information with each other. For example, a mobile app may need to access data from a web service, or a website may need to integrate with a third-party payment gateway. This is where APIs come in.

There are many different types of APIs, including web APIs, operating system APIs, and database APIs. Web APIs are the most common, and they allow software applications to communicate over the internet. Operating system APIs, on the other hand, provide a way for applications to interact with the operating system of a device, such as a computer or mobile phone. Database APIs enable applications to interact with a database system, such as MySQL or MongoDB.

Now, let's talk about how APIs work. APIs provide a set of rules and protocols that govern how applications communicate with each other. These rules dictate what types of data can be sent and received, and how that data should be formatted. Essentially, APIs act as a bridge between different applications, allowing them to work together seamlessly.

Finally, let's put our new knowledge into action. In this blog post, we'll learn how to build our own API using Node.js, a popular server-side JavaScript platform. Don't worry if you're new to Node.js - we'll give you a brief overview in this post. By the end of this blog post, you'll have a solid understanding of what APIs are, how they work, and how to build your own. So let's get started!

Different API categories:

APIs can be categorized in different ways depending on their purpose, functionality, or implementation. Here are some common ways APIs are categorized:

  1. Based on the type of service they provide:

    • Web APIs: These are APIs that allow access to web-based services, such as social media platforms, weather data providers, or payment processing services. Web APIs are typically accessed over HTTP and use standard data formats such as JSON or XML to exchange data between the client and server. Web APIs can be used by developers to integrate the services provided by the API into their own applications or websites.

    • Mobile APIs: These are APIs that provide access to mobile device functionality, such as location tracking, camera, or sensors. Mobile APIs can be used by developers to create mobile applications that can interact with the device's hardware and provide a better user experience. Mobile APIs can also provide access to cloud-based services, such as push notifications or data storage.

  2. Based on the level of abstraction:

    • High-level APIs: These are APIs that provide a simplified, abstract interface to a complex system or functionality. High-level APIs are typically designed to be easy to use and understand and hide the complexity of the underlying system. High-level APIs can be used by developers who want to add specific functionality to their applications without having to deal with the underlying complexity. Some examples of high-level APIs are Google maps, stripe API, and Twilio API.

    • Low-level APIs: These are APIs that provide direct access to the underlying system or hardware, and require more technical knowledge and implementation. Low-level APIs are typically more flexible and powerful than high-level APIs, but they also require more effort to use and maintain. Low-level APIs can be used by developers who need fine-grained control over the system or hardware. Some examples are Win32 API (Microsoft Windows operating system), BIOS, and CUDA API.

  3. Based on the implementation:

    • REST APIs: These are APIs that use the REST (Representational State Transfer) architectural style, and follow a standard set of principles for data exchange and communication. REST APIs are typically accessed over HTTP, and use standard HTTP methods such as GET, POST, PUT, and DELETE to perform operations on resources. REST APIs use resource identifiers (URIs) to identify and manipulate resources, and use standard data formats such as JSON or XML to exchange data between the client and server.

    • SOAP APIs: These are APIs that use the SOAP (Simple Object Access Protocol) protocol for exchanging structured data between systems. SOAP APIs use XML to encode data, and have a strict message structure that includes a header and a body. SOAP APIs provide a standardized way of exchanging data between systems, but are more complex and heavyweight than REST APIs.

    • GraphQL APIs: These are APIs that use the GraphQL query language to provide a more flexible and efficient way of querying and retrieving data. GraphQL APIs allow clients to specify the data they need, and provide only the requested data in response. This reduces the amount of data transferred over the network and improves performance. GraphQL APIs can be used with any programming language or framework, and are often used in modern web applications.

  4. Based on ownership and usage:

    • Third-party APIs: These are APIs that are developed and maintained by a third-party service provider and are made available to other developers to integrate into their applications. Third-party APIs can provide a wide range of functionalities and services and can save developers time and effort by allowing them to reuse existing code and infrastructure.

    • Internal APIs: These are APIs that are developed and used within an organization to facilitate communication and data exchange between different systems or departments. Internal APIs can provide a way to standardize and streamline communication between different systems and can help to improve efficiency and collaboration within the organization. Internal APIs can be designed and developed to meet the specific needs of the organization.

The architecture of APIs:

There are several different types of API architecture some of which have been discussed above. Each with its own advantages and disadvantages. Here are some of the most common types:

  1. REST (Representational State Transfer): REST is a popular architecture for web-based APIs. It uses HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources identified by URLs. REST APIs are easy to use, scalable, and can be cached for better performance.

  2. SOAP (Simple Object Access Protocol): SOAP is an XML-based protocol for exchanging structured information between different software systems. It uses a standardized set of rules for defining the structure of the message, including headers, body, and fault messages. SOAP APIs are more complex than REST APIs, but they offer more advanced features like transactions and security.

  3. GraphQL: GraphQL is a query language for APIs that was developed by Facebook. It enables clients to specify exactly what data they need and get back only that data, rather than a whole resource. GraphQL APIs are highly flexible and efficient, but they require more upfront design work than REST APIs.

  4. RPC (Remote Procedure Call): RPC is a protocol that enables one application to call a function on another application across a network. It is often used for internal APIs within a single organization. RPC APIs are simple and fast, but they can be difficult to scale and manage.

Understanding the different types of API architecture can help you choose the right one for your needs. Each architecture has its own strengths and weaknesses, so it's important to carefully consider your requirements before making a decision. As a beginner, you can start building your own RESTful API using a tool like Node.js or Flask. We'll soon be building our first RESTful API using node.

RESTful APIs:

RESTful APIs, also known as REST APIs, are web APIs that follow the principles of Representational State Transfer (REST) architecture. RESTful APIs are based on the HTTP protocol and use the HTTP verbs (GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE, HEAD, CONNECT) to perform operations on resources.

The two key concepts in RESTful API design are the base URI (Uniform Resource Identifier) and resources. The base URI identifies the base URL for all resources in the API. Resources are the objects or data elements that the API exposes to clients. Each resource in a RESTful API is identified by a unique URL or URI.

Requests and responses in RESTful APIs are typically in JSON (JavaScript Object Notation) or XML (Extensible Markup Language) format. JSON is a lightweight data-interchange format that is easy to read and write, while XML is a markup language that is used for structuring and encoding data.

RESTful APIs are designed to be stateless, meaning that each request contains all the information necessary for the server to process it. This allows for greater scalability and performance since the server does not need to maintain state information for each client.

Building a RESTful API:

In my last blog post, I gave a brief overview of Node.js for beginners. In this post, I will show you how to build a RESTful API using Node.js. (In case you want to go through the previous blog you can check it out at https://hashnode.com/post/clfu8fo36000709me0idt2h10.)

RESTful APIs are built on a client-server architecture, where the server provides resources and the client can interact with them using HTTP requests. The Node.js platform provides a powerful set of tools for building RESTful APIs, including the Express framework and various middleware packages.

Before we begin, it's important to note that to run this application, you must have Node.js installed on your PC. If you don't already have it installed, you can download it from this link: nodejs.org/en/download

To build our RESTful API with Node.js, we will be using the following dependencies and packages:

  • Express: A popular Node.js framework for building web applications and APIs

  • Body-parser: A middleware package for parsing incoming request bodies in JSON format

  • Nodemon: A development dependency that automatically restarts the server when changes are made to the code

Step 1:

To get started, create a new directory for your project and navigate to it in your terminal. Then, run the following command to initialize a new Node.js project:

npm init

This will create a package.json file, which is used to manage the dependencies for your project. Next, install the required dependencies by running the following commands:

npm install express
npm install body-parser 
npm install nodemon --save-dev

Step 2:

Create a new file called server.js in your project directory.

Import the required dependencies and packages:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }))
const port = 3000;

Here we are importing the required dependencies and packages. express is a popular Node.js framework for building web applications, while body-parser is a middleware that parses incoming request bodies.

The app.use(bodyParser.urlencoded({ extended: true })) line of code is configuring the Express application to use the body-parser middleware for handling URL encoded data.

We are creating a new instance of express() and storing it in the variable app. We are also specifying the port number to run the server on, which is 3000 in this case.

Step 3:

Define a route for the root of the API:

app.get('/', (req, res) => {
  res.send('Welcome to my RESTful API');
});

This line defines a route for the root of the API. When a GET request is made to the root URL (/), the server will send the string "Welcome to my RESTful API" as the response.

Step 4:

app.get('/resources', (req, res) => {
  const resources = ['resource1', 'resource2', 'resource3'];
  res.json(resources);
});

This line defines a route for getting a list of resources. When a GET request is made to the URL /resources, the server will send a JSON array of resources as the response.

Step 5:

app.get('/resources/:id', (req, res) => {
  const id = req.params.id;
  const resource = `resource${id}`;
  res.json(resource);
});

This line defines a route for getting a single resource by ID. When a GET request is made to a URL like /resources/1, the server will extract the id parameter from the URL and use it to construct the resource name (resource1 in this case). The server will then send the resource name as the response.

Step 6:

app.post('/resources', (req, res) => {
  const newResource = req.body;
  // logic for creating a new resource
  res.send('Resource created');
});

This line defines a route for creating a new resource. When a POST request is made to the URL /resources, the server will extract the JSON data from the request body and store it in the newResource variable. The server can then use this data to create a new resource (the logic for which is not shown here). The server will then send the string "Resource created" as the response.

Step 7:

app.put('/resources/:id', (req, res) => {
  const id = req.params.id;
  const updatedResource = req.body;
  // logic for updating an existing resource
  res.send(`Resource ${id} updated`);
});

This line defines a route for updating an existing resource. When a PUT request is made to a URL like /resources/1, the server will extract the id parameter from the URL and use it to identify the resource to be updated. The server will also extract the JSON data from the request body and store it in the updatedResource variable. The server can then use this data to update the resource (the logic for which is not shown here). The server will then send the string "Resource 1 updated" (or the appropriate ID) as the response.

Step 8:

app.delete('/resources/:id', (req, res) => {
  const id = req.params.id;
  // logic for deleting a resource
  res.send(`Resource ${id} deleted`);
});

This line defines a route for deleting a resource. When a DELETE request is made to a URL like /resources/1, the server will extract the id parameter from the URL and use it to identify the resource to be deleted.

Step 9:

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

The app.listen() function starts the server and listens for incoming requests on the specified port (in this case, port 3000). When a request is received, it is processed by the appropriate route handler function.

Don't worry if you're having trouble understanding REST APIs. I'll be covering it in much greater detail in future blog posts, so stay tuned for more in-depth discussions on how they work.

Conclusion:

So that's it for today's blog post on building a RESTful API using Node.js. We covered a lot of ground in a short amount of time, from understanding what RESTful APIs are and how they work, to building a basic API using Node.js and Express. However, this is just the tip of the iceberg when it comes to APIs and RESTful APIs, and there is still so much more to learn.

In my next blog post, I will be dedicating it completely to REST APIs where we'll dive deeper and learn how to make HTTP requests not only by using the browser but also using Postman, a powerful tool for working with APIs. We will also explore more advanced topics like authentication, security, and error handling.

Thank you for reading, and I hope you found this blog post useful. Stay tuned for more content on APIs