httprest 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
httprest-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Andrii Nechaiev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.1
2
+ Name: httprest
3
+ Version: 0.1.0
4
+ Summary: A library for making simple REST-like HTTP requests
5
+ Home-page: https://github.com/litteratum/httprest
6
+ License: MIT
7
+ Author: Andrii Nechaiev
8
+ Author-email: andrewnech@gmail.com
9
+ Requires-Python: >=3.9,<4.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Topic :: Utilities
24
+ Project-URL: Repository, https://github.com/litteratum/httprest
25
+ Description-Content-Type: text/markdown
26
+
27
+ # httprest
28
+ `httprest` is a minimalistic framework for communicating with REST APIs.
29
+ Its goal is to reduce a boilerplate code required to communicate with APIs.
30
+ * It has the `http` package exposing an HTTP client interface. There is also a client implementation that uses `urllib` under the hood. So no need to use extra libraries like `requests`
31
+ * It has the `api.API` class which may be overridden and used to make API calls
32
+
33
+ ## Usage
34
+ ```python
35
+ from httprest import API
36
+
37
+ class MyAPI(API):
38
+ def operation(self):
39
+ result = self._request("POST", "/operation/endpoint", json={...})
40
+ if result.ok:
41
+ print(result.json)
42
+
43
+ api = MyAPI("http://api.com")
44
+ api.operation()
45
+ ```
46
+
47
+ ## Installation
48
+ ```bash
49
+ pip install httprest
50
+ ```
51
+
52
+
53
+ ## HTTP client
54
+ The library exposes an `HTTPClient` interface.
55
+ There is also an `http.urllib_client.UrllibHTTPClient` implementation that is used by default.
56
+
57
+ You may define your own HTTP client like this:
58
+ ```python
59
+ from httprest.http import HTTPClient, HTTPResponse
60
+
61
+ class MyHTTPClient(HTTPClient):
62
+ def _request(...) -> HTTPResponse
63
+ ```
64
+
65
+ And then you simply use it in the API client:
66
+ ```python
67
+
68
+ api = MyAPI(..., http_client=MyHTTPClient())
69
+ ```
70
+
@@ -0,0 +1,43 @@
1
+ # httprest
2
+ `httprest` is a minimalistic framework for communicating with REST APIs.
3
+ Its goal is to reduce a boilerplate code required to communicate with APIs.
4
+ * It has the `http` package exposing an HTTP client interface. There is also a client implementation that uses `urllib` under the hood. So no need to use extra libraries like `requests`
5
+ * It has the `api.API` class which may be overridden and used to make API calls
6
+
7
+ ## Usage
8
+ ```python
9
+ from httprest import API
10
+
11
+ class MyAPI(API):
12
+ def operation(self):
13
+ result = self._request("POST", "/operation/endpoint", json={...})
14
+ if result.ok:
15
+ print(result.json)
16
+
17
+ api = MyAPI("http://api.com")
18
+ api.operation()
19
+ ```
20
+
21
+ ## Installation
22
+ ```bash
23
+ pip install httprest
24
+ ```
25
+
26
+
27
+ ## HTTP client
28
+ The library exposes an `HTTPClient` interface.
29
+ There is also an `http.urllib_client.UrllibHTTPClient` implementation that is used by default.
30
+
31
+ You may define your own HTTP client like this:
32
+ ```python
33
+ from httprest.http import HTTPClient, HTTPResponse
34
+
35
+ class MyHTTPClient(HTTPClient):
36
+ def _request(...) -> HTTPResponse
37
+ ```
38
+
39
+ And then you simply use it in the API client:
40
+ ```python
41
+
42
+ api = MyAPI(..., http_client=MyHTTPClient())
43
+ ```
@@ -0,0 +1,7 @@
1
+ """The library package."""
2
+
3
+ from .api import API
4
+
5
+ __all__ = [
6
+ "API",
7
+ ]
@@ -0,0 +1,46 @@
1
+ """API."""
2
+
3
+ from typing import Optional as _Optional
4
+
5
+ from httprest.http import HTTPClient as _HTTPClient
6
+ from httprest.http import HTTPResponse as _HTTPResponse
7
+ from httprest.http.urllib_client import UrllibHTTPClient as _UrllibHTTPClient
8
+
9
+
10
+ class API:
11
+ """API.
12
+
13
+ This class is used to communicated with the API.
14
+ """
15
+
16
+ def __init__(
17
+ self, base_url: str, http_client: _Optional[_HTTPClient] = None
18
+ ) -> None:
19
+ """Init API.
20
+
21
+ :param base_url: API base URL
22
+ :param http_client: HTTP client to use for making HTTP requests.
23
+ If not provided, the default one will be used
24
+ """
25
+ self._base_url = base_url.rstrip("/")
26
+ self._http_client = http_client or _UrllibHTTPClient()
27
+
28
+ def _request(
29
+ self,
30
+ method: str,
31
+ endpoint: str,
32
+ json: _Optional[dict] = None,
33
+ headers: _Optional[dict] = None,
34
+ ) -> _HTTPResponse:
35
+ """Make API request.
36
+
37
+ :param method: request HTTP method (case-insensitive)
38
+ :param endpoint: API endpoint. Will be appended to the base URL
39
+ :param json: JSON data to send in the request body
40
+ """
41
+ return self._http_client.request(
42
+ method, self._build_url(endpoint), json, headers
43
+ )
44
+
45
+ def _build_url(self, endpoint: str) -> str:
46
+ return f"{self._base_url}/{endpoint.strip('/')}"
@@ -0,0 +1,17 @@
1
+ """Package for dealing with HTTP."""
2
+
3
+ from .base import (
4
+ HTTPClient,
5
+ HTTPConnectionError,
6
+ HTTPRequestError,
7
+ HTTPResponse,
8
+ HTTPTimeoutError,
9
+ )
10
+
11
+ __all__ = [
12
+ "HTTPClient",
13
+ "HTTPConnectionError",
14
+ "HTTPRequestError",
15
+ "HTTPResponse",
16
+ "HTTPTimeoutError",
17
+ ]
@@ -0,0 +1,107 @@
1
+ """Base client."""
2
+
3
+ import json as jsonlib
4
+ import logging
5
+ from abc import ABC, abstractmethod
6
+ from typing import Optional
7
+
8
+
9
+ class HTTPRequestError(Exception):
10
+ """Base HTTP request error."""
11
+
12
+
13
+ class HTTPConnectionError(HTTPRequestError):
14
+ """Any error related to connection."""
15
+
16
+
17
+ class HTTPTimeoutError(HTTPRequestError):
18
+ """HTTP request timed out."""
19
+
20
+
21
+ class HTTPInvalidResponseError(HTTPRequestError):
22
+ """HTTP response is invalid."""
23
+
24
+
25
+ class HTTPResponse:
26
+ """HTTP response wrapper."""
27
+
28
+ def __init__(
29
+ self, status_code: int, body: Optional[bytes], headers: dict
30
+ ) -> None:
31
+ self.status_code = status_code
32
+ self.body = body or b""
33
+ self._headers = headers
34
+ self._json = None
35
+
36
+ def ok(self) -> bool:
37
+ """Return whether the response is successful."""
38
+ return self.status_code >= 200 and self.status_code < 400
39
+
40
+ @property
41
+ def json(self) -> Optional[dict]:
42
+ """Return body as JSON."""
43
+ if self._json is not None:
44
+ return self._json
45
+
46
+ headers = {key.lower(): val for key, val in self._headers.items()}
47
+ if "application/json" in headers.get("content-type", ""):
48
+ try:
49
+ self._json = jsonlib.loads(self.body)
50
+ except Exception as exc:
51
+ raise HTTPInvalidResponseError(
52
+ f"Invalid JSON in response: {exc}"
53
+ ) from exc
54
+
55
+ return self._json
56
+
57
+ def __str__(self) -> str:
58
+ return f"{self.__class__.__name__}(status={self.status_code})"
59
+
60
+ def __repr__(self) -> str:
61
+ return (
62
+ f"{self.__class__.__name__}("
63
+ f"status={self.status_code}, "
64
+ f"body={self.body!r}, "
65
+ f"headers={self._headers}"
66
+ ")"
67
+ )
68
+
69
+
70
+ class HTTPClient(ABC):
71
+ """Base HTTP client."""
72
+
73
+ def __init__(self, request_timeout: float = 5) -> None:
74
+ self.request_timeout = request_timeout
75
+
76
+ @abstractmethod
77
+ def _request(
78
+ self,
79
+ method: str,
80
+ url: str,
81
+ json: Optional[dict] = None,
82
+ headers: Optional[dict] = None,
83
+ ) -> HTTPResponse:
84
+ """Perform request.
85
+
86
+ This method must handle all possible HTTP exceptions and raise them
87
+ as `HTTPRequestError`.
88
+
89
+ Headers may be extended if necessary.
90
+ """
91
+
92
+ def request(
93
+ self,
94
+ method: str,
95
+ url: str,
96
+ json: Optional[dict] = None,
97
+ headers: Optional[dict] = None,
98
+ ) -> HTTPResponse:
99
+ """Perform HTTP request with a given HTTP method.
100
+
101
+ :param method: HTTP method to use
102
+ :param url: API URL
103
+ :param json: JSON data to post
104
+ :param headers: headers
105
+ """
106
+ logging.info("%s %s", method.upper(), url)
107
+ return self._request(method, url, json, headers=headers)
@@ -0,0 +1,62 @@
1
+ """HTTP client which uses `urllib` under the hood."""
2
+
3
+ import json as _jsonlib
4
+ import urllib
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from typing import Optional
9
+
10
+ from .base import (
11
+ HTTPClient,
12
+ HTTPConnectionError,
13
+ HTTPRequestError,
14
+ HTTPResponse,
15
+ HTTPTimeoutError,
16
+ )
17
+
18
+
19
+ class UrllibHTTPClient(HTTPClient):
20
+ """`urllib` HTTP client."""
21
+
22
+ # pylint: disable=too-many-arguments
23
+ def _request(
24
+ self,
25
+ method: str,
26
+ url: str,
27
+ json: Optional[dict] = None,
28
+ headers: Optional[dict] = None,
29
+ ) -> HTTPResponse:
30
+ headers = headers or {}
31
+ data = None
32
+
33
+ if json:
34
+ headers["Content-Type"] = "application/json"
35
+ data = _jsonlib.dumps(json).encode()
36
+
37
+ try:
38
+ with urllib.request.urlopen(
39
+ urllib.request.Request(
40
+ url,
41
+ data=data,
42
+ headers=headers,
43
+ method=method.upper(),
44
+ ),
45
+ timeout=self.request_timeout,
46
+ ) as response:
47
+ return HTTPResponse(
48
+ response.status, response.read(), dict(response.headers)
49
+ )
50
+ except ConnectionError as exc:
51
+ raise HTTPConnectionError(exc) from exc
52
+ except TimeoutError as exc:
53
+ raise HTTPTimeoutError(exc) from exc
54
+ except urllib.error.HTTPError as exc:
55
+ return HTTPResponse(
56
+ exc.status or 500, exc.read(), dict(exc.headers)
57
+ )
58
+ except urllib.error.URLError as exc:
59
+ raise HTTPRequestError(exc) from exc
60
+
61
+ def __str__(self) -> str:
62
+ return self.__class__.__name__
@@ -0,0 +1,85 @@
1
+ [tool.poetry]
2
+ name = "httprest"
3
+ version = "0.1.0"
4
+ description = "A library for making simple REST-like HTTP requests"
5
+ authors = ["Andrii Nechaiev <andrewnech@gmail.com>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ repository = "https://github.com/litteratum/httprest"
9
+ classifiers=[
10
+ "Development Status :: 4 - Beta",
11
+ "Intended Audience :: Developers",
12
+ "Programming Language :: Python",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.9",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: Implementation :: CPython",
19
+ "Topic :: Software Development :: Libraries",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Operating System :: POSIX :: Linux",
22
+ "Topic :: Utilities",
23
+ ]
24
+
25
+ [tool.poetry.dependencies]
26
+ python = "^3.9"
27
+
28
+
29
+ [tool.poetry.group.test.dependencies]
30
+ pytest = "^8.3.2"
31
+ pytest-cov = "^5.0.0"
32
+
33
+
34
+ [tool.poetry.group.lint.dependencies]
35
+ black = {version = "^24.8.0", python = "3.11"}
36
+ pylint = {version = "^3.2.6", python = "3.11"}
37
+ flake8 = {version = "^7.1.1", python = "3.11"}
38
+ flake8-bugbear = {version = "^24.8.19", python = "3.11"}
39
+ mypy = {version = "^1.11.1", python = "3.11"}
40
+ pydocstyle = {version = "^6.3.0", python = "3.11"}
41
+
42
+ [build-system]
43
+ requires = ["poetry-core"]
44
+ build-backend = "poetry.core.masonry.api"
45
+
46
+ [tool.black]
47
+ line-length = 79
48
+
49
+ [tool.isort]
50
+ line_length = 79
51
+ profile = "black"
52
+
53
+ [tool.flake8]
54
+ max-line-length = 79
55
+ extend-ignore = "E203"
56
+
57
+ [tool.mypy]
58
+ ignore_missing_imports = true
59
+
60
+ [tool.pydocstyle]
61
+ ignore = "D102,D105,D107,D203,D213,D413"
62
+
63
+ [tool.pylint.'MAIN']
64
+ py-version=3.7
65
+
66
+ [tool.pylint.'BASIC']
67
+ good-names = [
68
+ "i",
69
+ "j",
70
+ "k",
71
+ "_",
72
+ "id",
73
+ "db"
74
+ ]
75
+
76
+ [tool.pylint.'MESSAGES CONTROL']
77
+ disable = [
78
+ "fixme",
79
+ ]
80
+
81
+ [tool.pylint.'VARIABLES']
82
+ allowed-redefined-builtins = "id"
83
+
84
+ [tool.pylint.'DESIGN']
85
+ min-public-methods=0