Everything You Need To Know About REST APIs
In the digital age, where applications and services seamlessly connect and interact, REST APIs have emerged as the unsung heroes behind the scenes. They’re the magic conduits that allow different software systems to communicate, enabling everything from social media interactions to e-commerce transactions and mobile app functionality. But what exactly is a REST API, and why is it the backbone of modern web development?
Welcome to my exposition into the realm of REST APIs — a guided journey that will demystify the world of web services and empower you with the knowledge to harness their potential. Whether you’re a tech enthusiast looking to understand the magic behind your favorite apps or a budding developer aiming to craft your own digital solutions, this exploration is for you.
In this blog, I’ll make sure to give you everything i wish i found in one place, when i was first introduced to the Rest APIs world.
What is an API
An API, or Application Programming Interface, is a vital component of modern software development. It acts as a bridge, enabling different applications to communicate and share data seamlessly. Let’s delve into this concept through a practical example.
Imagine you want to book train tickets using a web application. When you visit the application, it displays valuable information like departure times and available stations. Now, let’s take a peek behind the scenes from a developer’s perspective.
From the developer’s standpoint, the goal is to present all the essential train schedule data within the web application. To achieve this, developers make use of APIs. These APIs serve as the intermediaries that connect the web application with the web server, where all the intricate details about train schedules are securely stored.
In simple terms, an API acts as a communication channel. It enables developers to request specific information, such as train schedules, from the web server. The server, in turn, responds to these requests by providing the necessary data. This data can then be seamlessly integrated into the web application, allowing users like you to effortlessly access train information, make bookings, and plan your journey.
In other words, when you want to interact with a computer or system to retrieve information or perform a function, an API allows you to communicate your expectations to the system so that it can understand your request and respond accordingly. You can think of an API as a mediator between users or clients and the web resources or services they want to access. For businesses, it also serves as a solution for sharing resources and information while maintaining a certain level of security, control, and authentication, determining who is authorized to access what.
So, whether you’re booking train tickets, checking the weather, or interacting with a multitude of digital services, APIs are at work behind the scenes, facilitating the flow of information and making these interactions possible. They’re the unsung heroes of the digital age, enabling a world of interconnected applications and services to function harmoniously.
Benefits Of Using APIs
APIs play a pivotal role in modern software development, offering a multitude of advantages that streamline processes and enhance functionality. Let’s explore some of the key benefits of using APIs:
1. Ease of Integration: APIs are incredibly versatile and can be seamlessly integrated into various software applications. They act as the connectors that facilitate communication and data exchange between different websites, services, or systems. This ease of integration is a game-changer, as it allows developers to leverage existing functionalities without reinventing the wheel.
2. Reduced Software Development Effort: APIs significantly reduce the development workload. Consider this scenario: You want to provide website visitors with precise store locations using GPS data. Instead of embarking on the massive task of building a GPS-based location tracking application from scratch, you can harness the power of APIs. In this case, you’d integrate APIs from services like Google Maps to effortlessly achieve the required functionality. This approach not only saves time but also minimizes development costs, making it a more efficient and cost-effective solution.
3. Enhanced Security: Security is paramount in the digital realm, and APIs excel in providing a secure communication gateway. They ensure that different components of an application can interact and exchange data without compromising data integrity or exposing vulnerabilities. By enforcing secure communication protocols, APIs help maintain the confidentiality and integrity of the data being transmitted, safeguarding against potential threats.
What is a RESTful Api ?
In the realm of web services and API design, the terms ‘RESTful API’ and ‘REST API’ are often used interchangeably, but it’s important to distinguish between the two for a clearer understanding of their distinct characteristics and functionalities.
1. What is REST API?
A REST API, an abbreviation for Representational State Transfer Application Programming Interface, is a communication protocol that follows a defined set of rules and principles. It facilitates interaction between different applications and services. REST APIs handle client requests for specific resources, responding by delivering relevant resource information in a format easily comprehensible to the client. Moreover, they enable clients to modify server items and create new ones, offering versatility in data interaction.
2. What is a RESTful API?
A RESTful API is an Application Programming Interface (API) that follows the principles and architectural constraints of REST. These APIs interact with RESTful web services and exhibit advantages such as enhanced scalability and a longer lifespan. RESTful APIs employ standard HTTP requests to access and manipulate data, providing clients with four primary methods: GET (retrieve a resource), POST (create a new resource), PUT (edit or update an existing resource), and DELETE (remove a resource).
Principles of REST API
In the realm of REST APIs, adherence to a set of fundamental principles defines their effectiveness and versatility. These 6 rules, often referred to as the “Six Rules of REST APIs,” form the cornerstone of RESTful architecture, providing a robust foundation for efficient communication and interaction between clients and servers.
1. Client-Server Separation: REST APIs enforce a strict separation between clients and servers, with interactions initiated solely by clients. This independence empowers client software to evolve independently of servers, fostering flexibility and maintainability.
2. Uniform Interface: A uniform interface standardizes communication between clients and REST APIs, facilitating compatibility across various languages and applications.This ensures that resources are identifiable and separated from the representations sent to the client, resources can be manipulated by the client using the received representation, self-descriptive messages contain sufficient details for the client to process the information, and the API includes hypertext/hypermedia, allowing the client to use hyperlinks to discover available actions after accessing a resource.
3. Stateless: Stateless interactions ensure that each request-response cycle stands alone, with no reliance on past requests. This enhances scalability and reduces server memory usage, guaranteeing efficient and independent interactions.
4. Layered System: REST APIs accommodate layers between clients and servers, enabling functions like security and traffic handling. These additional layers should not impact the core client-server interactions, ensuring flexibility and system resilience.
5. Cacheable: REST APIs support data caching, allowing clients to store resources locally for faster access. Responses specify cacheability, duration, and rules, optimizing server resource usage and reducing page load times.
6. Code on Demand (Optional): As an optional feature, REST APIs can deliver executable code to clients, empowering them to execute code in their own backend. This flexibility sets REST APIs apart and distinguishes them from other API methods like SOAP.
Understanding and following these six rules is essential for creating RESTful APIs that offer efficient, scalable, and adaptable interactions between clients and servers. These principles form the core of REST API design, ensuring robust communication in the ever-evolving landscape of web services.
HTTP Methods in RESTful APIs
One of the fundamental aspects of designing a RESTful API is the utilization of HTTP methods, also known as HTTP verbs. These methods define the type of operation to be performed on a resource and are crucial for enabling various interactions between clients and servers. RESTful APIs commonly employ four primary HTTP methods, each serving a distinct purpose:
1. GET: The GET method is used to retrieve information and resources from the server. When a client sends a GET request, it asks the server to provide the specified resource, and the server responds with the resource’s current representation. This method is read-only and should not have any side effects on the server.
2. POST: POST is employed for creating new resources on the server. When a client sends a POST request, it submits data to the server to create a new resource. The server processes the data and responds with information about the newly created resource, usually including a unique identifier.
3. PUT: PUT is used for updating or replacing an existing resource. Clients send a PUT request along with the updated representation of the resource, and the server replaces the existing resource with the new data provided in the request. PUT requests are idempotent, meaning that performing the same request multiple times produces the same result as performing it once.
4. DELETE: The DELETE method does exactly what its name suggests. It deletes a resource from the server. When a client sends a DELETE request, it instructs the server to remove the specified resource permanently.
These four HTTP methods provide a standardized and versatile way for clients to interact with RESTful APIs. They map to common CRUD (Create, Read, Update, Delete) operations, making API endpoints intuitive and easy to understand. Additionally, adhering to these methods ensures that the API remains consistent with REST principles, promoting a uniform and predictable interface for clients.
While these are the core HTTP methods in RESTful APIs, it’s worth noting that there are additional HTTP methods like PATCH (Used to make partial updates to a resource. It’s handy when you want to modify specific parts of a resource without replacing the whole thing), HEAD (HEAD is like GET, but it only asks for resource headers, not the content. It’s useful for checking if a resource exists, getting metadata, or assessing cached data) , and OPTIONS (Helps clients understand what they can do with a resource. It provides a list of supported methods and other details about the resource’s capabilities ) that can serve specific use cases. Understanding when and how to use each method is essential for designing APIs that are efficient, maintainable, and user-friendly. In the following sections, we’ll delve deeper into the usage and best practices of these HTTP methods in the context of RESTful API design.
Status Codes
In the world of RESTful APIs, status codes play a pivotal role in communication between clients and servers. They are concise three-digit numbers that provide a quick way to convey the outcome of a client’s request to the server. Status codes are divided into three main levels: 200, 400, and 500.
1. Level 200 (Successful): Status codes in the 200 range indicate that the client’s request was successfully received, understood, and processed by the server. One of the most common 200 status codes is “200 OK,” which signifies that the request was successful, and the server has responded with the requested information.
2.Level 400 (Client Errors): Status codes in the 400 range typically indicate client-side errors. These codes are issued when there is an issue with the client’s request. Common examples include:
- 401 Unauthorized: The status code 401 is used to indicate that the client’s request lacks proper authentication or credentials. It signifies that the client must provide valid authentication information to access the requested resource.
- 402 Payment Required: The status code 402 indicates that a payment is required to access the requested resource. It’s not as commonly used as other status codes but can be employed in scenarios where access to a resource is restricted until a payment or subscription is processed.
- 403 Forbidden: This status code signifies that the server understood the request, but it refuses to fulfill it due to insufficient permissions.
- 404 Not Found: It is returned when the requested resource does not exist on the server.
3.Level 500 (Server Errors): Status codes in the 500 range indicate server-side errors. These codes are issued when there is an issue with the server while processing the request. “500 Internal Server Error” is a common example and suggests that something went wrong on the server’s end, often due to misconfiguration or unexpected issues.
How to create a basic REST API using Python
Wondering how to implement Python RESTful API Python RESTful API ? No worries, I got you . In this little simple example, I’ll make sure you will learn how to implement Python RESTFul API with CRUD operations.
We hope you have installed Python in Your Windows or Linux with Python and its packages. Here we are using Python 3.10.4 version. We will use flask, flask-mysql and flask-cors module. For the database, I’m comfortable with MySql, but feel free to use the one you are most confident with.
So let’s create RESTful API using Python and MySQL. We have project directory restful-api-python and the major files are:
- config.py
- app.py
- main.py
Step 1: Create MySQL Database Table :
As we will implement RESTful API to perform CRUD operations, so we will create MySQL database, table emp to perform operations. So first we will create MySQL database rest-api and then create table emp using below table create statement. Also if you are not familiar with SQL, checkout my blog : “ SQL Basics” . It should cover everything you need to get started with this tutorial.
CREATE TABLE `emp` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(16) DEFAULT NULL,
`address` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `emp`
ADD PRIMARY KEY (`id`);
ALTER TABLE `emp`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Step 2 : Import Flask Modules
As we handle handle REST API functionality using Flask and MySQL, so we will need both the modules. The module Flask works as web framework while MySQL module require to make connection with MySQL database.
So first we will create project directory restful-api-python and move inside using cd command.
Then we will install flask module by running below command.
we will also install flask-cors extension for handling Cross Origin Resource Sharing (CORS), making cross-origin possible.
pip install Flask
pip install -U flask-cors
So now we will create the app.py Python script and import the flask module and create the flask instance to use with MySQL module. We will also import code — flask-cors extension for cross-origin.
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
Step 3: Create MySQL Connection
We need to install Flask-MySQL extension that allows you to access a MySQL database. We will install Flask-MySQL extension using below command.
pip install flask-mysql
We will create config.py Python file to initialize MySQL database connection details to make connection with MySQL database.
We will import the app script to handle MySQL database connection with Flask-MySQL module.
As we have already created MySQL database rest-api, so we will connect by providing connection details.
from app import app
from flaskext.mysql import MySQL
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'rest-api'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
Step 4: Create The CRUD Operations
In the following main.py script, we import two modules: app and config. Our primary objective is to establish a connection with a MySQL database and implement a set of CRUD (Create, Read, Update, Delete) operations by defining RESTful URIs.
To create new employee records in the MySQL database, we employ the POST HTTP method. For retrieving employee records, we utilize the GET HTTP method, which can be used to fetch either all records or an individual record. To update employee records, the PUT HTTP method is employed. Additionally, we have implemented the DELETE HTTP method for removing records from the database. In case no records are found, we have implemented a custom 404 error handling method.
import pymysql
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request
@app.route('/create', methods=['POST']) # Create new employee
def create_emp():
try:
_json = request.json
_name = _json['name']
_email = _json['email']
_phone = _json['phone']
_address = _json['address']
if _name and _email and _phone and _address and request.method == 'POST':
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
sqlQuery = "INSERT INTO emp(name, email, phone, address) VALUES(%s, %s, %s, %s)"
bindData = (_name, _email, _phone, _address)
cursor.execute(sqlQuery, bindData)
conn.commit()
respone = jsonify('Employee added successfully!')
respone.status_code = 200
return respone
else:
return showMessage()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/emp') # retrieving all employees records
def emp():
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT id, name, email, phone, address FROM emp")
empRows = cursor.fetchall()
respone = jsonify(empRows)
respone.status_code = 200
return respone
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/emp/')
def emp_details(emp_id): # retrieving 1 employee record
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT id, name, email, phone, address FROM emp WHERE id =%s", emp_id)
empRow = cursor.fetchone()
respone = jsonify(empRow)
respone.status_code = 200
return respone
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/update', methods=['PUT']) # Update the employee
def update_emp():
try:
_json = request.json
_id = _json['id']
_name = _json['name']
_email = _json['email']
_phone = _json['phone']
_address = _json['address']
if _name and _email and _phone and _address and _id and request.method == 'PUT':
sqlQuery = "UPDATE emp SET name=%s, email=%s, phone=%s, address=%s WHERE id=%s"
bindData = (_name, _email, _phone, _address, _id,)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sqlQuery, bindData)
conn.commit()
respone = jsonify('Employee updated successfully!')
respone.status_code = 200
return respone
else:
return showMessage()
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/delete/', methods=['DELETE']) # delete the employee
def delete_emp(id):
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("DELETE FROM emp WHERE id =%s", (id,))
conn.commit()
respone = jsonify('Employee deleted successfully!')
respone.status_code = 200
return respone
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.errorhandler(404)
def showMessage(error=None):
message = {
'status': 404,
'message': 'Record not found: ' + request.url,
}
respone = jsonify(message)
respone.status_code = 404
return respone
if __name__ == "__main__":
app.run()
Step 5: Run the application
Now we will go the project directory restful-api-python and execute the the command python main.py and the server will start on default port 5000. Now we will use Postman to run our Python RESTful API with (POST, GET, PUT or DELETE) methods to test it.
We will run the below URL with HTTP GET method to get the all employee and display data in JSON format.
http://localhost:5000/emp
The following JSON data response will be returned:
We will get the employee record in JSON data with id = 1 using below URL with GET HTTP method.
http://localhost:5000/emp/1
And the response is going to be like the next screenshot.
We will create new employee record with POST HTTP method.
http://localhost:5000/create
The request body in Postman will be following. Also , the response will JSON data employee add message.
We will update existing employee record with id = 1 using PUT HTTP method.
http://localhost:5000/update
The request body will be demonstrated in the picture below:
Now, To our last method. We will delete existing fourth employee using DELETE HTTP method.
http://localhost:5000/delete/4
The response is going to be :
You have made it to the end. Now, I believe you have grasped all the essentials you need to know about RESTful APIs. This was simple; try other methods on your own, with different frameworks and databases. It’s fun!!!
Conclusion
RESTful APIs are a foundational component of modern software systems. By adhering to the six fundamental principles and effectively utilizing HTTP methods, developers can create APIs that offer efficient, scalable, and adaptable interactions.
As you embark on your journey in API development or consumption, remember that RESTful APIs are designed to simplify the exchange of data while maintaining a high degree of flexibility. By embracing these principles and following this simple code explanation, you’ll be well-equipped to create and utilize RESTful APIs that power the next generation of applications.
“Happy coding!”