0
0
Flaskframework~5 mins

HTTP methods (GET, POST, PUT, DELETE) in Flask

Choose your learning style9 modes available
Introduction

HTTP methods tell a web server what action you want to do with data. They help your app get, send, update, or delete information.

When you want to show data on a webpage (GET).
When you want to send new data to the server, like submitting a form (POST).
When you want to change existing data on the server (PUT).
When you want to remove data from the server (DELETE).
Syntax
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/resource', methods=['GET', 'POST', 'PUT', 'DELETE'])
def resource():
    if request.method == 'GET':
        return 'Get data'
    elif request.method == 'POST':
        return 'Create data'
    elif request.method == 'PUT':
        return 'Update data'
    elif request.method == 'DELETE':
        return 'Delete data'

Use @app.route with methods to specify allowed HTTP methods.

Check request.method to handle each method differently.

Examples
This route only responds to GET requests to show items.
Flask
@app.route('/items', methods=['GET'])
def get_items():
    return 'List of items'
This route accepts POST requests to add a new item using JSON data.
Flask
@app.route('/items', methods=['POST'])
def add_item():
    data = request.json
    return f"Added item: {data['name']}"
This route updates an existing item by its ID using PUT.
Flask
@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
    data = request.json
    return f"Updated item {id} with name {data['name']}"
This route deletes an item by its ID using DELETE.
Flask
@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
    return f"Deleted item {id}"
Sample Program

This Flask app manages a simple list of items using all four HTTP methods. You can get all items, add a new item, update an existing item, or delete an item by its ID.

Flask
from flask import Flask, request

app = Flask(__name__)

items = {1: 'apple', 2: 'banana'}

@app.route('/items', methods=['GET'])
def get_items():
    return items

@app.route('/items', methods=['POST'])
def add_item():
    new_id = max(items.keys()) + 1 if items else 1
    data = request.json
    items[new_id] = data['name']
    return {'id': new_id, 'name': items[new_id]}, 201

@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
    if id in items:
        data = request.json
        items[id] = data['name']
        return {'id': id, 'name': items[id]}
    else:
        return {'error': 'Item not found'}, 404

@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
    if id in items:
        del items[id]
        return {'message': f'Item {id} deleted'}
    else:
        return {'error': 'Item not found'}, 404
OutputSuccess
Important Notes

GET requests should not change data; they only fetch it.

POST is for creating new data, PUT is for updating existing data.

DELETE removes data and should be used carefully.

Summary

HTTP methods tell the server what action to do with data.

Use GET to read, POST to create, PUT to update, and DELETE to remove data.

Flask lets you handle these methods easily with routes and request checks.