# REST Services

This section contains comprehensive documentation for REST service operations in FlexBase applications. Each document demonstrates the complete flow from API controller to database operations, including event publishing and subscriber processing.

## Available REST Operations

### **Communication Architecture**

* [**REST Client Communication**](https://github.com/sumeru-flexbase/flexbase-docs/blob/main/solution-structure/getting-started/features/rest-services/rest-client-communication.md) - Complete communication flow explanation
* DTOs vs Request/Response Objects distinction
* Mapping between internal and external contracts
* RESTClient implementation patterns
* Error handling and resilience strategies

### **Insert Operations**

* [**Insert Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/insert-example) - `AddToShipping` flow demonstrating POST operations
* Complete flow from POST request to event publishing
* PreBus validation pipeline with business rules
* Command handler processing and domain logic
* Event-driven architecture with subscribers
* RESTClient integration for external communication

### **Update Operations**

* [**Update Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/update-example) - `UpdateShipping` flow demonstrating PUT operations
* Entity lookup and validation before updating
* PreBus validation with business rules
* Domain model state management
* Event publishing for change notifications
* RESTClient integration for external updates

### **Query Operations**

* [**Get By ID Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/get-by-id-example) - `GetShippingInfoById` flow demonstrating single entity retrieval
* Fast indexed lookup by unique identifier
* AutoMapper for entity-to-DTO transformation
* Error handling with 404 responses
* Optimized for single entity details
* RESTClient integration for external data
* [**Get List Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/get-list-example) - `GetShippingDetails` flow demonstrating list retrieval
* Simple `IEnumerable<T>` without pagination
* Optimized for dropdown/lookup scenarios
* Lightweight data transfer
* Fast loading for small datasets
* RESTClient integration for external lists
* [**Get Paged List Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/get-paged-list-example) - `GetShippingPagedList` flow demonstrating paginated retrieval
* `FlexiPagedList<T>` with pagination metadata
* Optimized for data grids and large datasets
* Built-in pagination with page numbers and sizes
* Rich metadata for frontend integration
* RESTClient integration for external pagination
* [**Get Single Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/get-single-example) - `GetShippingSingle` flow demonstrating flexible single entity retrieval
* Multiple criteria for entity identification
* Flexible filtering beyond just ID
* Business logic for complex lookups
* Alternative key support (tracking numbers, order IDs, etc.)
* RESTClient integration for external lookups

### **Delete Operations**

* [**Delete Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/delete-example) - `DeleteShipping` flow demonstrating hard delete operations
* Physical removal from database
* PreBus validation before deletion
* Event publishing for cleanup operations
* Audit trail considerations
* RESTClient integration for external deletions
* [**Soft Delete Example**](https://docs.flexbase.in/solution-structure/getting-started/features/rest-services/soft-delete-example) - `SoftDeleteShipping` flow demonstrating soft delete operations
* Data preservation with deletion flag
* Recovery capabilities
* Complete audit trail
* Query filtering for soft-deleted items
* RESTClient integration for external soft deletes

## REST Service Architecture

### **Complete Communication Flow Pattern**

```
External System → RESTClient → Request DTO → Mapping → Internal DTO → Controller → Service → Domain → Database
                ↑                                                                                    ↓
External System ← RESTClient ← Response DTO ← Mapping ← Internal DTO ← Controller ← Service ← Domain ← Database
```

### **Internal Flow Pattern (Write Operations)**

```
HTTP Request → Controller → Service → PreBus Plugins → Command Handler → Domain Model → Database → Event Publishing → Subscribers
```

### **Internal Flow Pattern (Read Operations)**

```
HTTP Request → Controller → Service → Query Handler → Database → AutoMapper → Response
```

### **External Communication Pattern**

```
Internal DTO → Mapping → Request DTO → RESTClient → External System
External System → RESTClient → Response DTO → Mapping → Internal DTO
```

## Key Components

### **Controllers**

* API entry points with HTTP method attributes
* Parameter binding and validation
* Response type declarations
* Error handling and status codes

### **Services**

* Business orchestration layer
* PreBus processing for validation
* Command/Query resolution
* Result processing
* RESTClient integration

### **RESTClients**

* External system communication
* HTTP client management
* Request/Response serialization
* Error handling and resilience
* Retry policies and circuit breakers

### **Request/Response DTOs**

* External system contracts
* Serialization/Deserialization
* External validation rules
* Version management

### **Internal DTOs**

* Application contracts
* Business validation rules
* FlexBase integration
* Internal data structures

### **Mapping Layer**

* DTO to Request/Response transformation
* Field mapping and conversion
* Validation rule translation
* Contract versioning

### **PreBus System**

* Plugin-based validation pipeline
* Business rule sequences
* Data packet context
* Error collection and reporting

### **Command Handlers**

* Data processing for write operations
* Domain model interaction
* Database persistence
* Event publishing
* RESTClient integration

### **Query Handlers**

* Data retrieval for read operations
* Database query building
* AutoMapper integration
* Result transformation
* RESTClient integration

### **Domain Models**

* Business logic implementation
* State management
* Data validation
* Business rules

### **Event System**

* Asynchronous processing
* Event publishing
* Subscriber processing
* Side effects handling

## HTTP Methods and Use Cases

| HTTP Method | Use Case               | Example               | Response               |
| ----------- | ---------------------- | --------------------- | ---------------------- |
| **POST**    | Create new entity      | `AddToShipping`       | 201 Created            |
| **PUT**     | Update existing entity | `UpdateShipping`      | 200 OK                 |
| **GET**     | Retrieve data          | `GetShippingInfoById` | 200 OK / 404 Not Found |
| **DELETE**  | Remove entity          | `DeleteShipping`      | 200 OK                 |

## Response Patterns

### **Success Responses**

* **201 Created**: New entity created successfully
* **200 OK**: Operation completed successfully
* **200 OK with Data**: Query operations with results

### **Error Responses**

* **400 Bad Request**: Invalid parameters or validation errors
* **404 Not Found**: Entity not found (for GET operations)
* **500 Internal Server Error**: Server or database errors

## Data Transfer Objects (DTOs)

### **Input DTOs**

* Request body parameters for POST/PUT operations
* Query parameters for GET operations
* URL parameters for DELETE operations

### **Output DTOs**

* Response data for successful operations
* Error information for failed operations
* Pagination metadata for paged results

## Best Practices

### **Controller Design**

* Use appropriate HTTP methods
* Declare response types
* Handle errors gracefully
* Validate input parameters

### **Service Layer**

* Keep business logic in services
* Use PreBus for validation
* Handle command/query resolution
* Process results appropriately

### **Query Operations**

* Use appropriate query base classes
* Implement efficient query building
* Apply proper filtering
* Use AutoMapper for transformations

### **Command Operations**

* Validate business rules
* Handle domain logic
* Publish events appropriately
* Log operations

### **Error Handling**

* Use appropriate HTTP status codes
* Provide meaningful error messages
* Log errors appropriately
* Handle exceptions gracefully

## Performance Considerations

### **Query Optimization**

* Use database indexes effectively
* Implement efficient query building
* Apply appropriate filtering
* Use pagination for large datasets

### **Command Optimization**

* Validate early in the pipeline
* Use efficient database operations
* Implement proper logging
* Handle events asynchronously

### **Caching Strategies**

* Cache frequently accessed data
* Use appropriate cache keys
* Implement cache invalidation
* Consider cache warming

## Security Considerations

### **Input Validation**

* Validate all input parameters
* Use PreBus for business rule validation
* Sanitize user input
* Implement proper authorization

### **Data Protection**

* Use appropriate DTOs
* Implement data masking
* Handle sensitive data carefully
* Follow security best practices

## Testing Strategies

### **Unit Testing**

* Test each component independently
* Mock dependencies appropriately
* Test error scenarios
* Verify business logic

### **Integration Testing**

* Test complete flows
* Verify database operations
* Test event publishing
* Validate error handling

### **API Testing**

* Test HTTP endpoints
* Verify response formats
* Test error scenarios
* Validate security

***

**This REST Services documentation provides comprehensive guidance for implementing clean, maintainable, and scalable REST operations in FlexBase applications!** 🚀
