Python Flask Framework & RESTful APIs - A Practical Guide
Python Flask Framework & RESTful APIs - A Practical Guide
An Application Programming Interface (API) allows software applications to communicate with each other.
Flask, a lightweight Python web framework, is widely used for building APIs due to its simplicity and flexibility.
This article introduces the basics of creating APIs with Flask and outlines key concepts.
RESTful APIs (Representational State Transfer APIs) are a type of web service interface that adhere to the
principles of REST architecture, a set of constraints for creating scalable and stateless web services. RESTful
APIs enable communication between a client (e.g., web browser, mobile app) and a server over the HTTP
protocol, allowing the client to interact with resources on the server.
1. Stateless:
Each request from the client to the server must contain all the information needed to process the
request.
The server does not retain client state between requests.
2. Resource-Based:
Resources (e.g., users, products, orders) are the central elements of RESTful APIs.
Resources are represented using URIs (Uniform Resource Identifiers).
Example: /users/123 represents a specific user with ID 123.
3. HTTP Methods: RESTful APIs use standard HTTP methods to perform operations on resources:
4. Representations:
5. Stateless Communication:
6. Uniform Interface:
1/9
Suganya G
Resource: users
1. GET Request
Endpoint: GET /users/123
Response:
{
"id": 123,
"name": "John Doe",
"email": "johndoe@example.com"
}
2. POST Request
Endpoint: POST /users
Request Body:
{
"name": "Jane Smith",
"email": "janesmith@example.com"
}
Response:
{
"id": 124,
"name": "Jane Smith",
"email": "janesmith@example.com"
}
2/9
Suganya G
1. Web Applications:
Backend services for websites and web apps.
Example: Retrieving blog posts for a website.
2. Mobile Applications:
APIs for mobile apps to interact with a server.
Example: Fetching user data in a social media app.
3. IoT Devices:
Communication between IoT devices and servers.
Example: A smart thermostat interacting with a remote server.
4. Integration Between Systems:
Allowing different systems to communicate.
Example: Payment gateways.
RESTful APIs are widely used due to their simplicity, flexibility, and adherence to the principles of the web.
3/9
Suganya G
2. Setting Up Flask
1. Install Flask:
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
@app.route('/api/resource', methods=['GET'])
def get_resource():
return {"message": "Welcome to the API"}
Route: /api/resource
Method: GET
@app.route('/api/data', methods=['POST'])
def receive_data():
data = request.json
return {"received": data}, 201
4/9
Suganya G
app = Flask(__name__)
tasks = []
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify(tasks)
@app.route('/tasks', methods=['POST'])
def add_task():
task = request.json
tasks.append(task)
return jsonify({"message": "Task added!", "task": task}), 201
if __name__ == '__main__':
app.run(debug=True)
5/9
Suganya G
1. Imports:
Flask: The main class for creating the Flask web application.
request: To access the incoming HTTP request data (e.g., JSON payload).
jsonify: To convert Python data structures (like lists and dictionaries) into JSON responses.
2. App Initialization:
app = Flask(__name__)
3. Global Variables:
tasks = []
A list (tasks) is initialized to store task objects. This acts as an in-memory database.
4. Routes:
GET:
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify(tasks)
When a GET request is made, the API returns all tasks stored in the tasks list as a JSON
response.
POST:
@app.route('/tasks', methods=['POST'])
def add_task():
task = request.json
tasks.append(task)
return jsonify({"message": "Task added!", "task": task}), 201
When a POST request is made, the API extracts JSON data from the request body, appends
it to the tasks list, and returns a confirmation message along with the newly added task.
The HTTP status code 201 indicates successful resource creation.
6/9
Suganya G
if __name__ == '__main__':
app.run(debug=True)
Starts the Flask development server in debug mode, making it easier to test and debug the
application.
7/9
Suganya G
Example Outputs
[]
POST /tasks
Content-Type: application/json
{
"id": 1,
"title": "Learn Flask",
"completed": false
}
Response:
{
"message": "Task added!",
"task": {
"id": 1,
"title": "Learn Flask",
"completed": false
}
}
[
{"id": 1, "title": "Learn Flask", "completed": False}
]
8/9
Suganya G
GET /tasks
Response:
[
{
"id": 1,
"title": "Learn Flask",
"completed": false
}
]
Conclusion
This introduction provides a foundation for building RESTful APIs with Flask. As you grow comfortable, you
can add advanced features like authentication and error handling.
9/9