Categories
Code

Python JSON REST API wrapper library: a How-To in 15 simple steps

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:

Step 1: Read the Docs and use PostMan to understand the REST API

Step 2: Create a low-level REST adapter

Step 3: Understand the difference between WET code and DRY code, and then Refactor the low-level REST Adapter

Step 4: Implement Exception handling and raise new custom Exceptions

Step 5: Create a new Response/Result model

Step 6: Add Logging

Step 7: Add helpful Comments

Step 8: Create strong data models

Step 9: More complex data models

Step 10: Implement Inheritance with data models

Step 11: Create high level endpoint abstractions

Step 12: Create more endpoints and helper methods

Step 13: Page the endpoints

Step 14: Write your unit tests

Step 15: Make an app that consumes your module


Start the Tutorial here with Step 1

2 replies on “Python JSON REST API wrapper library: a How-To in 15 simple steps”

Very nice article series! This covers a lot of topics I’ve had to learn the hard way by building my own REST API client. Here are a couple other points worth mentioning:

* For more complex data models, the attrs library (https://github.com/python-attrs/attrs) is fantastic! It has handy features for validation, conversion, and lots more. It also has some nice integrations with other popular python tools and libraries like mypy and rich.
* A caching layer is extremely useful for an API client, especially if the server provides caching headers, or if it’s slow or rate-limited. I currently maintain requests-cache (https://github.com/reclosedev/requests-cache), which is built for exactly this kind of use case.

Leave a Reply

Your email address will not be published. Required fields are marked *