Adopt a Pet - Task 14 - KeyError: 'pet_type'

Project link: Build Python Web Apps with Flask - Adopt a Pet Project
Hi there, I have reviewed other threads on this same project and same step and am still confused, so here I am. My problem is that I keep getting KeyError:'pet_type’

Task 14 Directions:

In the function body, create a variable called pet that stores the profile information of the pet who is of pet_type and has index position pet_id in its list of pets.

In other words, first access the appropriate list of pets in the pets dictionary by the key, pet_type . Then, access the appropriate dictionary in the list of pets by the index position, pet_id .

My code for task 14:

@app.route('/animals/<pet_type>/<int:pet_id>')
def pet(pet_type, pet_id):
  pet = pets[pet_type][pet_id]
  return f'<h1>{pet}</h1>'

Does anyone have any insight to share on this? Thank you in advance!

I would open this in the shell and play with your pets list/json. Key error is usually when you try to access a key that doesn’t exist in a dictionary. So with pets[pet_type] you have to check that it’s an a valid value (if it is indeed a dictionary or json). Then, once confirmed, you can then try to access by id.

2 Likes

I think I got it fully. Hope it helps:

from flask import Flask
from helper import pets

app = Flask(__name__)

@app.route('/')
def index():
  return '''
  <h1> Adopt a Pet!</h1> 
  <p>Browse through the links below to find your new furry friend:</p>
  <ul>
    <li> <a href = '/animals/dogs'>Dogs</a>
    <li> <a href = '/animals/cats'>Cats
    <li> <a href = '/animals/rabbits'>Rabbits
  </ul>
  '''

@app.route('/animals/<pet_type>')
def animals(pet_type):
  html = f'<h1> List of {pet_type}: </h1>'
  html += '<ul>'
  for idx, pet in enumerate(pets[pet_type]):
    html += '<li>{link}{namey}</li>'.format(link='<a href="/animals/{pet_type}/{idx}">'.format(pet_type=pet_type, idx=idx),namey='{n}'.format(n=pet['name']))
  html += '</a>'
  html += '</ul>'  
  return html

@app.route('/animals/<pet_type>/<int:pet_id>')
def pet(pet_type, pet_id):
    pet = pets[pet_type][pet_id]
    return f"""
  <h1>{pet['name']}</h1>
  <img src={pet['url']} alt='alt text'>
  <p>{pet['description']}</p>
  <ul>
  <li>{pet['breed']}</li>
  <li>{pet['age']}</li>
  </ul>
  """




In your

@app.route('/animals/<pet_type>')

You are probably not formatting the variable pet_type to be an actual type, so the https request going out is carrying the literal pet_type instead of its abstraction into a value:

html += '<li>{link}{namey}</li>'.format(link='<a href="/animals/{pet_type}/{idx}">'.format(pet_type=pet_type, idx=idx),namey='{n}'.format(n=pet['name']))