Lab 4: Build a key-value database server

Summary

In this lab you will build a key value database server where you can through HTTP do the following:

  1. Store a value that’s associated by a key
  2. Get the value associated by a key
  3. Delete a key/value combination

Task

Please create a Flask application that does the following, listening on http://localhost:5000:

Create/Update a key

POST /post

Input

{"key": "the_key", "value": "the_value"}

Output

{"key": "the_key", "value": "the_value", "message": "success"}

Note the message “success”

Get value from key (version 1)

GET /get/<key>

Input

<key> (in the url)
Example: "/get/the_key"

Output

{"value": "the_value")

Get value from key (version 2)

GET /get?key=<key>

Input

<key> (in the url)
Example: "/get?key=the_key"

Output

{"value": "the_value")

Delete a specific task

DELETE /delete

Input

{key: "the_key"}

Output

{key: "the_key", "message": "success"}

Unit Tests

If you can run these tests successfully, you have finished the lab. Please note that you need to keep your server running and listening on port 5000 for the tests to work.

Also please note to run ‘pytest <name of unit test file>’ to run the tests

import requests
import json

def test_post():
    r = requests.post('http://localhost:5000/post', json={"key": "key1", "value": "value1"})
    true_content = {"key": "key1", "value": "value1", "message":"success"}

    assert r.json() == true_content

def test_get_1():
    r = requests.get('http://localhost:5000/get/key1')
    true_content = {"value": "value1"}

    assert r.json() == true_content


def test_get_2():
    r = requests.get('http://localhost:5000/get?key=key1')
    true_content = {"value": "value1"}

    assert r.json() == true_content

def test_delete():
    r = requests.delete('http://localhost:5000/delete?key=key1', json={"key": "key1"})
    true_content = {"key": "key1", "message": "success"}

    assert r.json() == true_content
 

Follow up tasks

  • GET/DELETE Endpoings: if key does not exist, send 404 message