5 minute read

Project Overview

The Smart Truck Rating API is a production REST API developed for Mov3ment's RateYourTruck platform. It evaluates commercial trucks for environmental and operational efficiency based on a comprehensive rating scheme created by Mark Gjerek. The API accepts detailed vehicle specifications and returns star ratings along with specific recommendations for improvement. Deployed on Azure Container Apps, it serves real-time rating calculations for fleet operators across Australia.

Technology: Python 3.11, FastAPI, SQLAlchemy, SQLite, Pydantic, Uvicorn, Docker, Azure Container Apps

Testing Tools: Jupyter Notebook, Pandas for test case management

The Challenge

There's been no standard way to compare truck fuel efficiency or emissions in Australia. The rating scheme addresses this by providing operators a simple star rating that rewards decisions on features and equipment that reduce energy use and emissions, not just the truck brand or powertrain. My role was translating this sophisticated rating logic into a flexible, maintainable API that could handle 40+ vehicle configuration parameters and provide actionable advice.

Key Features

  • API key authentication with expiration tracking and client name validation.
  • Timestamp header validation for additional request security.
  • Dynamic scoring based on database-configured weights (pollution standards, efficiency features, aerodynamics, smart systems).
  • Star rating generation with percentage breakdowns across categories.
  • Intelligent advice system prioritizing retrofits over new vehicle purchases.
  • Request logging to SQLite database via SQLAlchemy for audit trail.
  • Comprehensive validation of 40+ input fields using Pydantic schemas.
  • Health check endpoint for availability monitoring.

Architecture & Components

SmartTruckRating/
├── app/
│   ├── main.py                   # FastAPI app setup and middleware
│   ├── scoring_logic.py          # Core logic for vehicle scoring
│   ├── rating_logic.py           # Star rating conversion
│   ├── advice_gen.py             # Recommendation generation
│   ├── schemas.py                # Pydantic models for validation
│   ├── authentication.py         # API key and timestamp validation
│   ├── database.py               # SQLAlchemy DB setup
│   ├── model_log.py              # Request logging model
│   ├── routers/
│   │   └── rating.py             # Rating endpoints
│   └── data/                     # (API keys managed in database)
├── tests/
│   ├── test_cases.csv            # Test scenarios
│   └── run_tests.ipynb           # Jupyter notebook for validation
├── SQL_Database/                 # Database schema and setup
├── Dockerfile                    # Container build recipe
├── dev_requirements.txt          # Local development dependencies
└── container_requirements.txt    # Production container dependencies

Design Decisions

Database-Driven Configuration

One of my favorite design choices was making the scoring logic configurable through database tables. I started by organizing all the scoring variables in CSV format during development to get a clear view of the weights and relationships, then created SQL tables to store these variables for production. This allows the operations team to update scoring weights, add new features, or adjust rating thresholds through direct database updates without code changes. It's practical and maintainable.

Modular Business Logic

The scoring, rating, and advice generation are separated into distinct modules. This makes it easy to test individual components and modify one aspect without affecting others.

Request Validation

With 40+ fields in the request body, Pydantic's automatic validation prevents bad data from reaching the business logic. If a field is missing or the wrong type, the API returns a clear error before any processing happens.

Example API Request

import requests
from datetime import datetime

url = "https://api.rateyourtruck.com.au/rating/single"
headers = {
    "x-api-key": "your-api-key",
    "timestamp": datetime.utcnow().isoformat() + "Z",
    "Content-Type": "application/json"
}

payload = {
    "user_name": "Fleet Manager",
    "user_email": "manager@example.com",
    "duty_cycle": "Mostly Urban",
    "vehicle_type": "Rigid (Urban or regional)",
    "make": "Volvo",
    "model": "FE",
    "yom": 2025,
    "pollution": "Euro VI",
    "transmission": "Automated manual transmission",
    "eco_mode": True,
    "lrr": True,
    "telematics": True,
    # ... 30+ more configuration options
}

response = requests.post(url, json=payload, headers=headers)
result = response.json()

print(f"Rating: {result['rating']} stars")
print(f"Pollution Score: {result['percent_pollution']}%")
print(f"Top Advice: {result['advice']['Advice 1']}")

Deployment & Cloud Infrastructure

The API is containerized with Docker and deployed to Azure Container Apps. This was my first time working with Azure cloud services, so it was a good learning experience. I explored Azure's container orchestration, environment variables management, networking configuration, and monitoring capabilities. Azure Container Apps made it straightforward to deploy without managing the underlying infrastructure, and the API scales automatically based on load.

Deployment Process

# Build container image
docker build -t smarttruckrating -f Dockerfile .

# Deploy to Azure Container Apps
# (via Azure Portal or Azure CLI)
az containerapp create \
  --name smarttruckrating \
  --resource-group mov3ment-rg \
  --image smarttruckrating:latest \
  --environment production

Testing Strategy

I built a comprehensive test suite using Jupyter Notebooks. Test cases are defined in CSV files with expected outputs, making it easy to verify that scoring logic changes don't break existing behavior. The notebook loads test scenarios, calls the API, and compares actual vs. expected results with detailed reporting.

Performance Insights

  • Response Time: API optimized with async routes and Uvicorn ASGI server for fast response times.
  • Validation Speed: Pydantic's compiled validators handle 40+ field validation efficiently.
  • Scaling: Azure Container Apps provides automatic horizontal scaling based on HTTP traffic.
  • Logging: Every request tracked with timestamp, client name, and response data for debugging and analytics.
  • Security: Multi-layer authentication (API keys + timestamp validation) prevents unauthorized access.

Skills I Practiced

This project gave me hands-on experience with several technical areas:

  • API Design: Structuring endpoints, choosing HTTP methods, designing clear request/response schemas.
  • Security Implementation: API key authentication, timestamp validation, keeping secrets out of code.
  • Cloud Deployment: Working with Azure Container Apps, managing container images, configuring cloud resources.
  • Azure Platform: Container services, networking, environment management, and monitoring.
  • Data Modeling: Translating complex rating logic into flexible, maintainable code.
  • Requirements Gathering: Working with stakeholders to understand the rating scheme, identify API functionality needs, and clarify edge cases.
  • Product Management: Developing and maintaining a product backlog to guide development priorities and future enhancements.
  • Stakeholder Communication: Translating technical concepts for non-technical stakeholders and gathering feedback on API behavior.

Building production APIs and deploying to cloud infrastructure was relatively new territory for me. My mechanical engineering background helped me understand the vehicle characteristics and efficiency factors, but the API development and cloud deployment side required focus and effort. FastAPI's excellent documentation and Azure's straightforward Container Apps service made it manageable.

Practical Applications

The RateYourTruck platform (powered by this API) helps:

  • Fleet managers assess their vehicles' environmental impact.
  • Companies evaluate new vehicle purchases with objective data.
  • Operators prioritize efficiency upgrades and retrofits.
  • Organizations meet environmental reporting requirements.
  • Supply chain partners demonstrate fleet improvements to customers.

Simplified Example Repository

I created a public example repository that demonstrates similar architectural patterns with simplified logic: FastAPI_VehicleRating

That repo uses basic scoring based on vehicle age, mileage, and engine size (completely made-up logic), but demonstrates the same patterns:

  • FastAPI routers and Pydantic schemas
  • CSV-based configuration (the example uses CSV files for simplicity)
  • API key authentication
  • Request logging with SQLAlchemy
  • Docker deployment

The actual Smart Truck Rating API uses database tables for all configuration (scoring variables, API keys, rating thresholds) and a far more sophisticated scoring model with dozens of weighted features across multiple categories, but the fundamental structure is the same.

Project Links

Simplified Example Repository
RateYourTruck Platform