Python API With Flask And Postman – Put and Delete Methods

In the previous article, the post and get API methods were presented. In this one, Put and Delete are coming. 🙂

Random picture, not exactly related to Flask and Python.

Well, nothing that fancy, this is how these two methods look like:

# Update item by id
@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    data = request.get_json()
    updated_data = data.get('item') # Get the nested 'item' data

    if not updated_data:
        return jsonify({'error': 'No data provided'}), 400
    
    item = next((item for item in items if item['id'] == item_id), None)
    if item is None:
        return jsonify({'error': f'Item #{item_id} not found!'})

    # Update fields in the item (dummy db)
    for key, value in updated_data.items():
        if key in item:
            item[key] = value

    return jsonify({'message': 'Item updated successfully', 'item':item}), 200


# Delete item by id
@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item_to_delete = next((item for item in items if item['id'] == item_id), None)

    if item_to_delete is None:
        return jsonify({'error': f'Item {item_id} not found!'}), 404
    items.remove(item_to_delete)

    return jsonify({'message': f'Item: {item_to_delete} has been deleted successfully!'}), 200

And, of course tests are a “must”.

Just make sure that you never create items the same way, by repeating lines, this is an automatic “no-go” in production 🙂

import pytest
from app import app

@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

def test_update_item(client):
    # Setup: create a new item
    client.post('/api/items', json={'name': 'Test Item1'})
    client.post('/api/items', json={'name': 'Test Item2'})
    client.post('/api/items', json={'name': 'Test Item3'})

    # Test update 
    update_response = client.put('/api/items/2', json={'item':{"name":'Updated Test Item2'}})
    assert update_response.status_code == 200
    assert update_response.json['item']['name'] == 'Updated Test Item2'

    # Cleanup: delete the item
    client.delete('/api/items/1')
    client.delete('/api/items/2')
    client.delete('/api/items/3')


def test_delete_item(client):
    client.post('/api/items', json={'name': 'Test Item4'})

    delete_response = client.delete('/api/items/1')
    assert delete_response.status_code == 200

    get_response = client.get('/api/items/1')
    assert get_response.status_code == 404

To run the tests, go with pytest test_app.py

And this is how the tests look, if you are having some additional test, stating that 5=3:

Finally the YouTube video:

Python - API With Flask - Update and Delete

Enjoy it!