Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ async def get_items():
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,))
Comment on lines 22 to 33
Copy link

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.

  1. 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.

  2. 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?

  3. 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"}
  1. 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.

Expand Down