-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
59 lines (51 loc) · 1.51 KB
/
app.py
File metadata and controls
59 lines (51 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import sqlite3
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
DB_PATH = "items.db"
# GraphQL type
@strawberry.type
class Item:
id: int
name: str
price: float
# Helper function to get DB connection
def get_db_connection():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
# Query definition
@strawberry.type
class Query:
@strawberry.field
def items(self) -> list[Item]:
conn = get_db_connection()
rows = conn.execute("SELECT * FROM items").fetchall()
conn.close()
return [Item(**row) for row in map(dict, rows)]
@strawberry.field
def item(self, id: int) -> Item | None:
conn = get_db_connection()
row = conn.execute("SELECT * FROM items WHERE id = ?", (id,)).fetchone()
conn.close()
if row:
return Item(**dict(row))
return None
# Mutation definition
@strawberry.type
class Mutation:
@strawberry.mutation
def create_item(self, name: str, price: float) -> Item:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("INSERT INTO items (name, price) VALUES (?, ?)",(name, price))
conn.commit()
item_id = cursor.lastrowid
conn.close()
return Item(id=item_id, name=name, price=price)
# Create schema
schema = strawberry.Schema(query=Query, mutation=Mutation)
# FastAPI app
app = FastAPI()
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix="/graphql")