This commit is contained in:
2023-10-01 01:22:11 +03:00
parent dda01f0135
commit be4c1c547e
3 changed files with 68 additions and 4 deletions

2
README.MD Normal file
View File

@ -0,0 +1,2 @@
# Example of a message API system on FastAPI with a backend Sqlite3 Database
## Documentation of pathes can be read on /docs

View File

@ -4,5 +4,47 @@ con = sqlite3.connect("data.db")
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS data_table (key, value)')
cur.execute(
"""CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT,
author TEXT NOT NULL,
recipient TEXT NOT NULL,
content TEXT
);
"""
)
cur.close()
con.close()
def DB_get_msg(id: int = None):
con = sqlite3.connect("data.db")
cur = con.cursor()
cur.execute("SELECT * FROM messages WHERE id=?", (id,))
row = cur.fetchone()
cur.close()
con.close()
return row
def DB_new_msg(
author: str = "Unknown", recipient: str = "Unknown", content: str = "N/A"
):
con = sqlite3.connect("data.db")
cur = con.cursor()
data = (author, recipient, content)
cur.execute(
"INSERT INTO messages (author, recipient, content) VALUES(?, ?, ?)", (data)
)
con.commit()
cur.close()
con.close()
def DB_get_recent_msgs(last: int = 10):
con = sqlite3.connect("data.db")
cur = con.cursor()
cur.execute("SELECT * FROM messages ORDER BY id DESC")
rows = cur.fetchmany(last)
con.close()
print(rows)
return rows

26
main.py
View File

@ -1,9 +1,29 @@
from fastapi import FastAPI
from pydantic import BaseModel
import database
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
class Message(BaseModel):
author: str
recipient: str
content: str
@app.get("/")
def read_recents(history: int = 10):
rs = database.DB_get_recent_msgs(history)
return rs
@app.post("/msg")
def post_msg(msg: Message):
database.DB_new_msg(author=msg.author, recipient=msg.recipient, content=msg.content)
return f"Message sent to {msg.recipient}"
@app.get("/msg/{msg_id}")
def get_msg(msg_id: int):
r = database.DB_get_msg(msg_id)
return r