diff --git a/.github/chatmodes/4.1-Beast.chatmode.md b/.github/chatmodes/4.1-Beast.chatmode.md new file mode 100644 index 0000000..94bc168 --- /dev/null +++ b/.github/chatmodes/4.1-Beast.chatmode.md @@ -0,0 +1,119 @@ +--- +description: 'GPT 4.1 as a top-notch coding agent.' +model: GPT-4.1 + +You are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. + +Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough. + +You MUST iterate and keep going until the problem is solved. + +You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me. + +Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn. + +THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH. + +You must use the fetch_webpage tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages. + +Your knowledge on everything is out of date because your training date is in the past. + +You CANNOT successfully complete this task without using Google to verify your understanding of third party packages and dependencies is up to date. You must use the fetch_webpage tool to search google for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need. + +Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why. + +If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is. + +Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided. + +You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. + +You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead of just saying that you will do it. + +You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input. + +# Workflow + +1. Fetch any URL's provided by the user using the `fetch_webpage` tool. +2. Understand the problem deeply. Carefully read the issue and think critically about what is required. Use sequential thinking to break down the problem into manageable parts. Consider the following: + - What is the expected behavior? + - What are the edge cases? + - What are the potential pitfalls? + - How does this fit into the larger context of the codebase? + - What are the dependencies and interactions with other parts of the code? +3. Investigate the codebase. Explore relevant files, search for key functions, and gather context. +4. Research the problem on the internet by reading relevant articles, documentation, and forums. +5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using standard markdown format. Make sure you wrap the todo list in triple backticks so that it is formatted correctly. +6. Implement the fix incrementally. Make small, testable code changes. +7. Debug as needed. Use debugging techniques to isolate and resolve issues. +8. Test frequently. Run tests after each change to verify correctness. +9. Iterate until the root cause is fixed and all tests pass. +10. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete. + +Refer to the detailed sections below for more information on each step. + +## 1. Fetch Provided URLs +- If the user provides a URL, use the `functions.fetch_webpage` tool to retrieve the content of the provided URL. +- After fetching, review the content returned by the fetch tool. +- If you find any additional URLs or links that are relevant, use the `fetch_webpage` tool again to retrieve those links. +- Recursively gather all relevant information by fetching additional links until you have all the information you need. + +## 2. Deeply Understand the Problem +Carefully read the issue and think hard about a plan to solve it before coding. + +## 3. Codebase Investigation +- Explore relevant files and directories. +- Search for key functions, classes, or variables related to the issue. +- Read and understand relevant code snippets. +- Identify the root cause of the problem. +- Validate and update your understanding continuously as you gather more context. + +## 4. Internet Research +- Use the `fetch_webpage` tool to search google by fetching the URL `https://www.google.com/search?q=your+search+query`. +- After fetching, review the content returned by the fetch tool. +- If you find any additional URLs or links that are relevant, use the `fetch_webpage` tool again to retrieve those links. +- Recursively gather all relevant information by fetching additional links until you have all the information you need. + +## 5. Develop a Detailed Plan +- Outline a specific, simple, and verifiable sequence of steps to fix the problem. +- Create a todo list in markdown format to track your progress. +- Each time you complete a step, check it off using `[x]` syntax. +- Each time you check off a step, display the updated todo list to the user. +- Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next. + +## 6. Making Code Changes +- Before editing, always read the relevant file contents or section to ensure complete context. +- Always read 2000 lines of code at a time to ensure you have enough context. +- If a patch is not applied correctly, attempt to reapply it. +- Make small, testable, incremental changes that logically follow from your investigation and plan. + +## 7. Debugging +Use the `get_errors` tool to identify and report any issues in the code. This tool replaces the previously used problems tool. +- Make code changes only if you have high confidence they can solve the problem +- When debugging, try to determine the root cause rather than addressing symptoms +- Debug for as long as needed to identify the root cause and identify a fix +- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening +- To test hypotheses, you can also add test statements or functions +- Revisit your assumptions if unexpected behavior occurs. + +# How to create a Todo List +Use the following format to create a todo list: +```markdown +- [ ] Step 1: Description of the first step +- [ ] Step 2: Description of the second step +- [ ] Step 3: Description of the third step +``` + +Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above. + +# Communication Guidelines +Always communicate clearly and concisely in a casual, friendly yet professional tone. + + +"Let me fetch the URL you provided to gather more information." +"Ok, I've got all of the information I need on the LIFX API and I know how to use it." +"Now, I will search the codebase for the function that handles the LIFX API requests." +"I need to update several files here - stand by" +"OK! Now let's run the tests to make sure everything is working correctly." +"Whelp - I see we have some problems. Let's fix those up." + diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..51a564d --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "chat.tools.autoApprove": true, + "chat.agent.maxRequests": 100 +} \ No newline at end of file diff --git a/openapi.yaml b/openapi.yaml new file mode 100644 index 0000000..631f972 --- /dev/null +++ b/openapi.yaml @@ -0,0 +1,399 @@ +openapi: 3.0.1 +info: + title: Simple Social Media Application API + version: 1.0.0 + description: | + API for a simple social media application supporting posts, comments, and likes. Designed for MVP and educational use cases. +servers: + - url: http://localhost:8080/api +paths: + /posts: + get: + summary: List all posts + tags: [Post] + responses: + '200': + description: List of posts + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Post' + '500': + $ref: '#/components/responses/InternalServerError' + post: + summary: Create a new post + tags: [Post] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreatePostRequest' + responses: + '201': + description: Post created + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + '400': + $ref: '#/components/responses/BadRequest' + '500': + $ref: '#/components/responses/InternalServerError' + /posts/{postId}: + get: + summary: Get a single post + tags: [Post] + parameters: + - name: postId + in: path + required: true + schema: + type: string + responses: + '200': + description: Post details + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + patch: + summary: Update a post + tags: [Post] + parameters: + - name: postId + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdatePostRequest' + responses: + '200': + description: Post updated + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + '400': + $ref: '#/components/responses/BadRequest' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + delete: + summary: Delete a post + tags: [Post] + parameters: + - name: postId + in: path + required: true + schema: + type: string + responses: + '204': + description: Post deleted + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + /posts/{postId}/comments: + get: + summary: List comments for a post + tags: [Comment] + parameters: + - name: postId + in: path + required: true + schema: + type: string + responses: + '200': + description: List of comments + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Comment' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + post: + summary: Create a comment on a post + tags: [Comment] + parameters: + - name: postId + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateCommentRequest' + responses: + '201': + description: Comment created + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + $ref: '#/components/responses/BadRequest' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + /posts/{postId}/comments/{commentId}: + get: + summary: Get a specific comment + tags: [Comment] + parameters: + - name: postId + in: path + required: true + schema: + type: string + - name: commentId + in: path + required: true + schema: + type: string + responses: + '200': + description: Comment details + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + patch: + summary: Update a comment + tags: [Comment] + parameters: + - name: postId + in: path + required: true + schema: + type: string + - name: commentId + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateCommentRequest' + responses: + '200': + description: Comment updated + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + $ref: '#/components/responses/BadRequest' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + delete: + summary: Delete a comment + tags: [Comment] + parameters: + - name: postId + in: path + required: true + schema: + type: string + - name: commentId + in: path + required: true + schema: + type: string + responses: + '204': + description: Comment deleted + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + /posts/{postId}/likes: + post: + summary: Like a post + tags: [Like] + parameters: + - name: postId + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LikeRequest' + responses: + '201': + description: Like added + '400': + $ref: '#/components/responses/BadRequest' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' + delete: + summary: Unlike a post + tags: [Like] + parameters: + - name: postId + in: path + required: true + schema: + type: string + responses: + '204': + description: Like removed + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalServerError' +components: + schemas: + Post: + type: object + properties: + id: + type: string + username: + type: string + content: + type: string + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + comments: + type: array + items: + $ref: '#/components/schemas/Comment' + likes: + type: array + items: + $ref: '#/components/schemas/Like' + Comment: + type: object + properties: + id: + type: string + postId: + type: string + username: + type: string + content: + type: string + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + Like: + type: object + properties: + username: + type: string + CreatePostRequest: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + UpdatePostRequest: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + CreateCommentRequest: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + UpdateCommentRequest: + type: object + required: + - username + - content + properties: + username: + type: string + content: + type: string + LikeRequest: + type: object + required: + - username + properties: + username: + type: string + Error: + type: object + properties: + message: + type: string + responses: + BadRequest: + description: Bad request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + NotFound: + description: Resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + InternalServerError: + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' diff --git a/python/main.py b/python/main.py new file mode 100644 index 0000000..cf08f2e --- /dev/null +++ b/python/main.py @@ -0,0 +1,352 @@ +import os +import sqlite3 +from fastapi import FastAPI, HTTPException, Request, Response +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import FileResponse +from fastapi.openapi.docs import get_swagger_ui_html +from fastapi.staticfiles import StaticFiles +from typing import List, Optional +from pydantic import BaseModel + +DB_PATH = "sns_api.db" +OPENAPI_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "openapi.yaml") + +app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None) + +# Allow CORS from everywhere +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +def init_db(): + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + # Posts table + c.execute(""" + CREATE TABLE IF NOT EXISTS posts ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL, + content TEXT NOT NULL, + createdAt TEXT NOT NULL, + updatedAt TEXT NOT NULL + ) + """) + # Comments table + c.execute(""" + CREATE TABLE IF NOT EXISTS comments ( + id TEXT PRIMARY KEY, + postId TEXT NOT NULL, + username TEXT NOT NULL, + content TEXT NOT NULL, + createdAt TEXT NOT NULL, + updatedAt TEXT NOT NULL + ) + """) + # Likes table + c.execute(""" + CREATE TABLE IF NOT EXISTS likes ( + postId TEXT NOT NULL, + username TEXT NOT NULL, + PRIMARY KEY (postId, username) + ) + """) + conn.commit() + conn.close() + +@app.on_event("startup") +def startup_event(): + init_db() + +# Serve Swagger UI at default endpoint + +# Root endpoint redirects to /docs +from fastapi.responses import RedirectResponse + +@app.get("/", include_in_schema=False) +def root(): + return RedirectResponse(url="/docs") + +@app.get("/docs", include_in_schema=False) +def custom_swagger_ui_html(): + return get_swagger_ui_html(openapi_url="/openapi.yaml", title="Simple Social Media Application API") + +# Serve the exact openapi.yaml at default endpoint +@app.get("/openapi.yaml", include_in_schema=False) +def serve_openapi_yaml(): + return FileResponse(OPENAPI_PATH, media_type="application/x-yaml") + +# ... API endpoints will be implemented here, strictly matching openapi.yaml ... +# --- Data Models --- +from uuid import uuid4 +from datetime import datetime + +class Like(BaseModel): + username: str + +class Comment(BaseModel): + id: str + postId: str + username: str + content: str + createdAt: str + updatedAt: str + +class Post(BaseModel): + id: str + username: str + content: str + createdAt: str + updatedAt: str + comments: List[Comment] = [] + likes: List[Like] = [] + +class CreatePostRequest(BaseModel): + username: str + content: str + +class UpdatePostRequest(BaseModel): + username: str + content: str + +class CreateCommentRequest(BaseModel): + username: str + content: str + +class UpdateCommentRequest(BaseModel): + username: str + content: str + +class LikeRequest(BaseModel): + username: str + +class Error(BaseModel): + message: str + +# --- Helper Functions --- +def get_db(): + conn = sqlite3.connect(DB_PATH) + conn.row_factory = sqlite3.Row + return conn + +def get_post(post_id): + conn = get_db() + post = conn.execute("SELECT * FROM posts WHERE id=?", (post_id,)).fetchone() + if not post: + conn.close() + return None + comments = conn.execute("SELECT * FROM comments WHERE postId=?", (post_id,)).fetchall() + likes = conn.execute("SELECT username FROM likes WHERE postId=?", (post_id,)).fetchall() + conn.close() + return Post( + id=post["id"], + username=post["username"], + content=post["content"], + createdAt=post["createdAt"], + updatedAt=post["updatedAt"], + comments=[Comment(**dict(c)) for c in comments], + likes=[Like(username=l["username"]) for l in likes], + ) + +# --- Endpoints --- +@app.get("/posts", response_model=List[Post], responses={500: {"model": Error}}) +def list_posts(): + try: + conn = get_db() + posts = conn.execute("SELECT * FROM posts").fetchall() + result = [] + for post in posts: + result.append(get_post(post["id"])) + conn.close() + return result + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + +@app.post("/posts", response_model=Post, status_code=201, responses={400: {"model": Error}, 500: {"model": Error}}) +def create_post(req: CreatePostRequest): + if not req.username or not req.content: + raise HTTPException(status_code=400, detail="username and content required") + post_id = str(uuid4()) + now = datetime.utcnow().isoformat() + conn = get_db() + try: + conn.execute( + "INSERT INTO posts (id, username, content, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)", + (post_id, req.username, req.content, now, now) + ) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return get_post(post_id) + +@app.get("/posts/{postId}", response_model=Post, responses={404: {"model": Error}, 500: {"model": Error}}) +def get_single_post(postId: str): + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + return post + +@app.patch("/posts/{postId}", response_model=Post, responses={400: {"model": Error}, 404: {"model": Error}, 500: {"model": Error}}) +def update_post(postId: str, req: UpdatePostRequest): + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + if not req.username or not req.content: + raise HTTPException(status_code=400, detail="username and content required") + now = datetime.utcnow().isoformat() + conn = get_db() + try: + conn.execute( + "UPDATE posts SET username=?, content=?, updatedAt=? WHERE id=?", + (req.username, req.content, now, postId) + ) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return get_post(postId) + +@app.delete("/posts/{postId}", status_code=204, responses={404: {"model": Error}, 500: {"model": Error}}) +def delete_post(postId: str): + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + conn = get_db() + try: + conn.execute("DELETE FROM posts WHERE id=?", (postId,)) + conn.execute("DELETE FROM comments WHERE postId=?", (postId,)) + conn.execute("DELETE FROM likes WHERE postId=?", (postId,)) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return Response(status_code=204) + +@app.get("/posts/{postId}/comments", response_model=List[Comment], responses={404: {"model": Error}, 500: {"model": Error}}) +def list_comments(postId: str): + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + return post.comments + +@app.post("/posts/{postId}/comments", response_model=Comment, status_code=201, responses={400: {"model": Error}, 404: {"model": Error}, 500: {"model": Error}}) +def create_comment(postId: str, req: CreateCommentRequest): + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + if not req.username or not req.content: + raise HTTPException(status_code=400, detail="username and content required") + comment_id = str(uuid4()) + now = datetime.utcnow().isoformat() + conn = get_db() + try: + conn.execute( + "INSERT INTO comments (id, postId, username, content, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)", + (comment_id, postId, req.username, req.content, now, now) + ) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return Comment(id=comment_id, postId=postId, username=req.username, content=req.content, createdAt=now, updatedAt=now) + +@app.get("/posts/{postId}/comments/{commentId}", response_model=Comment, responses={404: {"model": Error}, 500: {"model": Error}}) +def get_comment(postId: str, commentId: str): + conn = get_db() + comment = conn.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + conn.close() + if not comment: + raise HTTPException(status_code=404, detail="Comment not found") + return Comment(**dict(comment)) + +@app.patch("/posts/{postId}/comments/{commentId}", response_model=Comment, responses={400: {"model": Error}, 404: {"model": Error}, 500: {"model": Error}}) +def update_comment(postId: str, commentId: str, req: UpdateCommentRequest): + conn = get_db() + comment = conn.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + if not comment: + conn.close() + raise HTTPException(status_code=404, detail="Comment not found") + if not req.username or not req.content: + conn.close() + raise HTTPException(status_code=400, detail="username and content required") + now = datetime.utcnow().isoformat() + try: + conn.execute( + "UPDATE comments SET username=?, content=?, updatedAt=? WHERE id=? AND postId=?", + (req.username, req.content, now, commentId, postId) + ) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + comment = conn.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + conn.close() + return Comment(**dict(comment)) + +@app.delete("/posts/{postId}/comments/{commentId}", status_code=204, responses={404: {"model": Error}, 500: {"model": Error}}) +def delete_comment(postId: str, commentId: str): + conn = get_db() + comment = conn.execute("SELECT * FROM comments WHERE id=? AND postId=?", (commentId, postId)).fetchone() + if not comment: + conn.close() + raise HTTPException(status_code=404, detail="Comment not found") + try: + conn.execute("DELETE FROM comments WHERE id=? AND postId=?", (commentId, postId)) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return Response(status_code=204) + +@app.post("/posts/{postId}/likes", status_code=201, responses={400: {"model": Error}, 404: {"model": Error}, 500: {"model": Error}}) +def like_post(postId: str, req: LikeRequest): + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + if not req.username: + raise HTTPException(status_code=400, detail="username required") + conn = get_db() + try: + conn.execute("INSERT OR IGNORE INTO likes (postId, username) VALUES (?, ?)", (postId, req.username)) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return Response(status_code=201) + +@app.delete("/posts/{postId}/likes", status_code=204, responses={404: {"model": Error}, 500: {"model": Error}}) +def unlike_post(postId: str, req: Request): + # username must be provided in body for DELETE + body = req.json() if hasattr(req, 'json') else None + username = None + if body and "username" in body: + username = body["username"] + if not username: + raise HTTPException(status_code=400, detail="username required") + post = get_post(postId) + if not post: + raise HTTPException(status_code=404, detail="Post not found") + conn = get_db() + try: + conn.execute("DELETE FROM likes WHERE postId=? AND username=?", (postId, username)) + conn.commit() + except Exception as e: + conn.close() + raise HTTPException(status_code=500, detail=str(e)) + conn.close() + return Response(status_code=204) + +# Run the app on port 8000 +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/python/sns_api.db b/python/sns_api.db new file mode 100644 index 0000000..e12e8f5 Binary files /dev/null and b/python/sns_api.db differ