Web API删除接口实现规范咨询:现有GET方式是否合理?
Hey there! Let's break down this API design question and get you on track with best practices.
First: Why your current GET-based delete is a problem
Using a GET request to delete resources goes against the core semantics of HTTP methods:
GETis meant to be safe (it shouldn't modify server state) and idempotent (calling it multiple times has the same effect as once). Deleting data clearly changes server state, so this is a bad fit.- Browsers often cache
GETrequests or prefetch URLs, which could lead to accidental, unintended deletions. - It doesn't align with standard API design patterns, making your code harder for other developers to understand.
Why /API/DELETE/ID is also a mistake
The senior dev was right to call this out—here's why:
RESTful API design focuses on resources, not actions. The URL should identify the resource you're working with, and the HTTP method should define what you're doing to it. Putting DELETE in the URL is redundant because the DELETE HTTP method already tells the server you want to remove the resource.
For example:
- Instead of
/API/DELETE/123, use theDELETEmethod on/api/projects/123—this makes the intent clear and follows industry standards.
How to fix your PHP/JS code for proper DELETE requests
Let's rewrite your code to follow these best practices:
1. JavaScript (using Fetch API, cleaner than XMLHttpRequest)
function deleteProject(ID) { // First, get your CSRF token (more on this later) const csrfToken = document.querySelector('meta[name="csrf-token"]').content; fetch(`/api/projects/${encodeURIComponent(ID)}`, { method: 'DELETE', credentials: 'include', // Ensures session cookies are sent with the request headers: { 'X-CSRF-Token': csrfToken, 'Content-Type': 'application/json' } }) .then(response => { if (response.ok) { // Handle successful deletion (e.g., refresh the project list) alert('Project deleted successfully!'); location.reload(); } else if (response.status === 401) { alert('You need to log in to perform this action'); window.location.href = '/login'; } else { return response.json().then(err => { throw new Error(err.error) }); } }) .catch(error => { console.error('Deletion failed:', error); alert(`Error: ${error.message}`); }); }
2. PHP API (api.php)
First, we'll handle the DELETE method, use proper HTTP status codes, and keep your auth check:
session_start(); header('Content-Type: application/json'); // Login & permission check (adjust response for APIs—don't redirect, send status codes) if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['userLVL'] < 2) { http_response_code(401); echo json_encode(['error' => 'Not authorized to perform this action']); exit; } // Handle DELETE requests for projects if ($_SERVER['REQUEST_METHOD'] === 'DELETE') { // Parse the project ID from the URL (we'll need URL rewriting for this) $pathParts = explode('/', trim($_SERVER['PATH_INFO'], '/')); if (isset($pathParts[1]) && is_numeric($pathParts[1])) { $projectID = (int)$pathParts[1]; // Include your deletion logic require('../php/delete.php'); // Send success response (204 No Content is also common for deletions) http_response_code(200); echo json_encode(['success' => true, 'message' => 'Project deleted']); } else { http_response_code(400); echo json_encode(['error' => 'Invalid project ID provided']); } } else { // Method not allowed (only DELETE is accepted here) http_response_code(405); echo json_encode(['error' => 'Only DELETE requests are allowed for this endpoint']); }
3. URL Rewriting (to make /api/projects/123 work)
To map the clean resource URL to your api.php file, add this to an .htaccess file (for Apache):
RewriteEngine On RewriteRule ^api/projects/(\d+)$ api.php [L]
Or for Nginx, add this to your server block:
location /api/projects/ { rewrite ^/api/projects/(\d+)$ /api.php last; }
Key API Design Best Practices to Remember
- Use HTTP methods correctly:
GET: Retrieve resources (never modify state)POST: Create new resourcesPUT: Update an entire existing resourcePATCH: Update part of a resourceDELETE: Remove a resource
- Return meaningful HTTP status codes: 200 (success), 204 (no content), 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (resource not found), 405 (method not allowed)
- Add CSRF protection: For all non-GET requests (DELETE, POST, etc.), include a CSRF token (like the meta tag in the JS example) to prevent cross-site request forgery attacks
- Keep URLs resource-focused: URLs should describe what you're interacting with, not what action you're taking
内容的提问来源于stack exchange,提问作者Joeri

