r/FastAPI • • Dec 09 '22

Question Not showing list?

@.get("/") async def read_root():

# houses = json.load(open("data.json"))["houses"]["house"]

# return houses[0]["id"]

houses = json.load(open("data.json"))["houses"]["house"]

for house in houses:

return house["id"]

When I run the commented code, I receive "3070", which is working as intended, however when I try to loop it in the non-commented code, I also receive "3070" instead of a list of ids.

Can't figure this one out, thanks for the help :)

0 Upvotes

6 comments sorted by

2

u/Mikkognito Dec 09 '22 edited Dec 09 '22

Quick question. Are you following a tutorial or are you working on a personal project for yourself?

I want to help you. The code you got on stack overflow is bad and if you're just starting out, I wanted to help you avoid making these mistakes.

  1. Do not use open() without using a context manager or closing the file afterwards.

  2. Creating an empty list then appending to the list using a for loop is an anti-pattern in Python.

  3. FastAPI has dependency injection built in, which means you can use that to inject the file handle Dependency Injection

If you're an absolute beginner, then this should be okay, but you should revisit this code later to see why I'm raising alarms here. However, if you're working on a personal project, then you should learn the Python anti-patterns early on so you don't continue to do them later in your career.

1

u/Bubbly-Desk-4479 Dec 13 '22

I am mostly following the fastapi docs and trying to create an api for my mobile app, you could consider me an extreme beginner ahah.

I don't quite understand the need to close the file, as it needs to be accessed, but this file is 25MB so I assume it can cause some problems.

Also don't quite understand why I shouldn't create an open list, I have seen it on multiple tutorials, and honesly couldn't find a better way to do it.

Finally, I have no idea what is dependency injection :)

Anyways, I will keep your tips in mind for the future. Or the present, if if you are interested in freelance, PM.

1

u/TormentedTopiary Dec 09 '22

houses = json.load(open("data.json"))["houses"]["house"]

How many items does this line load?

1

u/Bubbly-Desk-4479 Dec 09 '22

returns a dict with every item in the database

2

u/Bubbly-Desk-4479 Dec 09 '22

Someone replied on SO, and its working:

houses = []
for house in json.load(open("data.json"))["houses"]["house"]:
houses.append(house["id"])
return houses

1

u/Jmodell Dec 12 '22

with open(“data.json”) as f: houses = [house for house in json.load(f)[“houses”][“house”]]

return houses

What someone was saying above, the code you got from so will work but it’s not pythonic and doesn’t use the list comprehension that makes Python code succinct. Using “with” closes the file when the close block is done on its own too.