Back to Blog

Flask in Python - GET, POST, PUT, DELETE with curl Testing #39

Sandy LaneSandy Lane

Video: Flask in Python - GET, POST, PUT, DELETE with curl Testing #39 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Flask in Python - GET, POST, PUT, DELETE with curl Testing

This tutorial demonstrates how to build a RESTful API using Flask, a lightweight Python web framework. You will learn to define routes for GET, POST, PUT, and DELETE methods, handle JSON data, validate requests, and test your API endpoints using curl commands.

Code

from flask import Flask, request, jsonify

app = Flask(__name__)

# In-memory storage for tasks
tasks = {}

# GET all tasks or filter by 'completed' query parameter
@app.route('/tasks', methods=['GET'])
def get_tasks():
  completed = request.args.get('completed')
  if completed is not None:
    filtered = {k: v for k, v in tasks.items() if v['completed'] == (completed.lower() == 'true')}
    return jsonify(filtered)
  return jsonify(tasks)

# GET a single task by ID
@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
  task = tasks.get(task_id)
  if task:
    return jsonify(task)
  return jsonify({'error': 'Task not found'}), 404

# POST to create a new task
@app.route('/tasks', methods=['POST'])
def create_task():
  data = request.get_json()
  if not data or 'title' not in data:
    return jsonify({'error': 'Title is required'}), 400
  task_id = max(tasks.keys(), default=0) + 1
  task = {'title': data['title'], 'completed': data.get('completed', False)}
  tasks[task_id] = task
  return jsonify({'id': task_id, **task}), 201

# PUT to update an existing task
@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
  if task_id not in tasks:
    return jsonify({'error': 'Task not found'}), 404
  data = request.get_json()
  if not data:
    return jsonify({'error': 'No data provided'}), 400
  task = tasks[task_id]
  task['title'] = data.get('title', task['title'])
  task['completed'] = data.get('completed', task['completed'])
  return jsonify(task)

# DELETE a task by 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 jsonify({'error': 'Task not found'}), 404

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

Key Points

  • Use @app.route decorators with methods=['GET', 'POST', 'PUT', 'DELETE'] to define RESTful endpoints.
  • Access query parameters with request.args and JSON payloads with request.get_json().
  • Return JSON responses using jsonify() and include HTTP status codes by returning tuples.
  • Perform manual validation on incoming request data to ensure required fields are present.
  • Test your API endpoints easily from the command line using curl and format JSON output with python3 -m json.tool.