c_agri_trade/project_code/docs/runbooks/API_INTEGRATION_GUIDE.md

6.6 KiB

Agriculture Trading Backoffice (ATB) — API Integration & Developer Guide

Field Value
Product Agriculture Trading Backoffice (ATB)
Release Version v1.0.0 (Production / UAT Release)
Governed Standard OpenAPI 3.0 / REST standard (UP-AI v1.5 / tech-profile.yaml)
Document Path 04_generated_documentation/08_review_ready_baselines/02_handover_package/API_INTEGRATION_GUIDE.md
Interactive Docs /docs (Swagger UI), /redoc (ReDoc)

1. Architectural Overview & Protocols

The Agriculture Trading Backoffice (ATB) API provides a modern, RESTful HTTP interface designed for integration with client web portals, mobile yard supervisor devices, automated weighbridge digital indicators, and third-party enterprise ERP systems.

1.1 Base URLs

  • Production Gateway: https://trading.company.com/api
  • UAT Staging Gateway: https://uat.trading.company.com/api
  • Local Development: http://localhost:8000/api

1.2 Mandatory Request Headers

Every API request to tenant-partitioned services requires two standard headers:

Authorization: Bearer <OIDC_ACCESS_TOKEN>
X-Tenant-ID: 7b841a22-3112-4f2a-b605-649fae61cb01
Content-Type: application/json
Accept: application/json

2. Authentication & Token Exchange

ATB implements standard OAuth 2.0 / OpenID Connect (OIDC) with PKCE via Keycloak 26.

2.1 Token Acquisition (Client Credentials / Password Flow)

To obtain an access token programmatically:

curl -X POST "https://auth.company.com/auth/realms/atb/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=password" \
  -d "client_id=atb-portal" \
  -d "client_secret=$CLIENT_SECRET" \
  -d "username=buyer@alpha-agri.com" \
  -d "password=$USER_PASSWORD"

Token Response:

{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "eyJhbGciOiJSUzI1NiIs...",
  "scope": "openid email profile"
}

3. Core API Endpoint Reference

3.1 Mandi Market Desk (/api/market/*)

  • POST /api/market/arrivals: Record morning mandi arrivals (Commodity, Mandi Name, Arrival Quantity in Quintals, Modal Price).
  • GET /api/market/rates?commodity=SOYBEAN: Retrieve active APMC rate bands and modal prices.

3.2 Sauda Procurement Contracts (/api/procurement/*)

  • POST /api/procurement/contracts: Create a binding sauda procurement contract (Supplier ID, Commodity, Quantity, Rate per Quintal, Delivery Type: LOOSE or BAGGED, Mandi Tax inclusion).
  • POST /api/procurement/contracts/{id}/approve: Managerial approval of contract terms.
  • GET /api/procurement/contracts: Filter contracts by status (DRAFT, APPROVED, PARTIALLY_DELIVERED, FULFILLED).

3.3 Gate Inward & Weighbridge (/api/receiving/*)

  • POST /api/receiving/gate-in: Record truck arrival at the mandi yard gate (Vehicle Number, Driver Name, Sauda Reference).
  • POST /api/receiving/weighbridge/gross: Capture digital weighbridge gross weight (Vehicle + Commodity).
  • POST /api/receiving/weighbridge/tare: Capture tare weight (Empty Vehicle) and compute net commodity weight.
  • GET /api/receiving/tickets/{id}: Retrieve weighbridge receipt with scale calibration hash.

3.4 Quality Lab Assay & Lot Grading (/api/quality/*)

  • POST /api/quality/assays: Record moisture analysis, foreign admixture, and damaged kernel percentages.
  • POST /api/quality/deductions/calculate: Compute automatic weight/price deductions based on tenant policy tolerance thresholds.
  • POST /api/quality/lots/release: Approve lot for warehouse stack unloading or issue rejection gate pass.

3.5 Godown Inventory Ledger (/api/inventory/*)

  • GET /api/inventory/balances?godown_id={id}: Real-time stock balance by commodity and stack number.
  • POST /api/inventory/transfers: Issue inter-godown transfer order.
  • POST /api/inventory/write-offs: Partner-authorized damage or spillage stock adjustment.

3.6 Sales Contracts & Dispatch Board (/api/sales/*, /api/logistics/*)

  • POST /api/sales/contracts: Book customer sales order with real-time credit limit exposure verification.
  • POST /api/logistics/dispatch: Allocate released inventory lots to outward shipment.
  • POST /api/logistics/bilty: Generate digital bilty manifest with GST E-way bill number and driver details.

3.7 Financial Settlement & Receivables (/api/finance/*)

  • GET /api/finance/receivables/aging: Generate customer credit aging report (0-15, 16-30, 31-60, 60+ days).
  • POST /api/finance/payments/receive: Record customer payment and match against outstanding sales invoices.
  • POST /api/finance/payables/vouchers: Generate supplier payment voucher for inward sauda.
  • POST /api/finance/expenses: Record mandi market fee, cess, labour charges, and freight expenses.

3.8 Master Data & Operating Policies (/api/master-data/*, /api/policies/*)

  • POST /api/master-data/commodities: Register new commodity with standard moisture and test-weight specs.
  • POST /api/master-data/counterparties: Register suppliers/customers with mandatory PAN and GSTIN validation.
  • GET /api/policies: Retrieve tenant operating thresholds (credit tolerance, moisture rejection cutoffs).

4. Bruno Automated API Collections

All delivered APIs are accompanied by version-controlled Bruno collections stored under project_code/docs/api/bruno/.

4.1 Running the Entire API Suite via Bruno CLI

Install Bruno CLI:

npm install -g @usebruno/cli

Execute collections against your deployment environment:

cd project_code
bru run docs/api/bruno --env uat

5. Standard Error Response Structure

In accordance with RFC 7807 (Problem Details), all error responses follow a uniform JSON schema:

{
  "error": "INSUFFICIENT_STOCK",
  "message": "Requested dispatch quantity 250.00 Qtl exceeds available released stock 180.50 Qtl in Godown Stack G-04",
  "status": 422,
  "timestamp": "2026-10-13T09:15:00Z",
  "trace_id": "req-9b81a20-3321"
}

Common HTTP Status Codes

  • 200 OK: Request succeeded.
  • 201 Created: Resource successfully created.
  • 400 Bad Request: Missing mandatory parameters or invalid tenant context.
  • 401 Unauthorized: Missing, expired, or malformed JWT bearer token.
  • 403 Forbidden: Insufficient role permissions or tenant suspended.
  • 404 Not Found: Target entity does not exist within the active tenant.
  • 422 Unprocessable Entity: Business invariant violation (negative stock, credit limit exceeded, assay failure).
  • 500 Internal Server Error: Unhandled exception (escalates to platform on-call).