Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Flask Framework & RESTful APIs - A Practical Guide

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Flask Framework & RESTful APIs - A Practical Guide

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Suganya G

Basics of Building RESTful APIs and Introduction to Flask


Introduction

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.

What Are RESTful APIs?

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.

Key Characteristics of RESTful APIs

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:

GET: Retrieve a resource or a collection of resources.


POST: Create a new resource.
PUT: Update an existing resource.
PATCH: Partially update a resource.
DELETE: Remove a resource.

4. Representations:

Resources can be represented in different formats (e.g., JSON, XML).


JSON is the most commonly used format.

5. Stateless Communication:

Each API request is independent.


Servers do not store information about client sessions.

6. Uniform Interface:

Consistency in resource naming, structure, and behavior.


Example: /products for product-related operations.

1/9
Suganya G

Example of a RESTful API

Resource: users

HTTP Method Endpoint Description

GET /users Retrieve all users

GET /users/123 Retrieve user with ID 123

POST /users Create a new user

PUT /users/123 Update user with ID 123

DELETE /users/123 Delete user with ID 123

Example with JSON

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

Advantages of RESTful APIs

1. Scalability: Statelessness and resource-based design make it easy to scale.


2. Interoperability: Wide compatibility with various platforms, languages, and tools.
3. Simplicity: Easy to implement and consume.
4. Flexibility: Supports multiple data formats (e.g., JSON, XML).
5. Performance: Efficient use of HTTP caching mechanisms.

Use Cases of RESTful APIs

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:

pip install flask

2. Basic Flask Application:

from flask import Flask


app = Flask(__name__)

@app.route('/')
def home():
return "Hello, Flask!"

if __name__ == '__main__':
app.run(debug=True)

3. API Endpoint Basics

Adding a Resource Endpoint:

@app.route('/api/resource', methods=['GET'])
def get_resource():
return {"message": "Welcome to the API"}

Route: /api/resource
Method: GET

4. Flask Core Concepts for APIs

Request Parsing: Extract data sent by the client.

from flask import request

@app.route('/api/data', methods=['POST'])
def receive_data():
data = request.json
return {"received": data}, 201

Response Handling: Return JSON responses.

4/9
Suganya G

A simple task manager example


This example demonstrates a simple Flask-based RESTful API for managing a list of tasks.

from flask import Flask, request, jsonify

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

Explanation of the Code

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__)

Creates a Flask application instance.

3. Global Variables:

tasks = []

A list (tasks) is initialized to store task objects. This acts as an in-memory database.

4. Routes:

/tasks endpoint handles two HTTP methods:

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

5. Run the Application:

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

Initial State of tasks:

[]

1. Adding a Task with a POST Request:

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
}
}

Updated State of tasks:

[
{"id": 1, "title": "Learn Flask", "completed": False}
]

8/9
Suganya G

2. Retrieving Tasks with a GET Request:

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

You might also like