Skip to content

Instantly share code, notes, and snippets.

@Ceasar Ceasar/
Created Mar 10, 2017

What would you like to do?
import json
from flask import Flask, request, url_for, jsonify
app = Flask(__name__)
with open('photos.json') as fp:
PHOTOS = json.loads(
with open('albums.json') as fp:
ALBUMS = json.loads(
def index():
return jsonify({
'albums_url': url_for('albums', _external=True),
'photos_url': url_for('photos', _external=True)
def find_photo(photo_id):
return next(photo for photo in PHOTOS if photo['id'] == photo_id)
def _get(collection, _id=None):
return jsonify(
next(obj for obj in collection if obj['id'] == int(_id)) if _id else
@app.route("/albums", methods=['GET', 'POST'])
def albums(album_id=None):
if request.method == 'POST':
album_data = request.get_json()
album_data['id'] = max([album['id'] for album in ALBUMS]) + 1
return jsonify(album_data)
return _get(ALBUMS, album_id)
def photos(photo_id=None):
return _get(PHOTOS, photo_id)
@app.route("/albums/<album_id>/photos", methods=['GET', 'POST'])
def album_photos(album_id):
if request.method == 'POST':
photo_id = request.get_json()['id']
photo_data = dict(find_photo(photo_id))
photo_data['albumId'] = int(album_id)
return jsonify(photo_data)
photos = [photo for photo in PHOTOS if photo['albumId'] == int(album_id)]
return jsonify(photos)
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.