This chapter is a bit of a side-bar conversation, but it’s an important one. If you’re still fairly new to programming, it’s time we introduce the concept of WET and DRY code as well as knowing when to take the time to refactor (clean-up) your code.
In the previous chapter, we wrote a simple low-level REST API Adapter. We hadn’t even passed 30 lines of code when it started to become apparent that our code was getting sloppy.
Let’s get started by selecting Create New Project. As shown here, I called the project, py-cat-api. Right-click on “py-cat-api ” folder in the Project navigation panel and click New => Python Package. You can name the package similar to what you named your project. In this case, the_cat_api.
There should now be a subfolder in your project folder with a single empty file named __init__.py — This indicates to Python that this folder is a Python Package. (You could have just manually created a subfolder and manually added that same file, but this feature in the IDE saves you a step.)
So why did we create a folder with a subfolder of a similar name? Well, we’re setting up for creating a Git repository (the first folder) and putting a Python Package inside it (the second folder). If you’re familiar with Git, you know what to do. If not, don’t worry, we’ll get to this later.
Problem Scope
To understand what we’re about to do, it’s important to step back for a minute and understand the scope of the problem.
What we have is a JSON REST API (TheCatAPI)
What we want to do is create a uniform way of connecting to that API in Python.
The Python library we’re going to use to enable us to reach this service is known as requests.
Before going into battle, it’s important to do some reconnaissance. With any REST API, it’s important to get a feel for how the REST API behaves. Some REST APIs are written by professionals and are very easy to work with. And well, others are written by amateurs and are down-right terrible and inconsistent. Understanding how the API behaves before writing any code is the foundation for whether your wrapper library will be any good or not.
REST APIs. They’re all over the web. You could directly code against them in Python, but after a while, you start repeating yourself and your code becomes crufty and difficult to maintain. Your “high-level” business logic becomes intertwined with the “low-level” nitty-gritty logic of parsing I/O. And that’s bad news.
The smart solution is to abstract away the REST API with a “wrapper” library module more commonly known as a Software Developer Kit (SDK). Take all that nitty-gritty detail and push it down to where you don’t need to worry about it anymore and then just import your Python module and code directly against it.
If you’re using an intelligent IDE like PyCharm or VS Code, then you can leverage Type Hinting for auto-code completion. Keep your business logic separate from the boring details and your code is faster to develop and easier to maintain. Here’s how to do it: