API Best Practices: Standardized REST API Development

API best practices module

1.  Executive Summary & Overview 

The ApiBestPractice module serves as the authoritative blueprint and reference implementation for RESTful API development across the CodeStandardDemo enterprise platform. It demonstrates standard design patterns, strict validation controls, standardized HTTP response structures, OpenAPI (Swagger) annotations, soft deletion, and modular separation of concerns. 

Core Architectural Principles Demonstrated:

  • Standardized API Responses: Uniform JSON envelope via ApiResponseTrait for consistent client integration.
  • Decoupled Request Validation: Isolated validation logic using Laravel Form Requests (StoreApiBestPracticeRequest, UpdateApiBestPracticeRequest).
  • Structured Data Transformations: Clean presentation layer transformation using Eloquent API Resources (ApiBestPracticeResource).
  • OpenAPI / Swagger Annotations: Comprehensive PHP 8 attributes (#[OA\Get], #[OA\Post]) for automated documentation rendering.
  • Data Integrity & Auditability: Soft deletes, Eloquent query scopes (search, status, category), and automated type casting.

2. Module Architecture & File Structure 

The module adheres strictly to the modular architectural layout provided by nwidart/laravel-modules. 

Directory / File Component Type Description & Responsibilities 
Http/Controllers/ApiBestPracticeController.php Controller Layer Handles incoming HTTP requests, invokes validation, executes model logic, and formats responses. Contains Swagger OA attributes. 
Entities/ApiBestPractice.php Eloquent Model Represents best_practice_demos table. Defines mass assignable fields, type casts, relationships, and reusable query scopes. 
Http/Requests/StoreApiBestPracticeRequest.php Form Request Defines validation rules and custom error messages for record creation. 
Http/Requests/UpdateApiBestPracticeRequest.php Form Request Defines conditional validation rules for updating existing records. 
Http/Requests/CheckUniqueCodeRequest.php Form Request Validates input payload for email/code uniqueness validation checks. 
Transformers/ApiBestPracticeResource.php API Resource Layer Transforms model instances into consistent JSON responses, suppressing sensitive fields (e.g. password) and formatting dates/urls. 
routes/api.php Routing Layer Defines API routes under Sanctum authentication middleware and v1 prefix. 
module.json Configuration Module metadata, priority, and ServiceProvider registration details. 

3. Database Schema & Data Model 

The underlying database table best_practice_demos stores demo entities showcasing multi-field validation, JSON arrays, file path attachments, and soft deletes. 

Table Schema: best_practice_demos 

Column Name Data Type Nullable Default / Details Description 
id BIGINT (PK) No Auto Increment Unique record ID 
user_id BIGINT (FK) No Foreign Key -> users.id Owner user relationship (cascade delete) 
title VARCHAR(255) No  Title or subject line 
email VARCHAR(255) No  Email address 
password VARCHAR(255) No  Bcrypt hashed secret key 
age INT No  Age numeric value (1 to 120) 
category VARCHAR(255) No  Category (education, technology, finance, lifestyle) 
status BOOLEAN No false Record status (active = true, inactive = false) 
gender VARCHAR(255) No  Gender classification (male, female, other) 
description TEXT Yes NULL Detailed narrative description 
attachment VARCHAR(255) Yes NULL Relative path to uploaded attachment file 
subscribed_topics JSON Yes NULL Array of subscribed topics (news, events, offers, updates) 
event_date DATE No  Target event date 
satisfaction_score INT No 50 Score metric (0 to 100) 
created_at / updated_at TIMESTAMP Yes Current Timestamp Standard Eloquent timestamps 
deleted_at TIMESTAMP Yes NULL Soft delete timestamp 

Eloquent Model Scopes & Features 

  • scopeActive($query): Filters query to only records where status = true. 
  • scopeByCategory($query, $category): Filters records by a specific category when provided. 
  • scopeSearch($query, $keyword): Performs multi-column fuzzy search across title, email, category, and description. 
  • user(): BelongsTo relationship mapping to Modules\UserManagement\Entities\User. 

4. API Response Standardization Framework 

All controller actions utilize App\Http\Traits\ApiResponseTrait to maintain strict schema consistency across HTTP responses. 

Standard Success Envelope (HTTP 200 / 201) 

{
"status": true,
"message": "API Best Practices fetched successfully.",
"data": {
"current_page": 1,
"items": [],
"total": 50,
"per_page": 15,
"last_page": 4
}
}

Standard Validation Error Envelope (HTTP 422) 

{
"status": false,
"message": "Validation failed",
"error": {
"email": ["The email field is required."],
"category": ["The selected category is invalid."]
}
}

5. API Endpoint Specifications & Response Payloads 

GET
/api/v1/api-best-practice
Summary:
Get Paginated List of API Best Practice Demos
Query Parameters:
search, category, status, per_page, page
API RESPONSE (HTTP 200 OK):
{
    "status": true,
    "message": "API Best Practices fetched successfully.",
    "data": {
        "current_page": 1,
        "items": [
            {
                "id": 1,
                "user_id": 2,
                "user": {
                    "id": 2,
                    "name": "John Doe",
                    "email": "john@example.com"
                },
                "title": "API Security Standards",
                "email": "john@example.com",
                "age": 30,
                "category": "technology",
                "status": true,
                "gender": "male",
                "description": "Comprehensive API guidelines and security best practices.",
                "attachment": "http://localhost/storage/best_practice_demos/sample.jpg",
                "subscribed_topics": [
                    "news",
                    "updates"
                ],
                "event_date": "2026-08-15",
                "satisfaction_score": 90,
                "created_at": "2026-07-29T10:00:00.000000Z",
                "updated_at": "2026-07-29T10:00:00.000000Z",
                "deleted_at": null
            }
        ],
        "total": 50,
        "per_page": 15,
        "last_page": 4
    }
}
POST
/api/v1/api-best-practice
Summary: Create New API Best Practice Demo
API REQUEST PAYLOAD:
{
    "user_id": 2,
    "title": "API Security Standards",
    "email": "user@example.com",
    "password": "SecretPassword123!",
    "age": 30,
    "category": "technology",
    "status": true,
    "gender": "male",
    "description": "Comprehensive API guidelines.",
    "subscribed_topics": ["news", "updates"],
    "event_date": "2026-08-15",
    "satisfaction_score": 90
}
API RESPONSE (HTTP 201 CREATED):
{
    "status": true,
    "message": "API Best Practice created successfully.",
    "data": {
        "id": 15,
        "user_id": 2,
        "user": {
            "id": 2,
            "name": "John Doe",
            "email": "john@example.com"
        },
        "title": "API Security Standards",
        "email": "user@example.com",
        "age": 30,
        "category": "technology",
        "status": true,
        "gender": "male",
        "description": "Comprehensive API guidelines.",
        "attachment": null,
        "subscribed_topics": ["news", "updates"],
        "event_date": "2026-08-15",
        "satisfaction_score": 90,
        "created_at": "2026-07-30T10:05:00.000000Z",
        "updated_at": "2026-07-30T10:05:00.000000Z",
        "deleted_at": null
    }
}
GET
/api/v1/api-best-practice/{id}
Summary: Get Single API Best Practice Details
Path Parameter:
id = 15
API SUCCESS RESPONSE (HTTP 200 OK):
{
    "status": true,
    "message": "API Best Practice details retrieved successfully.",
    "data": {
        "id": 15,
        "user_id": 2,
        "user": {
            "id": 2,
            "name": "John Doe",
            "email": "john@example.com"
        },
        "title": "API Security Standards",
        "email": "user@example.com",
        "age": 30,
        "category": "technology",
        "status": true,
        "gender": "male",
        "description": "Comprehensive API guidelines.",
        "attachment": null,
        "subscribed_topics": ["news", "updates"],
        "event_date": "2026-08-15",
        "satisfaction_score": 90,
        "created_at": "2026-07-30T10:05:00.000000Z",
        "updated_at": "2026-07-30T10:05:00.000000Z",
        "deleted_at": null
    }
}
API ERROR RESPONSE (HTTP 404 NOT FOUND):
{
    "status": false,
    "message": "API Best Practice record not found.",
    "error": []
}
PUT
/api/v1/api-best-practice/{id}
Summary: Update API Best Practice Record
Path Parameter:
id = 15
API REQUEST PAYLOAD:
{
    "title": "Updated API Security Standards",
    "category": "technology",
    "status": true,
    "description": "Updated guidelines description details."
}
API RESPONSE (HTTP 200 OK):
{
    "status": true,
    "message": "API Best Practice updated successfully.",
    "data": {
        "id": 15,
        "user_id": 2,
        "user": {
            "id": 2,
            "name": "John Doe",
            "email": "john@example.com"
        },
        "title": "Updated API Security Standards",
        "email": "user@example.com",
        "age": 30,
        "category": "technology",
        "status": true,
        "gender": "male",
        "description": "Updated guidelines description details.",
        "attachment": null,
        "subscribed_topics": ["news", "updates"],
        "event_date": "2026-08-15",
        "satisfaction_score": 90,
        "created_at": "2026-07-30T10:05:00.000000Z",
        "updated_at": "2026-07-30T10:07:00.000000Z",
        "deleted_at": null
    }
}
DELETE
/api/v1/api-best-practice/{id}
Summary: Soft Delete API Best Practice Record
Path Parameter:
id = 15
API RESPONSE (HTTP 200 OK):
{
    "status": true,
    "message": "API Best Practice deleted successfully."
}
POST
/api/v1/api-best-practice/check-unique-email
Summary: Check Email / Code Availability
API REQUEST PAYLOAD:
{
    "email": "user@example.com",
    "ignore_id": 15
}
API RESPONSE (HTTP 200 OK – AVAILABLE):
{
    "status": true,
    "message": "Email availability status retrieved.",
    "data": {
        "email": "user@example.com",
        "is_unique": true,
        "message": "Email is available."
    }
}
API RESPONSE (HTTP 200 OK – ALREADY IN USE):
{
    "status": true,
    "message": "Email availability status retrieved.",
    "data": {
        "email": "user@example.com",
        "is_unique": false,
        "message": "Email is already in use."
    }
}
PATCH
/api/v1/api-best-practice/{id}/toggle-status
Summary: Toggle Status (Active / Inactive)
Path Parameter:
id = 15
API RESPONSE (HTTP 200 OK):
{
    "status": true,
    "message": "Record status toggled to inactive.",
    "data": {
        "id": 15,
        "user_id": 2,
        "user": {
            "id": 2,
            "name": "John Doe",
            "email": "john@example.com"
        },
        "title": "Updated API Security Standards",
        "email": "user@example.com",
        "age": 30,
        "category": "technology",
        "status": false,
        "gender": "male",
        "description": "Updated guidelines description details.",
        "attachment": null,
        "subscribed_topics": ["news", "updates"],
        "event_date": "2026-08-15",
        "satisfaction_score": 90,
        "created_at": "2026-07-30T10:05:00.000000Z",
        "updated_at": "2026-07-30T10:08:00.000000Z",
        "deleted_at": null
    }
}
POST
/api/v1/api-best-practice/{id}/restore
Summary: Restore Soft Deleted Record
Path Parameter:
id = 15
API RESPONSE (HTTP 200 OK):
{
    "status": true,
    "message": "Record restored successfully.",
    "data": {
        "id": 15,
        "user_id": 2,
        "user": {
            "id": 2,
            "name": "John Doe",
            "email": "john@example.com"
        },
        "title": "Updated API Security Standards",
        "email": "user@example.com",
        "age": 30,
        "category": "technology",
        "status": false,
        "gender": "male",
        "description": "Updated guidelines description details.",
        "attachment": null,
        "subscribed_topics": ["news", "updates"],
        "event_date": "2026-08-15",
        "satisfaction_score": 90,
        "created_at": "2026-07-30T10:05:00.000000Z",
        "updated_at": "2026-07-30T10:09:00.000000Z"
    }
}

6. Form Request Validation Rules Matrix

Field Name Store Rules Update Rules Constraints & Enums 
user_id required | integer sometimes | required Must exist in users.id 
title required | string sometimes | required Min 3, Max 255 chars 
email required | email sometimes | required Valid email address syntax 
password required | string nullable | string Min 8, Max 100 chars (Bcrypt hashed) 
age required | integer sometimes | required Numeric range: 1 to 120 
category required | string sometimes | required In: education, technology, finance, lifestyle 
status nullable | boolean nullable | boolean Boolean true/false (1/0) 
gender required | string sometimes | required In: male, female, other 
attachment nullable | file | image nullable | file | image Max size: 2048 KB (2MB) 
subscribed_topics required | array sometimes | required Min 1 array item in: news, events, offers, updates 
event_date required | date sometimes | required Valid ISO Date string (YYYY-MM-DD) 
satisfaction_score required | integer sometimes | required Numeric range: 0 to 100 

7. OpenAPI/SwaggerDocumentationIntegration

Themoduleleveragesdarkaonline/l5-swaggerwithnativePHP8OpenApi\Attributes(suchas#[OA\Get],#[OA\Post], #[OA\RequestBody], and #[OA\Response]).

Generating and Viewing API Documentation:

1.Run command to re-generate Swagger JSON spec:
php artisan l5-swagger:generate

2.
Access interactive Swagger UI in browser:
http://localhost/CodeStandardDemo/public/api/documentation

8. Guidelines for Module Developers 

  • Always return responses using ApiResponseTrait: Do not return raw arrays or custom response helpers. 
  • Isolate validation logic: Never perform inline validation inside controller methods; create dedicated Form Request classes. 
  • Always use API Resources: Protect database structure by mapping outputs through API Resource transformers. 
  • Include Swagger Annotations: Maintain accurate Swagger attributes for all endpoints created in new modules. 
  • Enforce Soft Deletes: Enable SoftDeletes trait on Eloquent models for sensitive business data. 

Leave a Reply

Your email address will not be published. Required fields are marked *