Junior — Middle
Explain the principles of building web application architecture using REST, providing specific examples.
sobes.tech AI
Answer from AI
Web application architecture using REST is built on REST principles (Representational State Transfer), which ensure simplicity, scalability, and component independence.
Main principles:
- Resource-oriented: all objects (users, products, orders, etc.) are represented as resources with unique URIs.
- Use of standard HTTP methods:
- GET — retrieve a resource
- POST — create a new resource
- PUT — update a resource
- DELETE — delete a resource
- HTTP status codes to inform about the request result (e.g., 200 OK, 404 Not Found, 201 Created).
- Statelessness: the server does not store client state between requests.
Example:
Suppose there is a web application for task management.
- Get list of tasks:
GET /tasks - Get a specific task:
GET /tasks/{id} - Create a task:
POST /taskswith request body containing task data - Update a task:
PUT /tasks/{id}with updated data - Delete a task:
DELETE /tasks/{id}
In Python with Flask, it might look like this:
from flask import Flask, request, jsonify
app = Flask(__name__)
tasks = {}
@app.route('/tasks', methods=['GET'])
def get_tasks():
return jsonify(list(tasks.values()))
@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = tasks.get(task_id)
if task:
return jsonify(task)
return '', 404
@app.route('/tasks', methods=['POST'])
def create_task():
data = request.json
task_id = len(tasks) + 1
tasks[task_id] = {'id': task_id, 'name': data['name']}
return jsonify(tasks[task_id]), 201
@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
if task_id not in tasks:
return '', 404
data = request.json
tasks[task_id].update(data)
return jsonify(tasks[task_id])
@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
if task_id in tasks:
del tasks[task_id]
return '', 204
return '', 404
if __name__ == '__main__':
app.run()
This approach simplifies interaction between client and server, making the API understandable and standardized.