In this lesson, we focus on implementing the DELETE operation, completing the CRUD (Create, Read, Update, Delete) functionalities for our Cash Card API. We start by defining the API specification for the DELETE endpoint:
- Request:
- Verb: DELETE
- URI:
/cashcards/{id}
- Body: (empty)
- Response:
- Status Code: 204 NO CONTENT
- Body: (empty)
For successful deletions, we return a 204 NO CONTENT status code. However, there are additional cases where we return 404 NOT FOUND:
- If the Cash Card does not exist (non-existent ID).
- If the Cash Card exists but the principal (user) is not authorized to delete it.
Returning 404 NOT FOUND in both cases prevents unauthorized users from discerning whether a particular ID exists, enhancing security by not "leaking" information.
Additional Options:
- Hard and Soft Delete:
- Hard Delete: Permanently removes the record from the database. The data is gone forever, which might be an issue if historical data is needed.
- Soft Delete: Marks the record as deleted (e.g., adding an
IS_DELETED
flag or DELETED_DATE
timestamp) without removing it from the database. Requires repository adjustments to exclude deleted records from queries.
- Audit Trail and Archiving:
- Audit Fields: Adding fields like
DELETED_DATE
or DELETED_BY_USER
to track deletion events.
- Audit Trail: Keeping a separate log of all operations (Create, Update, Delete) performed on records.
- Archiving: Moving deleted data to a different storage location for compliance or historical purposes.
Our API decision is to implement a simple DELETE operation returning 204 NO CONTENT, which suggests a hard delete approach. This means we are not implementing soft delete or including audit fields in the response body.
Learning Points:
- Completing CRUD Operations with DELETE:
- Implementing the DELETE method finalizes the essential CRUD functionalities in the API.
- API Specification Clarity:
- Clearly defining request and response specifications ensures consistent and predictable API behavior.
- Security Through Uniform Responses:
- Returning 404 NOT FOUND for both non-existent and unauthorized deletions prevents information leakage about resource existence.
- Understanding Hard vs. Soft Delete:
- Hard Delete: Permanently removes data, which may not be recoverable.
- Soft Delete: Marks data as deleted, allowing for recovery or auditing but requires additional handling in the application logic.
- Importance of Audit Trails:
- Maintaining audit logs helps meet compliance requirements and aids in tracking historical changes.
- Response Status Codes Matter:
- Choosing appropriate HTTP status codes (e.g., 204 NO CONTENT) communicates the result of operations effectively.
- API Design Decisions Impact Implementation:
- Decisions like returning 204 NO CONTENT influence whether features like soft delete are implemented.