A Beginner's Guide to APIs
Tags: api, beginners, programming, react
Published: 2023-10-25 04:34:44

<p data-pm-slice="1 5 []">The world today is more connected than ever before. We use phone apps to order food, transfer money, book rides, and do anything we need. But how do all these different apps and services integrate with one another or exchange information seamlessly? This is where APIs come in.</p>
API stands for Application Programming Interface. Don't let the name intimidate you - APIs are actually quite easy to understand, even if you're new to technology. This comprehensive guide will explain APIs, their importance, and how they work in simple terms.

I wrote <a class="attrlink" href="https://blog.learnhub.africa/2023/08/29/how-to-scrap-linkedin-company-data-using-voyager-api/" target="_blank" rel="noopener noreferrer nofollow">How to Scrap LinkedIn Company Data using Voyager Api</a>, showing why APIs are critical to building.
<h4>What Exactly Are APIs?</h4>
Let's break down the name first - <strong>Application Programming Interfaces.</strong>

An application is any software or program. For example, apps on your phone like WhatsApp or Facebook or websites like YouTube and Reddit are all applications. Programming refers to code that allows you to create software and applications. An interface between two applications enables them to talk to each other.

So, APIs are code interfaces that enable two software applications to communicate with each other. Like how two people talk - there needs to be a common language between them; APIs are that common language between applications.

For example, let's say you want to build an app that recommends recipes to users based on ingredients they have at home. Your app would need to interface with grocery websites to access their database of food items.

This interface that allows your app to retrieve data from the grocery website is the API. The API would need proper authentication and security to ensure only authorized access. The data may be exchanged via a JSON API with well-documented endpoints. Proper API testing and monitoring would help catch any errors and issues.

You can also <a class="attrlink" href="https://blog.learnhub.africa/2023/08/16/mastering-the-art-of-rest-apis-a-complete-overview/" target="_blank" rel="noopener noreferrer nofollow">Master the Art of REST APIs: A Complete Overview</a>.
<h4>Why Are APIs Important?</h4>
Now that we know what APIs are in simple terms, let's talk about why they are so important:
<ol>
 	<li>APIs allow different software systems to communicate and share data seamlessly. This is fundamental in enabling most modern web and mobile applications to work.</li>
</ol>
<ol start="2">
 	<li>APIs enable developers to reuse functionality that has already been built. For example, by calling the YouTube API, I can embed video playback functionality in my app without building video streaming from scratch.</li>
</ol>
<ol start="3">
 	<li>APIs significantly speed up software development, allowing developers to focus on building unique product features.</li>
</ol>
<ol start="4">
 	<li>Public APIs enable innovation by allowing developers to build on existing platforms. For example, many new weather apps have been built by giving developers access to weather data APIs.</li>
</ol>
<ol start="5">
 	<li>APIs allow the building of scalable software that can serve millions of users. Imagine if every app had to build its own servers and infrastructure - it would be impossible to scale up fast. But by leveraging common APIs, apps can exponentially scale access and user base.</li>
</ol>
Simply put, APIs power most of the applications we use today by enabling systems to communicate, share data, provide access to complex functionality, and allow innovation on existing platforms.
<h4>How Do APIs Work?</h4>
Now that we know why APIs are so fundamental let's go a bit deeper and understand how they actually work.

APIs essentially work by having two components - a client and a server. The client is the application or system that needs to access the functionality, while the server is the system that houses the API.

Let's take the grocery app example from earlier. Our recipe app would be the client trying to access the grocery website, which is the server.

The common API languages are REST and SOAP. REST has become popular in recent years due to its simplicity. Below is a high-level overview of how a REST API works:
<ol>
 	<li>The client sends an API request to a specific URL endpoint on the server. For example, to request all recipes containing chicken, the client may send a GET request to <a href="http://grocerystore.com/recipes/chicken" target="_blank" rel="noopener noreferrer nofollow">http://grocerystore.com/recipes/chicken</a>.</li>
</ol>
<ol start="2">
 	<li>The server processes these requests, interacts with the underlying database or software systems, and packages the response.</li>
</ol>
<ol start="3">
 	<li>The server finally sends back the data response, usually in JSON format. So, all chicken recipes may be sent back as JSON objects.</li>
</ol>
<ol start="4">
 	<li>The client app processes this response and displays recipes to the user or uses the data in the app as required.</li>
</ol>
So, in summary, the client app makes API calls over the internet to the remote server, which sends back structured data - and this data can then be displayed or manipulated within the client app.
<h4>Real-World Examples of APIs</h4>
Let's look at some real-world examples of popular APIs that you may use regularly:
<ul>
 	<li>Google Maps API - This allows any app to embed Google Maps. It makes adding mapping features easy without building complex mapping software from scratch.</li>
 	<li>Twitter API - Enables apps to access and display tweets and Twitter data like follower counts, profiles, etc. This is how Twitter clients and management apps are built.</li>
 	<li>Stripe API - Allows apps and websites to easily accept payments without managing the complex financial and regulatory requirements behind processing payments.</li>
 	<li>Slack API - Enables automation and building custom integrations with the Slack messaging platform. Apps can be notified of events through this API.</li>
 	<li>Darksky Weather API - Provides current and future weather data like precipitation chances, temperature, etc, that weather apps rely on.</li>
 	<li>YouTube API - Allows embedding YouTube videos in other apps and building custom YouTube clients.</li>
</ul>
These are examples of the thousands of APIs that power functionality across the apps and websites we use regularly.
<h4>Advantages of APIs</h4>
Now that you understand the basics of APIs, let's talk about why they provide so much value:
<ol>
 	<li>Abstract complexity - APIs hide all the messy details and complexity involved "under the hood." This allows developers to use the functionality easily without building everything from scratch.</li>
</ol>
<ol start="2">
 	<li>Save time and effort - Taping into existing APIs and code saves enormous development time and effort.</li>
</ol>
<ol start="3">
 	<li>Reusability - Once an API is built and shared publicly, any number of applications can leverage it, leading to reusability.</li>
</ol>
<ol start="4">
 	<li>Scalability - APIs allow easy scaling to large user bases without having to handle the loads directly.</li>
</ol>
<ol start="5">
 	<li>Provide core functionality - Be it payment processing, mapping, messaging, or more - APIs provide ready-to-use core functionalities.</li>
</ol>
<ol start="6">
 	<li>Faster innovation - Public APIs fuel innovation by allowing developers to build on existing platforms rapidly.</li>
</ol>
<ol start="7">
 	<li>Monetization - Companies like Google and Twitter expose APIs that enable them to monetize their platforms through increased usage further.</li>
</ol>
Hopefully, by now, you have a good high-level understanding of what APIs are, why they are important in software development, and their advantages.
<h4>API Security Considerations</h4>
However, it's important to note that APIs also present security risks that must be mitigated. Some key API security considerations are:
<ul>
 	<li>Authentication - Secure your APIs by implementing authentication mechanisms like OAuth to ensure only authorized clients can access them.</li>
</ul>
<ul>
 	<li>Access controls - Put in place proper access controls to restrict API access to only the functionality each client requires.</li>
</ul>
<ul>
 	<li>Encryption - Use HTTPS and encrypt all API communication to prevent snooping of data in transit.</li>
</ul>
<ul>
 	<li>Rate limiting - Implement rate limiting to prevent abuse and denial of service attacks via APIs.</li>
</ul>
<ul>
 	<li>Input validation - Validate all input data to prevent attacks like SQL injection that compromise the server via the API.</li>
</ul>
<ul>
 	<li>Monitoring - Track API usage statistics, errors, and latencies to stay on top of performance and quickly detect new threats.</li>
</ul>
<ul>
 	<li>Documentation - Embed security directly into API documentation to ensure developers understand proper usage from the start.</li>
</ul>
While APIs provide immense value, securing them requires thought and planning. APIs are integral to modern software applications powering key functionality and capabilities. Understanding APIs is a must for any aspiring developer today.
<h4>Real Life Practical <strong>(code was developed using AI)</strong></h4>
Here is a step-by-step code example for building the Sample To-Do List API in Node.js:

- Set up the project
<ul>
 	<li>Create a new directory for the project</li>
 	<li>Initialize a Node.js project:</li>
</ul>
<code>npm init</code>
<ul>
 	<li>Install Express with:</li>
</ul>
<code>npm install express</code>
<ul>
 	<li>Install SQLite3 package to interface with SQLite database</li>
</ul>
Step 2 - Define routes and controllers
<ul>
 	<li>In app.js define all the API endpoints:
<pre><code class="language-javascript">// GET /todos

// POST /todos

// GET /todos/:id

// PUT /todos/:id

// DELETE /todos/:id</code></pre>
</li>
 	<li>Create a controllers folder with separate files containing handler functions for each endpoint.</li>
 	<li>
<pre><code class="language-javascript">// controllers/todos.js
exports.getTodos = (req, res) =&gt; {
  // Get all todos logic
} 
exports.createTodo = (req, res) =&gt; {
  // Create todo logic  
}</code></pre>
</li>
</ul>
Step 3 - Handle requests and responses
<ul>
 	<li>Import the controllers into app.js</li>
 	<li>Match the endpoints to the corresponding controllers
<pre><code class="language-json">app.get('/todos', todosController.getTodos); 
app.post('/todos', todosController.createTodo);</code></pre>
</li>
 	<li>Send back JSON responses from the controllers.
<pre><code class="language-json">res.status(200).json({todos: [/* array of todos */]});
res.status(500).json({error: 'Error message'}); </code></pre>
</li>
</ul>
Step 4 - Connect to SQLite
<ul>
 	<li>Configure SQLite database using SQLite3 package</li>
 	<li>Define models to match database structure</li>
 	<li>Access the database from within controller functions</li>
</ul>
Step 5 - Add authentication
<ul>
 	<li>Install a package like Passport.js for authentication</li>
 	<li>Create a middleware to validate API keys on each request</li>
 	<li>Reject requests without a valid key</li>
</ul>
Step 6 - Write documentation
<ul>
 	<li>Use OpenAPI or Postman to create detailed API documentation</li>
 	<li>Include examples of requests and responses for each endpoint</li>
</ul>
And that's it! The main pieces of building a robust REST API with Node.js and SQLite.
<h4><strong>Resources</strong></h4>
<ul>
 	<li>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/06/13-powerful-python-snippets-to-automate-tasks/" target="_blank" rel="noopener noreferrer nofollow">13 Powerful Python Snippets To Automate Tasks</a></li>
 	<li><a class="attrlink" href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/07/21/scraping-using-python-in-step-by-step-approach/" target="_blank" rel="noopener noreferrer nofollow">Web scraping with Python</a></li>
</ul>
</li>
</ul>