Insights:PHP API Development: Integration, Authentication, and Error Handling
I. Define the Contract First
Specify for each API:
- Resource and method:
GET /api/v1/orders. - Request parameters: location, type, required flag, allowed values.
- Response structure: fields, types, examples.
- Error codes: HTTP status + business error code.
- Authentication method.
- Idempotency rules.
- Versioning strategy.
Example:
{
"code": 0,
"message": "ok",
"data": {
"id": 1001,
"status": "paid"
},
"trace_id": "req_abc123"
}
II. Authentication
Common approaches:
- Session/Cookie: suitable for same-origin admin panels.
- Bearer Token: suitable for separated frontend/backend architectures.
- HMAC signature: suitable for server-to-server calls.
- OAuth2: suitable for third-party authorization.
Key points:
- Define permissions per endpoint.
- Don't rely solely on frontend button hiding.
- Configure token expiration and refresh logic.
- Keep secrets out of version control.
- Return uniform errors on failure; do not leak internal details.
III. Parameter Validation
- Type, length, range, and enum checks.
- Required fields and default values.
- File type and size limits.
- Injection prevention: prepared statements and output escaping.
- Authorization bypass prevention: resource ownership verification.
Return 4xx on validation failure, never 500.
IV. Idempotency and Concurrency
- Order creation and payment APIs should support idempotency keys.
- Duplicate requests must return the same result.
- Use database unique indexes as a safety net.
- For concurrent updates, use optimistic locking (version) or row-level locks.
- Avoid race conditions in read-modify-write patterns.
V. Error Handling
Use a unified error structure:
| Field | Description |
|---|---|
| code | Business code; 0 means success |
| message | Human-readable error message |
| data | Response data on success, null on failure |
| trace_id | Trace ID for troubleshooting |
HTTP status recommendations:
- 200 — Success
- 400 — Bad request / invalid parameters
- 401 — Unauthorized
- 403 — Forbidden
- 404 — Not found
- 409 — Conflict
- 422 — Business validation failed
- 429 — Rate limited
- 500 — Internal server error
Never expose exception stack traces to the frontend.
VI. Logging and Monitoring
- Log request ID, user, endpoint, latency, and status.
- Mask sensitive fields.
- Alert on slow endpoints.
- Alert on elevated error rates.
- Maintain logs long enough for traceability.
VII. Rate Limiting and Security
- Apply rate limiting per IP, user, and API endpoint.
- Prevent replay attacks with timestamps and nonces.
- SSRF protection: Restrict callback addresses.
- Uploads: File type, size limits, storage isolation.
- CORS whitelist.
- HTTPS.
Eight. Integration Testing
Provide to frontend/counterparty:
- API documentation.
- Environment URLs.
- Test accounts.
- Sample requests and responses.
- Error code table.
- Mock data.
- Change notifications.
Most integration issues stem from unclear contracts, not unwritten code.
Nine. Versioning and Compatibility
- URL versioning:
/api/v1/. - Fields are additive only; deprecated fields are marked.
- Breaking changes are notified in advance.
- Maintain a transition period.
Ten. Acceptance
- Each API has documentation and examples.
- Authentication and authorization tests pass.
- Parameter validation coverage complete.
- Idempotency and concurrency tests.
- Unified error codes.
- Logs support issue localization.
- Rate limiting is effective.
- Stress testing meets targets.
Pricing and Timeline
Evaluation based on "number of APIs + auth method + integrated systems + documentation/testing + acceptance criteria." Quoting solely by price per interface often leads to budget overruns later due to integration adjustments and changes.
Related articles: