Skip to main content

Class-based helper for constructing API clients

Project description

API Consumer

Create clients for consuming endpoints in a class-based way.

Describe the endpoints using a class

from api_client_framework.requests import RequestsEndpoint
from api_client_framework.requests import Methods
from api_client_framework.parsers import NamedTupleParser
from collections import namedtuple

User = namedtuple("User", ["id", "uid", "password","first_name", ...], rename=True)

class UsersEndpoint(RequestsEndpoint):
    method = Methods.GET
    url = "https://random-data-api.com/api/v2/users"
    params = {"response_type": "json"}
    parser = NamedTupleParser(User)

Create your client

import requests

from examples.random_data_api.endpoints import UsersEndpoint
from examples.random_data_api.models import User
from api_client_framework.requests import RequestsClient


class RandomDataAPI(RequestsClient):
    """Client for random-data-api.com"""

    def __init__(self):
        self.session = requests.Session()

    def get_user(self) -> User:
        """Retrieve a single random user"""
        return self._perform_request(UsersEndpoint())

Advanced

Create your own data parsers

...using Parser protocol.

Convert HTTP exceptions in your custom exceptions

...by creating your own exception_handler

Define a base URL for all your endpoints only once

...using BaseUrlSession from requests_toolbelt package

Log responses

...by adding a hook in your requests.Session instance

def print_response(response, *args, **kwargs):
    print(response.url)

session = requests.Session()
session.hooks.setdefault("response", [])
session.hooks["response"].append(print_response)

Examples

There's a small example in this repo, under examples/random_data_api, which implements some endpoints of random-data-api.com

Made with python-api-consumer

  • PyWegowAPI - A client for the public, undocumented, Wegow API

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

api_client_framework-0.1.0.tar.gz (3.3 kB view hashes)

Uploaded Source

Built Distribution

api_client_framework-0.1.0-py3-none-any.whl (4.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page