Home > Enterprise >  Why am I getting TypeError string indices must be integers in this API call? (seeding Django DB)
Why am I getting TypeError string indices must be integers in this API call? (seeding Django DB)

Time:10-05

I am trying to seed a django DB from an external API using this guide (https://medium.com/@chilinski.a/how-to-seed-a-django-api-with-data-from-an-external-api-b577b6e6ad54).

I have replicated the code accurately for my own project, I think, but get a TypeError when i run python manage.py seed and am not sure why. Here's the error message:

File "...nrel/nrel_app/management/commands/seed.py", line 15, in seed_nrel utility_name = i["utility_name"], TypeError: string indices must be integers

Here's my code:

import requests
from django.core.management.base import BaseCommand
from nrel_app.models import Nrel


def get_nrel():
    url = 'https://developer.nrel.gov/api/utility_rates/v3.json?api_key=DEMO_KEY&lat=35.45&lon=-82.98'
    r = requests.get(url, headers={'Content=Type': 'nrel_app/json'})
    Nrels = r.json()
    return Nrels

def seed_nrel():
    for i in get_nrel():
            Nrels = Nrel(
                utility_name = i['utility_name'],
                company_id = i['company_id'],
                utility_info =i['utility_info'],
                residential = i['residential'],
                commercial = i['commercial'],
                industrial = i['industrial'],
            )
            Nrels.save()

class Command(BaseCommand):
    def handle(self, *args, **options):
        seed_nrel()
        print("Completed.")

Here's the json being requested from the nrel api:

{
    "inputs": {
        "lat": "35.45",
        "lon": "-82.98"
    },
    "errors": [],
    "warnings": [],
    "version": "3.1.0",
    "metadata": {
        "sources": [
            "Ventyx Research (2012)"
        ]
    },
    "outputs": {
        "company_id": "8333|18642",
        "utility_name": "Haywood Electric Member Corp|Tennessee Valley Authority",
        "utility_info": [
            {
                "company_id": "8333",
                "utility_name": "Haywood Electric Member Corp"
            }, {
                "company_id": "18642",
                "utility_name": "Tennessee Valley Authority"
            }
        ],
        "commercial": 0.0977,
        "industrial": 0.0862,
        "residential": 0.123
    }
}

CodePudding user response:

I think you should remove the for cycle and get the result from the object returned by the get_nrel() method directly:

def seed_nrel():
     i = get_nrel()['options']
     Nrels = Nrel(
          utility_name = i['utility_name'],
          company_id = i['company_id'],
          utility_info =i['utility_info'],
          residential = i['residential'],
          commercial = i['commercial'],
          industrial = i['industrial'],
     )
     Nrels.save()
  • Related