GET/DELETE请求API返回最佳实践咨询及现有接口合理性排查
Hey there! Let's dive into the best practices for GET and DELETE API responses, and evaluate your current implementations to see how they stack up against common REST standards.
Your current setup returns 200 OK with a list of child IDs (empty if no children exist) on success, and 500 Internal Server Error for other cases. Here's how this aligns with best practices:
- Success cases (
200 OK): Returning an empty list when there are no children is totally valid—this is a normal business state, not an error. Clients can easily handle an empty array, so this approach is clean and intuitive. - Error cases: Using
500for all non-success scenarios is where you’ll want to make adjustments.500should only be reserved for unexpected server-side failures (like database connection issues). For client-facing issues, use more specific status codes:- If the requested person (e.g.,
person/1) doesn’t exist, return404 Not Found—this tells the client the parent resource doesn’t exist, not that the server broke. - If the request has invalid parameters (e.g., a non-numeric ID), return
400 Bad Requestto signal the client sent malformed data. - If the client lacks permission to access the person’s children, return
403 Forbidden.
- If the requested person (e.g.,
You’re returning 200 OK for all "successful" scenarios, including when the target child doesn’t exist. Let’s break this down:
- Deleting an existing resource: Returning
200 OKis acceptable, but many REST practitioners prefer204 No Contenthere.204signals the operation succeeded and there’s no need to send a response body, which is concise for delete actions. If you want to confirm the deletion, you can still return200with a simple message like{"deleted": true, "childId": 2}. - Deleting a non-existent resource: There’s no strict REST rule here—both
200 OK(since the end state is what the client wanted: the resource doesn’t exist) and404 Not Found(to inform the client the resource never existed) are common. The key is to be consistent across your API and document this behavior clearly so clients know what to expect. - Error cases: Again, avoid lumping all errors into success status codes. If the client can’t delete the child (e.g., lack of permissions, the parent person doesn’t exist), return appropriate codes like
403 Forbiddenor404 Not Foundinstead of200.
Your core logic for success responses is on the right track, but refining your error status codes will make your API more robust and client-friendly. Clear documentation of each status code and response format will also go a long way in helping developers integrate with your endpoints smoothly.
内容的提问来源于stack exchange,提问作者MNY

