Lab 2b: Let’s build an API in Python

That’s right. We will go over the intricacies of how we can build our very own API. We will go over what an Application Programming Interface is later in the semester, but we are going to look at one of the core concepts

Please create a file named “api.py” and write a module that acts as a datasource for an application. Your module will use a single dictionary and allow the user/client to be able to add, edit, and subtract entries in that dictionary through your own interface.

Please accomplish this by implementing the following functions:

  • def set_item(db, key, value):
    • Adds a “key” with value “value” into the dictionary called “db”. If “key” already exists, will overwrite the key with the given value. Return the db.
  • def get_item(db, key):
    • Returns the value of the key in the database
  • def remove_item(db, key):
    • Removes a key from the db. Returns the resulting db

Please write this in a file called “api.py”.

To test if you are done:

Please create another file called “test_api.py” and copy and paste the following code (and save in the same folder as your api.py:

import unittest

from api import set_item, get_item, remove_item

class TestAPI(unittest.TestCase):

    def test_set_item_exists(self):
        db = {}

        set_item(db, "testkey1", "testvalue1")
        self.assertIn( "testkey1", db)

    def test_set_item_value_set(self):
        db = {}

        set_item(db, "testkey1", "testvalue1")
        self.assertEqual(db["testkey1"], "testvalue1")

    def test_get_item(self):

        db = {"testkey2": "testvalue2"}
        self.assertEqual(get_item(db, "testkey2"), "testvalue2")

    
    def test_remove_item(self):
        db = {"testkey2": "testvalue2"}
        remove_item(db, "testkey2")
        self.assertNotIn("testkey2", db)


if __name__ == '__main__':
    unittest.main()
  • You can run this test using the following command
    • python3 -m unittest test_api.py
  • This will run what is called unit tests against your code. Unit tests run your code and tests for expected behavior. If you see the below you are done with the lab:
% python3 -m unittest test_api.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK
  • If your code fails one of the tests, it will look something like this. It should tell you the line where the error occurred where you can go ahead and fix it:
======================================================================
FAIL: test_set_item_value_set (test_api.TestAPI)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/kay/Desktop/code/test_api.py", line 17, in test_set_item_value_set
    self.assertEqual(db["testkey1"], "testvalue1")
AssertionError: 'testvalue1!' != 'testvalue1'
- testvalue1!
?           -
+ testvalue1


----------------------------------------------------------------------