Skip to content

Instantly share code, notes, and snippets.

@artizirk

artizirk/api.py Secret

Last active December 3, 2015 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artizirk/ae9cf28d1f45ef0aa965 to your computer and use it in GitHub Desktop.
Save artizirk/ae9cf28d1f45ef0aa965 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import json
from wsgiref import simple_server
import falcon
from pymongo import MongoClient
"""
MusicSync backend http api implementation
"""
class Resource():
"""Base resource class"""
def __init__(self, db):
self.db = db
class PlaylistsResource(Resource):
"""Operations on playlists collection"""
def on_get(self, req, resp):
"""Returns list of all playlists"""
resp.status = falcon.HTTP_200
resp.body = json.dumps([])
def on_post(self, req, resp):
"""Create a new playlist"""
resp.status = falcon.HTTP_201
class PlaylistResource(Resource):
"""Operations on one playlist"""
def on_get(self, req, resp, playlist_id):
"""Return a playlist info"""
resp.status = falcon.HTTP_200
resp.body = json.dumps({"_id":playlist_id})
def on_delete(self, req, resp, playlist_id):
"""Delete this playlist"""
resp.status = falcon.HTTP_204
class SongsResource(Resource):
"""Operations on a songs collection in a playlist"""
def on_get(self, req, resp, playlist_id):
"""Return list of songs in a playlist"""
resp.status = falcon.HTTP_200
resp.body = json.dumps([{"_id":playlist_id, "resource":"songs"}])
def on_post(self, req, resp, playlist_id, song_id):
"""Add a song to a playlist"""
resp.status = falcon.HTTP_201
class SongResource(Resource):
"""Operations on a one song"""
def on_get(self, req, resp, playlist_id, song_id):
"""Return a one song"""
resp.status = falcon.HTTP_200
resp.body = json.dumps([{"_id":playlist_id,"song_id":song_id}])
def on_delete(self, req, resp, playlist_id, song_id):
"""Delete that song from playlist"""
resp.status = falcon.HTTP_204
client = MongoClient()
db = client["MusicSync"]
app = falcon.API()
app.add_route('/playlists/', PlaylistsResource(db))
app.add_route('/playlists/{playlist_id}/', PlaylistResource(db))
app.add_route('/playlists/{playlist_id}/songs/', SongsResource(db))
app.add_route('/playlists/{playlist_id}/songs/{song_id}', SongResource(db))
# a debug server
if __name__ == '__main__':
httpd = simple_server.make_server('127.0.0.1', 8000, app)
print("Running a dev server at http://{}:{}".format(*httpd.server_address))
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment