Commit 4a92076e authored by Schwieger, Jana's avatar Schwieger, Jana
Browse files

Aufgabe 1-3, Docker Compose, Postman Collection

parent d67599d9
import flask
import sqlite3
from flask import request, jsonify
from matplotlib import pyplot as plt
import numpy as np
app = flask.Flask(__name__)
books = [
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'},
{'id': 1,
'title': 'The Ones Who Walk Away From Omelas',
'author': 'Ursula K. Le Guin',
'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
'published': '1973'},
{'id': 2,
'title': 'Dhalgren',
'author': 'Samuel R. Delany',
'first_sentence': 'to wound the autumnal city.',
'published': '1975'}
]
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
@app.route('/', methods=['GET'])
def home():
return "<h1>Distant Reading Archive 2.0</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"
return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"
@app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
return jsonify(books)
@app.route('/api/v1/resources/books', methods=['GET'])
def api_id():
if 'id' in request.args:
id = int(request.args['id'])
else:
return "Error: No id field provided. Please specify an id."
results = []
for book in books:
if book['id'] == id:
results.append(book)
return jsonify(results)
@app.route('/api/v2/resources/books/all', methods=['GET'])
def api_v2_all():
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM books;').fetchall()
return jsonify(all_books)
@app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
@app.route('/api/v2/resources/books', methods=['GET'])
def api_filter():
query_parameters = request.args
id = query_parameters.get('id')
published = query_parameters.get('published')
author = query_parameters.get('author')
query = "SELECT * FROM books WHERE"
to_filter = []
if id:
query += ' id=? AND'
to_filter.append(id)
if published:
query += ' published=? AND'
to_filter.append(published)
if author:
query += ' author=? AND'
to_filter.append(author)
if not (id or published or author):
return page_not_found(404)
query = query[:-4] + ';'
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
@app.route('/api/v2/resources/books/plot', methods=['GET'])
def api_sentenceLength():
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM books;').fetchall()
sentence_length = np.array([len(book['first_sentence']) for book in all_books])
year = np.array([book['published'] for book in all_books])
m, b = np.polyfit(year, sentence_length, 1)
fig = plt.figure()
plt.scatter(year, sentence_length, color="red")
plt.plot(year, m * year + b, color="blue")
plt.xlabel("Date of Publication")
plt.ylabel("Length of First Sentence in Characters")
plt.savefig("sentences_length.svg")
return flask.Response(open("sentences_length.svg").read(), mimetype='image/svg+xml')
app.run(host="0.0.0.0")
\ No newline at end of file
services:
bookapi:
build: .
ports:
- "8080:5000"
volumes:
- .:/app
\ No newline at end of file
{
"info": {
"_postman_id": "b6098e6d-f75e-415f-baaf-81ebdf13c6f0",
"name": "lab-rest",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Chronicling America Basic",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://chroniclingamerica.loc.gov/search/pages/results/",
"protocol": "http",
"host": [
"chroniclingamerica",
"loc",
"gov"
],
"path": [
"search",
"pages",
"results",
""
]
}
},
"response": []
},
{
"name": "Chronicling America JSON Query=Fire",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://chroniclingamerica.loc.gov/search/pages/results/?format=json&proxtext=fire",
"protocol": "http",
"host": [
"chroniclingamerica",
"loc",
"gov"
],
"path": [
"search",
"pages",
"results",
""
],
"query": [
{
"key": "format",
"value": "json"
},
{
"key": "proxtext",
"value": "fire"
}
]
}
},
"response": []
},
{
"name": "Localhost",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});\r",
"\r",
"pm.test(\"Body is correct\", function () {\r",
" pm.response.to.have.body(\"<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>\");\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080"
}
},
"response": []
},
{
"name": "All Books",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});\r",
"\r",
"const responseJson = pm.response.json();\r",
"pm.test(\"JSON Inhalt\", () => {\r",
" \r",
" pm.expect(responseJson[0].author).to.eql(\"Vernor Vinge\");\r",
" pm.expect(responseJson[1].author).to.eql(\"Ursula K. Le Guin\");\r",
" pm.expect(responseJson[2].author).to.eql(\"Samuel R. Delany\");\r",
"});\r",
"\r",
"pm.test(\"JSON Schema\", () => {\r",
" const firstBook = responseJson[0];\r",
" pm.expect(responseJson).to.be.an(\"array\");\r",
" pm.expect(firstBook).to.be.an(\"object\");\r",
" pm.expect(firstBook.author).to.be.a(\"String\");\r",
" pm.expect(firstBook.first_sentence).to.be.a(\"String\");\r",
" pm.expect(firstBook.id).to.be.a(\"number\");\r",
" pm.expect(firstBook.year_published).to.be.a(\"String\");\r",
"})"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v1/resources/books/all",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v1",
"resources",
"books",
"all"
]
}
},
"response": []
},
{
"name": "Book With ID",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "localhost:8080/api/v1/resources/books?id=0",
"host": [
"localhost"
],
"port": "8080",
"path": [
"",
"api",
"v1",
"resources",
"books"
],
"query": [
{
"key": "id",
"value": "0"
}
]
}
},
"response": []
},
{
"name": "V2 All Books (DB)",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v2/resources/books/all",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v2",
"resources",
"books",
"all"
]
}
},
"response": []
},
{
"name": "V2 Book Author (DB)",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v2/resources/books?author=Connie+Willis",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v2",
"resources",
"books"
],
"query": [
{
"key": "author",
"value": "Connie+Willis"
}
]
}
},
"response": []
},
{
"name": "V2 Book Author + PubDate (DB)",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v2/resources/books?author=Connie+Willis&published=1993",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v2",
"resources",
"books"
],
"query": [
{
"key": "author",
"value": "Connie+Willis"
},
{
"key": "published",
"value": "1993"
}
]
}
},
"response": []
},
{
"name": "V2 Book PubDate (DB)",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 200\", function () {\r",
" pm.response.to.have.status(200);\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v2/resources/books?published=2010",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v2",
"resources",
"books"
],
"query": [
{
"key": "published",
"value": "2010"
}
]
}
},
"response": []
},
{
"name": "V2 404 Not Found",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test(\"Status code is 404\", function () {\r",
" pm.response.to.have.status(404);\r",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v2/resources/img",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v2",
"resources",
"img"
]
}
},
"response": []
},
{
"name": "Plot",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/api/v2/resources/books/plot",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"api",
"v2",
"resources",
"books",
"plot"
]
}
},
"response": []
}
]
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment