httprest 0.1.0__py3-none-any.whl
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/__init__.py +7 -0
- httprest/api.py +46 -0
- httprest/http/__init__.py +17 -0
- httprest/http/base.py +107 -0
- httprest/http/urllib_client.py +62 -0
- httprest-0.1.0.dist-info/LICENSE +21 -0
- httprest-0.1.0.dist-info/METADATA +70 -0
- httprest-0.1.0.dist-info/RECORD +9 -0
- httprest-0.1.0.dist-info/WHEEL +4 -0
httprest/__init__.py
ADDED
httprest/api.py
ADDED
|
@@ -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
|
+
]
|
httprest/http/base.py
ADDED
|
@@ -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,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,9 @@
|
|
|
1
|
+
httprest/__init__.py,sha256=Cq_jgg1V1q8ZzYw66uHlmpRsCgW9AtROyWbYoAj_D_Q,75
|
|
2
|
+
httprest/api.py,sha256=eooOY8E76MrGREBPNj1Qylq4otpsk1YefAiMCanpyyk,1377
|
|
3
|
+
httprest/http/__init__.py,sha256=uvOlTmAxNjDvZzbkT99NSWvGc8o3pt1VnfKcnAmythU,291
|
|
4
|
+
httprest/http/base.py,sha256=2rbI1ZXhJapawMG5ghy0IanmDE7zndDgc_zGj5qxsjM,2831
|
|
5
|
+
httprest/http/urllib_client.py,sha256=6jBrYbUx3VX-FF6CN3PJOl2ufWrXztGSefr3eIFb7eg,1721
|
|
6
|
+
httprest-0.1.0.dist-info/LICENSE,sha256=Fz2wBg189T0BPQMczcNcTafmw9iRHZHyfhsdN8_264I,1072
|
|
7
|
+
httprest-0.1.0.dist-info/METADATA,sha256=D6NfjZaBLr8IWrzRwQ8J_bzsu08cZXjMhxICVNnDDx0,2259
|
|
8
|
+
httprest-0.1.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
|
9
|
+
httprest-0.1.0.dist-info/RECORD,,
|