Logistics Microservice API Integration Guide - Wiz-DevTech/prettygirllz GitHub Wiki

Logistics Microservice API Integration Guide

Overview

The Logistics Microservice provides REST APIs for managing delivery operations with integrated fraud detection. This document outlines the API design, endpoints, data contracts, and integration patterns for frontend and other services.

API Design Principles

REST Architecture

  • Stateless: Each request contains all necessary information
  • Resource-based URLs: Clear, hierarchical URI structure
  • HTTP Methods: Proper use of GET, POST, PATCH for operations
  • Status Codes: Meaningful HTTP status codes

Versioning Strategy

  • URL Path Versioning: /api/v1/ prefix for all endpoints
  • Backward Compatibility: Maintain compatibility within major versions
  • Deprecation Policy: 6-month notice for breaking changes

Base Configuration

Server Details

  • Base URL: http://localhost:8080/api
  • Protocol: HTTP/HTTPS
  • Content-Type: application/json
  • Character Encoding: UTF-8

Authentication & Authorization

Current Status

  • Authentication: Currently not implemented
  • Security: Consider implementing JWT or OAuth2 for production

Recommended Implementation

Authorization: Bearer <token>

Core API Endpoints

1. Create Delivery

Endpoint: POST /v1/deliveries

Description: Creates a new delivery with fraud detection validation

Request Body:

{
  "orderId": "ORD-12345",
  "destinationType": "HOME",
  "recipient": {
    "name": "John Doe",
    "phone": "+1234567890",
    "email": "[email protected]"
  }
}

Response (201 Created):

{
  "id": 1,
  "orderId": "ORD-12345",
  "destinationType": "HOME",
  "status": "CREATED",
  "recipient": {
    "name": "John Doe",
    "phone": "+1234567890",
    "email": "[email protected]"
  },
  "createdAt": "2025-05-16T10:00:00",
  "updatedAt": "2025-05-16T10:00:00"
}

Error Responses:

  • 400 Bad Request: Invalid input or fraud detection flag
  • 500 Internal Server Error: Server processing error

2. Get Delivery by Order ID

Endpoint: GET /v1/deliveries/{orderId}

Description: Retrieves a specific delivery by its order ID

Path Parameters:

  • orderId (string): Unique order identifier

Response (200 OK):

{
  "id": 1,
  "orderId": "ORD-12345",
  "destinationType": "HOME",
  "status": "CREATED",
  "recipient": {
    "name": "John Doe",
    "phone": "+1234567890",
    "email": "[email protected]"
  },
  "createdAt": "2025-05-16T10:00:00",
  "updatedAt": "2025-05-16T10:00:00"
}

Error Responses:

  • 404 Not Found: Delivery not found

3. Get Deliveries by Status

Endpoint: GET /v1/deliveries

Description: Retrieves deliveries filtered by status

Query Parameters:

  • status (optional): Filter by delivery status
    • Valid values: CREATED, IN_TRANSIT, DELIVERED, FAILED
    • Default: CREATED if not specified

Response (200 OK):

[
  {
    "id": 1,
    "orderId": "ORD-12345",
    "destinationType": "HOME",
    "status": "CREATED",
    "recipient": {
      "name": "John Doe",
      "phone": "+1234567890",
      "email": "[email protected]"
    },
    "createdAt": "2025-05-16T10:00:00",
    "updatedAt": "2025-05-16T10:00:00"
  }
]

Error Responses:

  • 400 Bad Request: Invalid status value

4. Update Delivery Status

Endpoint: PATCH /v1/deliveries/{orderId}/status

Description: Updates the status of a specific delivery

Path Parameters:

  • orderId (string): Unique order identifier

Query Parameters:

  • status (required): New delivery status
    • Valid values: CREATED, IN_TRANSIT, DELIVERED, FAILED

Response (200 OK):

{
  "id": 1,
  "orderId": "ORD-12345",
  "destinationType": "HOME",
  "status": "IN_TRANSIT",
  "recipient": {
    "name": "John Doe",
    "phone": "+1234567890",
    "email": "[email protected]"
  },
  "createdAt": "2025-05-16T10:00:00",
  "updatedAt": "2025-05-16T10:30:00"
}

Error Responses:

  • 400 Bad Request: Invalid status value
  • 404 Not Found: Delivery not found

Data Models

Delivery Status Enum

CREATED       - Initial status when delivery is created
IN_TRANSIT    - Delivery is being processed/shipped
DELIVERED     - Successfully delivered
FAILED        - Delivery failed

Destination Type Enum

HOME          - Home delivery
BUSINESS      - Business/office delivery
PICKUP_POINT  - Collection point delivery

Error Handling

Standard Error Response Format

{
  "timestamp": "2025-05-16T10:00:00",
  "status": 400,
  "error": "Bad Request",
  "message": "Delivery request flagged for fraud",
  "path": "/api/v1/deliveries"
}

Error Codes & Messages

  • 400 Bad Request: Invalid input data or fraud detection
  • 404 Not Found: Resource not found
  • 500 Internal Server Error: Server processing error

Integration Patterns

Synchronous API Calls

// Create delivery example
const response = await fetch('/api/v1/deliveries', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    orderId: 'ORD-12345',
    destinationType: 'HOME',
    recipient: {
      name: 'John Doe',
      phone: '+1234567890',
      email: '[email protected]'
    }
  })
});

const delivery = await response.json();

Error Handling Pattern

try {
  const response = await fetch('/api/v1/deliveries/ORD-12345');
  
  if (!response.ok) {
    if (response.status === 404) {
      console.log('Delivery not found');
    } else if (response.status === 400) {
      console.log('Invalid request');
    }
    return;
  }
  
  const delivery = await response.json();
  // Process delivery data
} catch (error) {
  console.error('Network error:', error);
}

CORS Configuration

Current Setup

  • CORS configuration should be added for cross-origin requests
  • Consider allowing specific origins in production

Recommended CORS Headers

cors:
  allowed-origins: 
    - "http://localhost:3000"
    - "https://yourdomain.com"
  allowed-methods: GET,POST,PUT,PATCH,DELETE,OPTIONS
  allowed-headers: "*"

Performance Considerations

Caching Strategy

  • Redis Integration: Configured but implementation needed
  • HTTP Caching: Consider adding cache headers for GET requests
  • Database Queries: Optimized with proper indexing

Rate Limiting

  • Currently not implemented
  • Recommended for production use
  • Consider per-IP or per-user limits

Pagination

  • Not currently implemented
  • Recommended for large datasets
  • Standard format: ?page=1&size=20

Kafka Integration

Message Publishing

// Example: Publishing delivery events
@EventListener
public void handleDeliveryCreated(DeliveryCreatedEvent event) {
    kafkaTemplate.send("delivery-events", event);
}

Topic Structure

  • delivery-events: Delivery lifecycle events
  • fraud-alerts: Fraud detection notifications

Testing

API Testing Examples

Create Delivery Test:

curl -X POST http://localhost:8080/api/v1/deliveries \
  -H "Content-Type: application/json" \
  -d '{
    "orderId": "TEST-001",
    "destinationType": "HOME",
    "recipient": {
      "name": "Test User",
      "phone": "+1234567890",
      "email": "[email protected]"
    }
  }'

Get Delivery Test:

curl http://localhost:8080/api/v1/deliveries/TEST-001

Future Enhancements

Planned Features

  1. Authentication & Authorization: JWT-based security
  2. Real-time Updates: WebSocket support for status changes
  3. Bulk Operations: Batch create/update endpoints
  4. Advanced Filtering: More query parameters
  5. File Upload: Support for delivery documents
  6. Audit Trail: Track all changes
  7. GraphQL Support: Alternative API format

Documentation & Tools

API Documentation

  • Swagger/OpenAPI: Auto-generated documentation
  • Postman Collection: Pre-configured API calls
  • Example Requests: Sample integration code

Development Tools

  • H2 Console: Available in development mode
  • Actuator Endpoints: Health checks and metrics
  • Debug Logging: Configurable log levels

Contact & Support

  • API Documentation: [Swagger/OpenAPI URL]
  • Support Team: [support-email]
  • Issue Tracking: [JIRA/GitHub URL]
  • API Changes: [changelog-url]
⚠️ **GitHub.com Fallback** ⚠️