API Usage Examples

This document provides practical examples of using the Django API app with a sample project.

Basic API Usage

Retrieving a List of Inverters

Request:

GET /api/v1/renewableassets/inverter/

Response:

{
  "count": 25,
  "num_pages": 2,
  "current_page": 1,
  "has_next": true,
  "has_previous": false,
  "model": {
    "app_label": "renewableassets",
    "model_name": "inverter",
    "verbose_name": "inverter",
    "verbose_name_plural": "inverters"
  },
  "results": [
    {
      "id": 1,
      "name": "SolarMax 5000",
      "asset_id": 101,
      "commissioned": "2025-05-10T14:23:11.123Z",
      "decommissioned": null,
      "warranty_start": "2025-05-10",
      "warranty_end": "2030-05-10",
      "serial_number": "INV-001-2025",
      "device_model_id": 5,
      "location_id": 3,
      "capacity_dc": 5500.0,
      "capacity_ac": 5000.0
    },
    {
      "id": 2,
      "name": "PowerFlex 3000",
      "asset_id": 102,
      "commissioned": "2025-05-11T10:12:23.456Z",
      "decommissioned": null,
      "warranty_start": "2025-05-11",
      "warranty_end": "2030-05-11",
      "serial_number": "INV-002-2025",
      "device_model_id": 6,
      "location_id": 4,
      "capacity_dc": 3300.0,
      "capacity_ac": 3000.0
    }
  ],
  "api_version": "v1"
}

Retrieving a Single Inverter

Request:

GET /api/v1/renewableassets/inverter/1/

Response:

{
  "model": {
    "app_label": "renewableassets",
    "model_name": "inverter",
    "verbose_name": "inverter"
  },
  "data": {
    "id": 1,
    "name": "SolarMax 5000",
    "asset_id": 101,
    "commissioned": "2025-05-10T14:23:11.123Z",
    "decommissioned": null,
    "warranty_start": "2025-05-10",
    "warranty_end": "2030-05-10",
    "serial_number": "INV-001-2025",
    "device_model_id": 5,
    "location_id": 3,
    "capacity_dc": 5500.0,
    "capacity_ac": 5000.0
  },
  "api_version": "v1"
}

Creating a New Inverter

Request:

POST /api/v1/renewableassets/inverter/new/
Content-Type: application/json

{
  "name": "EcoVolt 4000",
  "asset_id": 103,
  "commissioned": "2025-05-14T08:45:12.789Z",
  "warranty_start": "2025-05-14",
  "warranty_end": "2030-05-14",
  "serial_number": "INV-003-2025",
  "device_model_id": 7,
  "location_id": 5,
  "capacity_dc": 4400.0,
  "capacity_ac": 4000.0
}

Response:

{
  "success": true,
  "id": 26,
  "data": {
    "id": 26,
    "name": "EcoVolt 4000",
    "asset_id": 103,
    "commissioned": "2025-05-14T08:45:12.789Z",
    "decommissioned": null,
    "warranty_start": "2025-05-14",
    "warranty_end": "2030-05-14",
    "serial_number": "INV-003-2025",
    "device_model_id": 7,
    "location_id": 5,
    "capacity_dc": 4400.0,
    "capacity_ac": 4000.0
  },
  "api_version": "v1"
}

Updating an Inverter

Request:

POST /api/v1/renewableassets/inverter/26/edit/
Content-Type: application/json

{
  "name": "EcoVolt 4500",
  "asset_id": 103,
  "commissioned": "2025-05-14T08:45:12.789Z",
  "warranty_start": "2025-05-14",
  "warranty_end": "2030-05-14",
  "serial_number": "INV-003-2025",
  "device_model_id": 7,
  "location_id": 5,
  "capacity_dc": 4500.0,
  "capacity_ac": 4100.0
}

Response:

{
  "success": true,
  "id": 26,
  "data": {
    "id": 26,
    "name": "EcoVolt 4500",
    "asset_id": 103,
    "commissioned": "2025-05-14T08:45:12.789Z",
    "decommissioned": null,
    "warranty_start": "2025-05-14",
    "warranty_end": "2030-05-14",
    "serial_number": "INV-003-2025",
    "device_model_id": 7,
    "location_id": 5,
    "capacity_dc": 4500.0,
    "capacity_ac": 4100.0
  },
  "api_version": "v1"
}

Deleting an Inverter

Request:

POST /api/v1/renewableassets/inverter/26/delete/

Response:

{
  "success": true,
  "message": "inverter with ID 26 successfully deleted",
  "api_version": "v1"
}

Pagination

Request:

GET /api/v1/renewableassets/inverter/?page=2&page_size=10

Response:

{
  "count": 25,
  "num_pages": 3,
  "current_page": 2,
  "has_next": true,
  "has_previous": true,
  "model": {
    "app_label": "renewableassets",
    "model_name": "inverter",
    "verbose_name": "inverter",
    "verbose_name_plural": "inverters"
  },
  "results": [
    // Second page of inverters (10 items)
  ],
  "api_version": "v1"
}

Authentication and Error Handling

Unauthorized Access

If a user attempts to access the API without being authenticated:

Request:

GET /api/v1/renewableassets/inverter/

Response:

HTTP/1.1 302 Found
Location: /accounts/login/?next=/api/v1/renewableassets/inverter/

Insufficient Permissions

If a user is authenticated but lacks the required permissions:

Request:

GET /api/v1/renewableassets/inverter/

Response:

{
  "success": false,
  "error": "Permission Denied",
  "message": "You do not have permission to perform this action",
  "api_version": "v1"
}

Validation Errors

When submitting invalid data:

Request:

POST /api/v1/renewableassets/inverter/new/
Content-Type: application/json

{
  "name": "",
  "capacity_dc": "invalid"
}

Response:

{
  "success": false,
  "errors": {
    "name": ["This field is required."],
    "asset_id": ["This field is required."],
    "capacity_dc": ["A valid number is required."]
  },
  "api_version": "v1"
}

Working with Related Objects

Accessing Category Inverters

Request:

GET /api/v1/renewableassets/category/4/

Response:

{
  "model": {
    "app_label": "renewableassets",
    "model_name": "category",
    "verbose_name": "category"
  },
  "data": {
    "id": 4,
    "name": "Solar Equipment",
    "description": "Solar inverters and related components",
    "is_active": true
  },
  "api_version": "v1"
}

Using the API from JavaScript

Here's a simple example of using the API with JavaScript:


      
// Function to fetch inverters
async function getInverters(page = 1) {
  try {
    const response = await fetch(`/api/v1/renewableassets/inverter/?page=${page}`, {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Accept': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching inverters:', error);
    return null;
  }
}

// Function to create an inverter
async function createInverter(inverterData) {
  try {
    const response = await fetch('/api/v1/renewableassets/inverter/new/', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-CSRFToken': getCsrfToken()
      },
      body: JSON.stringify(inverterData)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error creating inverter:', error);
    return null;
  }
}

// Helper function to get CSRF token
function getCsrfToken() {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; csrftoken=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
  return null;
}

// Example usage
async function displayInverters() {
  const invertersData = await getInverters();
  if (invertersData && invertersData.results) {
    const invertersContainer = document.getElementById('inverters-container');
    invertersContainer.innerHTML = '';
    
    invertersData.results.forEach(inverter => {
      const inverterElement = document.createElement('div');
      inverterElement.className = 'inverter-item';
      inverterElement.innerHTML = `
        <h3>${inverter.name}</h3>
        <p>Serial Number: ${inverter.serial_number}</p>
        <p>Capacity DC: ${inverter.capacity_dc} W</p>
        <p>Capacity AC: ${inverter.capacity_ac} W</p>
      `;
      invertersContainer.appendChild(inverterElement);
    });
  }
}

// Create a new inverter
document.getElementById('inverter-form').addEventListener('submit', async function(event) {
  event.preventDefault();
  
  const formData = new FormData(event.target);
  const inverterData = {
    name: formData.get('name'),
    asset_id: parseInt(formData.get('asset_id')),
    commissioned: formData.get('commissioned'),
    warranty_start: formData.get('warranty_start'),
    warranty_end: formData.get('warranty_end'),
    serial_number: formData.get('serial_number'),
    device_model_id: parseInt(formData.get('device_model_id')),
    location_id: parseInt(formData.get('location_id')),
    capacity_dc: parseFloat(formData.get('capacity_dc')),
    capacity_ac: parseFloat(formData.get('capacity_ac'))
  };
  
  const result = await createInverter(inverterData);
  if (result && result.success) {
    alert('Inverter created successfully!');
    displayInverters();
    event.target.reset();
  }
});

// Initialize
displayInverters();

Using with Python Requests

Here's how to use the API with Python's requests library:

import requests
from requests.auth import HTTPBasicAuth

# Base URL for the API
BASE_URL = 'http://example.com/api/v1'

# User credentials for authentication
USERNAME = 'your_username'
PASSWORD = 'your_password'

# Create a session to maintain cookies
session = requests.Session()

# Log in to the Django site to get authentication cookies
login_url = 'http://example.com/accounts/login/'
login_data = {
    'username': USERNAME,
    'password': PASSWORD,
    'csrfmiddlewaretoken': session.get(login_url).cookies['csrftoken']
}
session.post(login_url, data=login_data, headers={'Referer': login_url})

# Function to get inverters
def get_inverters(page=1, page_size=20):
    response = session.get(f'{BASE_URL}/renewableassets/inverter/', params={
        'page': page,
        'page_size': page_size
    })
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return None

# Function to create an inverter
def create_inverter(inverter_data):
    response = session.post(
        f'{BASE_URL}/renewableassets/inverter/new/',
        json=inverter_data,
        headers={'X-CSRFToken': session.cookies['csrftoken']}
    )
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return None

# Example usage
if __name__ == '__main__':
    # Get all inverters
    inverters = get_inverters()
    if inverters:
        print(f"Found {inverters['count']} inverters")
        for inverter in inverters['results']:
            print(f"- {inverter['name']}: {inverter['capacity_dc']} W DC")
    
    # Create a new inverter
    new_inverter = {
        'name': 'GreenPower 3500',
        'asset_id': 104,
        'commissioned': '2025-05-15T09:00:00.000Z',
        'warranty_start': '2025-05-15',
        'warranty_end': '2030-05-15',
        'serial_number': 'INV-004-2025',
        'device_model_id': 8,
        'location_id': 6,
        'capacity_dc': 3800.0,
        'capacity_ac': 3500.0
    }
    
    result = create_inverter(new_inverter)
    if result and result['success']:
        print(f"Inverter created with ID: {result['id']}")
    else:
        print("Failed to create inverter")

These examples illustrate how to interact with the API from both client-side JavaScript and server-side Python applications.