Add simple API

This commit is contained in:
David Todd 2020-01-18 21:38:52 -06:00
parent 200ed14d13
commit 163d8b71c4
2 changed files with 104 additions and 0 deletions

9
api/__init__.py Normal file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env python3
"""
Creates a python module for the API
Usage: from api import API
"""
from .api import API

95
api/api.py Normal file
View File

@ -0,0 +1,95 @@
#!/usr/bin/env python3
# Copyright 2020 - David Todd (c0de@c0defox.es)
# Licensed under the MIT License (https://opensource.org/licenses/MIT)
"""
This file contains the API for a simple bookmarking application
"""
import json
import datetime
from pprint import pprint
from uuid import UUID
from bottle import response
from .db import Database
class API:
"""
This class contains various methods for a simple bookmarking application API
As of right now, these are mostly just to pass data through to the database.
Stuff should be sanitized here though
"""
def __init__(self):
"""
Setup some internal variables, such as various constants
and the database connection
"""
self.database = Database('bookmarks.db')
self.dt_fmt = "%H:%M:%S on %B %d %Y"
self.response_type = 'application/json'
self.format_date = datetime.datetime.strftime
def save_bookmark(self, title, uri):
"""
Save the bookmark with `title` and `uri`
Returns a JSON object containing
the UUID of the saved bookmark
"""
response.content_type = self.response_type
bookmark = self.database.save_bookmark(uri, title)
return json.dumps({
'uuid': bookmark.hex
})
def get_bookmark(self, bookmark_id):
"""
Get the bookmark with the provided `bookmark_id`
`bookmark_id` is of type string
Returns a JSON object containing
everything about the bookmark
"""
response.content_type = self.response_type
bookmark = self.database.get_bookmark(UUID(bookmark_id))
# Maybe I need to use `sqlite3.Cursor.description` or `sqlite3.Row.keys()`
bookmark_object = {
'uuid': bookmark[0].hex,
'uri': bookmark[1],
'title': bookmark[2],
'date_created': self.format_date(bookmark[3], self.dt_fmt),
'date_updated': self.format_date(bookmark[4], self.dt_fmt) if bookmark[4] != None else '',
}
return json.dumps(bookmark_object)
def get_all_bookmarks(self):
"""
Gets all of the bookmarks that are currently saved
Returns a JSON object containing
everything about each bookmark
"""
response.content_type = self.response_type
bookmarks = self.database.get_all_bookmarks()
bookmark_object = [
{
'uuid': bookmark[0].hex,
'uri': bookmark[1],
'title': bookmark[2],
'date_created': self.format_date(bookmark[3], self.dt_fmt),
'date_updated': self.format_date(bookmark[4], self.dt_fmt) if bookmark[4] != None else ''
} for bookmark in bookmarks
]
return json.dumps(bookmark_object)
def delete_bookmark(self, bookmark_id):
"""
"""
response.content_type = self.response_type