Table of Contents
Introduction
Every time a piece of software or a simple document is shared with two systems the API (Application Programming Interface) is used. API is a type of software where two or more computer programs communicate with each other through data transfer.
With the help of this API, the company improves its productivity, efficiency and automation that can manage your work. Every organisation needs API, and there are several kinds of API available. among which the Restful API is one
What is a Restful API?
Restful API is defined as a Representational State Transfer Application Programming Interface known as REST API where the server will transfer a representation of the requested resource’s state to the client system which benefits the developers like.
- Simple and easy to use.
- Scalable
- Flexible
- Ease of integration
- Security
- Reduce Latency
As a popular architectural style for designing and developing web-based APIs. It helps to solve a variety of problems related to building web-based applications and services making it the best choice for the developers.
What is Flask?
A microweb framework is written in Python which does not require any particular tools or libraries and has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.
Flask is a small and lightweight framework of Python that offers useful tools and features for easy web development in Python with more flexibility and scalability by using a single Python file.
Creating RESTful Web APIs using Flask and Python
So, before creating a restful API let’s start by installing Flask Open your terminal and run the following command to install Flask using pip:
pip install Flask
Once Flask is installed, you can create a simple RESTful API.
from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample data
tasks = [
{
'id': 1,
'title': 'Task 1',
'done': False
},
{
'id': 2,
'title': 'Task 2',
'done': False
}
]
# Get all tasks
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
# Get a specific task by ID
@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = next((task for task in tasks if task['id'] == task_id), None)
if task is None:
return jsonify({'error': 'Task not found'}), 404
return jsonify({'task': task})
# Create a new task
@app.route('/tasks', methods=['POST'])
def create_task():
if not request.json or 'title' not in request.json:
return jsonify({'error': 'The title is required'}), 400
new_task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'done': False
}
tasks.append(new_task)
return jsonify({'task': new_task}), 201
# Update an existing task
@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
task = next((task for task in tasks if task['id'] == task_id), None)
if task is None:
return jsonify({'error': 'Task not found'}), 404
if 'title' in request.json:
task['title'] = request.json['title']
if 'done' in request.json:
task['done'] = request.json['done']
return jsonify({'task': task})
# Delete a task
@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
task = next((task for task in tasks if task['id'] == task_id), None)
if task is None:
return jsonify({'error': 'Task not found'}), 404
tasks.remove(task)
return jsonify({'result': True})
if __name__ == '__main__':
app.run(debug=True)
Save this code in a file, for example, app.py.
Run the application using:
python app.py
Your Flask app will be running at http://127.0.0.1:5000/.
You can use tools like curl, Postman
, or your preferred API testing tool to interact with the endpoints.
This example covers basic CRUD operations (Create, Read, Update, Delete) for a simple task list. You can extend and modify it based on your specific requirements.
In the provided example, we've created a simple Flask application that defines routes for a basic task management system. Let's break down the key components:
-
Importing Flask and other necessary modules
app = Flask(__name__)
This line creates an instance of the Flask class, which represents our web application.
-
Sample Data
tasks = [ {'id': 1, 'title': 'Task 1', 'done': False}, {'id': 2, 'title': 'Task 2', 'done': False}
We've initialized a list called tasks with some sample data to simulate a simple task list.
-
Route for getting all tasks
@app.route('/tasks', methods=['GET']) def get_tasks(): return jsonify({'tasks': tasks})
This route handles HTTP GET requests to / tasks and returns a JSON representation of the task list.
-
Route for getting a specific task by ID:
@app.route('/tasks/<int:task_id>', methods=['GET']) def get_task(task_id): # ... (code to find and return a specific task by ID)
This route handles GET requests to
/tasks/<task_id>
and returns details of a specific task identified by its ID. -
Route for creating a new task
@app.route('/tasks', methods=['POST']) def create_task(): # ... (code to create and add a new task to the task list)
This route handles PUT requests to
/tasks/<task_id>
and updates the details of an existing task. -
Route for deleting a task
@app.route('/tasks/<int:task_id>', methods=['DELETE']) def delete_task(task_id): # ... (code to delete an existing task from the task list)
This route handles and DELETE requests to
/tasks/<task_id>
and removes an existing task from the task list. -
Run the application
if __name__ == '__main__': app.run(debug=True)
This block ensures that the Flask app is only run when the script is executed directly, not when it’s imported as a module.
To interact with the API, you can use tools like curl, Postman, or any HTTP client.
-
Testing The API
To test the API, you can use tools like
curl, Postman,
or any HTTP client. If you’re using Postman, you can create requests for each endpoint (GET, POST, PUT, DELETE) to interact with the API. The base URL for the example ishttp://127.0.0.0:5000/.
Here's a summary of the endpoints
- GET all tasks:
GET http://127.0.0.1:5000/tasks
- GET a specific task:
GET http://127.0.0.1:5000/tasks/<task_id>
- CREATE a new task:
POST http://127.0.0.1:5000/tasks
with JSON data - UPDATE an existing task: PUT
http://127.0.0.1:5000/tasks/<task_id>
with JSON data - DELETE a task: DELETE
http://127.0.0.1:5000/tasks/<ta>
Conclusion
So, in conclusion, building a Restful API with Flask and Python provides a solid foundation for creating scalable and maintainable web services. Flask’s simplicity and flexibility make it an excellent choice for rapid development, while its modular structure allows for seamless expansion and customization.