Skip to content

Latest commit

Β 

History

History
338 lines (280 loc) Β· 8.46 KB

File metadata and controls

338 lines (280 loc) Β· 8.46 KB

🌐 HTTP API Usage Examples

The Home Repair Cost API is fully accessible over HTTP. Here are comprehensive examples of how to call it from various languages and tools.

πŸ”‘ API Key Required

First, create an API key (no authentication needed for this endpoint):

curl -X POST "http://localhost:8000/api/v1/auth/create-key" \
  -H "Content-Type: application/json" \
  -d '{"name": "My Application"}'

Response:

{
  "api_key": "rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez",
  "name": "My Application", 
  "created_at": "2025-07-31T22:11:51.520478",
  "rate_limit": 1000
}

πŸ“‹ HTTP Endpoints

1. Health Check (No Auth Required)

curl -X GET "http://localhost:8000/api/v1/health"

2. Single Repair Cost Estimate

curl -X GET "http://localhost:8000/api/v1/repair-cost/electrical_panel_replacement?zip_code=90210&scope=average" \
  -H "X-API-Key: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez"

Response:

{
  "repair_type": "electrical_panel_replacement",
  "location": {
    "zip_code": "90210",
    "region": "Beverly Hills, CA",
    "cost_multiplier": 1.45
  },
  "cost_estimate": {
    "low": 1740,
    "average": 3045,
    "high": 4350,
    "national_base": 2100
  },
  "details": {
    "labor_hours": "6-8",
    "materials_cost_percent": 40,
    "permit_required": true,
    "urgency_level": "critical",
    "description": "Replace main electrical panel and upgrade to current code"
  },
  "factors": {
    "regional_labor_cost": "Very High",
    "material_availability": "Good", 
    "permit_complexity": "High"
  },
  "timestamp": "2025-07-31T22:11:58.461131"
}

3. Batch Repair Estimates

curl -X POST "http://localhost:8000/api/v1/repair-cost/batch" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez" \
  -d '{
    "repairs": ["pipe_leak_repair", "toilet_replacement"],
    "zip_code": "94102",
    "scope": "average"
  }'

4. Available Repair Types

curl -X GET "http://localhost:8000/api/v1/repair-types" \
  -H "X-API-Key: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez"

5. Filter by Category

curl -X GET "http://localhost:8000/api/v1/repair-types?category=Electrical" \
  -H "X-API-Key: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez"

🐍 Python HTTP Examples

Using requests library:

import requests

# Configuration
API_KEY = "rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez"
BASE_URL = "http://localhost:8000"
headers = {"X-API-Key": API_KEY}

# Single repair cost
response = requests.get(
    f"{BASE_URL}/api/v1/repair-cost/water_heater_replacement",
    params={"zip_code": "90210", "scope": "average"},
    headers=headers
)
cost_data = response.json()
print(f"Average cost: ${cost_data['cost_estimate']['average']:,}")

# Batch request
batch_data = {
    "repairs": ["electrical_panel_replacement", "roof_leak_repair"],
    "zip_code": "94102",
    "scope": "comprehensive"
}
response = requests.post(
    f"{BASE_URL}/api/v1/repair-cost/batch",
    json=batch_data,
    headers=headers
)
estimates = response.json()['estimates']
total = sum(est['cost_estimate']['average'] for est in estimates)
print(f"Total cost: ${total:,}")

🟨 JavaScript/Node.js Examples

Using fetch:

const API_KEY = "rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez";
const BASE_URL = "http://localhost:8000";

// Single repair cost
async function getRepairCost(repairType, zipCode) {
    const response = await fetch(
        `${BASE_URL}/api/v1/repair-cost/${repairType}?zip_code=${zipCode}&scope=average`,
        {
            headers: {
                'X-API-Key': API_KEY
            }
        }
    );
    return await response.json();
}

// Batch request
async function getBatchCosts(repairs, zipCode) {
    const response = await fetch(
        `${BASE_URL}/api/v1/repair-cost/batch`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-API-Key': API_KEY
            },
            body: JSON.stringify({
                repairs: repairs,
                zip_code: zipCode,
                scope: 'average'
            })
        }
    );
    return await response.json();
}

// Usage
getRepairCost('electrical_panel_replacement', '90210')
    .then(data => console.log(`Cost: $${data.cost_estimate.average}`));

πŸ“± React/Frontend Example

import React, { useState, useEffect } from 'react';

function RepairCostEstimator() {
    const [cost, setCost] = useState(null);
    const API_KEY = "rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez";
    
    useEffect(() => {
        fetch(
            `http://localhost:8000/api/v1/repair-cost/electrical_panel_replacement?zip_code=90210&scope=average`,
            {
                headers: { 'X-API-Key': API_KEY }
            }
        )
        .then(response => response.json())
        .then(data => setCost(data));
    }, []);
    
    return (
        <div>
            {cost && (
                <div>
                    <h3>{cost.repair_type.replace('_', ' ')}</h3>
                    <p>Average Cost: ${cost.cost_estimate.average.toLocaleString()}</p>
                    <p>Region: {cost.location.region}</p>
                </div>
            )}
        </div>
    );
}

πŸ”§ Other Languages

PHP Example:

<?php
$api_key = "rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez";
$base_url = "http://localhost:8000";

$headers = [
    "X-API-Key: $api_key",
    "Content-Type: application/json"
];

// Single repair cost
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$base_url/api/v1/repair-cost/roof_leak_repair?zip_code=90210&scope=average");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo "Cost: $" . number_format($data['cost_estimate']['average']) . "\n";
?>

Go Example:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    apiKey := "rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez"
    baseURL := "http://localhost:8000"
    
    // Create HTTP client
    client := &http.Client{}
    
    // Single repair cost
    req, _ := http.NewRequest("GET", 
        baseURL+"/api/v1/repair-cost/electrical_panel_replacement?zip_code=90210&scope=average", 
        nil)
    req.Header.Set("X-API-Key", apiKey)
    
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    
    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    
    costEstimate := result["cost_estimate"].(map[string]interface{})
    fmt.Printf("Cost: $%.0f\n", costEstimate["average"])
}

🌐 From Any HTTP Tool

Postman Collection:

  • Base URL: http://localhost:8000
  • Headers: X-API-Key: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez

wget Example:

wget --header="X-API-Key: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez" \
     -qO- "http://localhost:8000/api/v1/repair-cost/water_heater_replacement?zip_code=94102&scope=average"

HTTPie Example:

http GET localhost:8000/api/v1/repair-cost/toilet_replacement \
     zip_code==90210 scope==average \
     X-API-Key:rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez

πŸ”’ Authentication & Headers

Required Headers:

  • X-API-Key: Your generated API key
  • Content-Type: application/json (for POST requests)

API Key Format:

  • Always starts with rca_
  • 32 character random string
  • Example: rca_IhxO7zJPfZYtRDk1OvUeUa4DClArGaez

πŸ“Š Response Format

All successful responses return JSON with:

  • Status Code: 200 (success)
  • Content-Type: application/json
  • Body: Structured JSON data

Error Responses:

  • 401: Invalid/missing API key
  • 404: Repair type not found
  • 400: Invalid zip code or scope
  • 429: Rate limit exceeded
  • 500: Internal server error

🌍 Network Access

The API is currently running on:

  • Local: http://localhost:8000
  • Network: http://0.0.0.0:8000 (accessible from other devices on your network)

Make it accessible from other machines:

# If you want external access, the API is already bound to 0.0.0.0:8000
# Other devices on your network can access it via:
# http://YOUR_IP_ADDRESS:8000

πŸš€ Production Deployment

For production use, deploy with:

  • HTTPS enabled
  • Domain name instead of localhost
  • Load balancer for scaling
  • API gateway for rate limiting

Example production URL: https://api.yourcompany.com/repair-costs/


βœ… The API is fully HTTP-compatible and can be called from any language or tool that supports HTTP requests!