-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add get single item route #3
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Feedback from Senior Dev Bot
items = cursor.fetchall() | ||
return {"data": items} | ||
|
||
@app.get("/items/{item_id}") | ||
async def get_item(item_id: int): | ||
cursor.execute("SELECT * FROM items WHERE id = %s", (item_id,)) | ||
item = cursor.fetchone() | ||
return {"data": item} | ||
|
||
@app.post("/items") | ||
async def add_item(name: str): | ||
cursor.execute("INSERT INTO items (name) VALUES (%s)", (name,)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code changes you've made are generally okay, but there are still some improvements that can be done.
-
Usage of SQL statements directly in routes: This can be risky as it might lead to SQL Injection attacks if not properly handled. Also, it's a best practice to separate database operations from your routes for modularity and maintainability.
-
Error handling: There is currently no error handling for database queries within the routes. What happens if the item doesn't exist in the database or the database connection fails?
-
SQL execute parameters: Use a tuple with a trailing comma for single parameters as it is safer against SQL-injection.
Here are the suggestions to improve your code:
@app.get("/items/{item_id}")
async def get_item(item_id: int):
try:
cursor.execute("SELECT * FROM items WHERE id = %s", (item_id,))
item = cursor.fetchone()
if item is None:
return {"error": "Item not found"}
return {"data": item}
except Exception as e:
# Ideally log the error and return a user-friendly message
return {"error": "An error occurred"}
@app.post("/items")
async def add_item(name: str):
try:
cursor.execute("INSERT INTO items (name) VALUES (%s)", (name,))
except Exception as e:
# Similarly, log errors and return a user-friendly message
return {"error": "An error occurred"}
- Finally, be aware that this simplified adjustment assumes you have the cursor object initiated and connected to a database, which is not shown in the provided snippet. If not, further changes would be needed.
We'd like the ability to get a singular item by id from the API instead of returning a full list.