ProcessIntermediate
How does the '/creature/plot' endpoint generate a histogram of creature name initials, and what libraries does it use?
The endpoint calls get_all() to retrieve all creatures, then uses collections.Counter to count the first letter of each creature's name. It builds a dictionary mapping each letter A-Z to its count and passes that to plotly.express.histogram with list(letters) as x and the counts as y. The resulting figure is converted to PNG bytes with fig.to_image(format="png") and returned as a FastAPI Response with media_type="image/png". The libraries used are collections.Counter, plotly.express, and fastapi.Response.
Key points
- Retrieves all creature records via service.creature.get_all().
- Uses collections.Counter to count the first character of each creature.name.
- Builds a dictionary with counts for every letter A-Z, defaulting to zero.
- Creates the chart with plotly.express.histogram.
- Converts the figure to PNG bytes and returns it as a FastAPI Response.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.