This is my first time working with Python and APIs. I am trying to get a list of books based on an author’s name. I’m using SQLAlchemy for this and Python 3.10.2. I think this is all the relevant code:
JavaScript
x
28
28
1
class Author(db.Model):
2
id = db.Column(db.Integer, primary_key=True)
3
name = db.Column(db.String(100))
4
biography = db.Column(db.String(100))
5
publisher = db.Column(db.String(50))
6
7
def __init__(self,name,biography,publisher):
8
self.name = name
9
self.biography = biography
10
self.publisher = publisher
11
12
# FUNCTION TO RETURN AN AUTHOR DICTIONARY
13
def author_dict(new_author):
14
author = {
15
"id": new_author.id,
16
"name": new_author.name,
17
"biography": new_author.biography,
18
"publisher": new_author.publisher
19
}
20
return author
21
22
# GET A LIST OF BOOKS BASED ON AUTHOR
23
@app.route('/bookauthor/<name>', methods = ['GET'])
24
def book_author(name):
25
author = Author.query.filter_by(name=name).all()
26
authorFilter = author_dict(author)
27
return json.dumps(authorFilter)
28
Why am I getting this error:
JavaScript
1
2
1
AttributeError: 'list' object has no attribute 'id'
2
And how do I fix it?
Advertisement
Answer
The all()
method will return you a list of Author
instances.
You cannot call the author_dict
by passing a list of Author
instances. This function accept only one Author
instance. But you can achieve what you are looking for with a simple list comprehension
JavaScript
1
6
1
@app.route('/bookauthor/<name>', methods = ['GET'])
2
def book_author(name):
3
authors = Author.query.filter_by(name=name).all()
4
authorFilter = [author_dict(author) for author in authors]
5
return json.dumps(authorFilter)
6
Another “cleaner” way is to create a to_dict
method at the Author
class level :
JavaScript
1
26
26
1
class Author(db.Model):
2
id = db.Column(db.Integer, primary_key=True)
3
name = db.Column(db.String(100))
4
biography = db.Column(db.String(100))
5
publisher = db.Column(db.String(50))
6
7
def __init__(self,name,biography,publisher):
8
self.name = name
9
self.biography = biography
10
self.publisher = publisher
11
12
def to_dict():
13
return {
14
"id": new_author.id,
15
"name": new_author.name,
16
"biography": new_author.biography,
17
"publisher": new_author.publisher
18
}
19
20
21
# GET A LIST OF BOOKS BASED ON AUTHOR
22
@app.route('/bookauthor/<name>', methods = ['GET'])
23
def book_author(name):
24
authors = Author.query.filter_by(name=name).all()
25
return json.dumps([author.to_dict() for author in authors])
26