httprest 0.1.2__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: httprest
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: A library for making simple REST-like HTTP requests
5
5
  Home-page: https://github.com/litteratum/httprest
6
6
  License: MIT
@@ -57,7 +57,7 @@ The library exposes an `HTTPClient` interface and provides two implementations f
57
57
  1. `http.urllib_client.UrllibHTTPClient`: the default implementation, uses the `urllib` library under the hood
58
58
  2. `http.requests_client.RequestsHTTPClient`: uses the `requests` library under the hood
59
59
 
60
- You may also define your own HTTP client like this:
60
+ ### Custom HTTP client
61
61
  ```python
62
62
  from httprest.http import HTTPClient, HTTPResponse
63
63
 
@@ -29,7 +29,7 @@ The library exposes an `HTTPClient` interface and provides two implementations f
29
29
  1. `http.urllib_client.UrllibHTTPClient`: the default implementation, uses the `urllib` library under the hood
30
30
  2. `http.requests_client.RequestsHTTPClient`: uses the `requests` library under the hood
31
31
 
32
- You may also define your own HTTP client like this:
32
+ ### Custom HTTP client
33
33
  ```python
34
34
  from httprest.http import HTTPClient, HTTPResponse
35
35
 
@@ -4,6 +4,8 @@ from typing import Optional as _Optional
4
4
 
5
5
  from httprest.http import HTTPClient as _HTTPClient
6
6
  from httprest.http import HTTPResponse as _HTTPResponse
7
+ from httprest.http.auth import BaseAuth as _BaseAuth
8
+ from httprest.http.cert import ClientCertificate as _ClientCertificate
7
9
  from httprest.http.urllib_client import UrllibHTTPClient as _UrllibHTTPClient
8
10
 
9
11
 
@@ -31,16 +33,29 @@ class API:
31
33
  endpoint: str,
32
34
  json: _Optional[dict] = None,
33
35
  headers: _Optional[dict] = None,
36
+ params: _Optional[dict] = None,
37
+ auth: _Optional[_BaseAuth] = None,
38
+ cert: _Optional[_ClientCertificate] = None,
34
39
  ) -> _HTTPResponse:
40
+ # pylint: disable=too-many-arguments
35
41
  """Make API request.
36
42
 
37
- :param method: request HTTP method (case-insensitive)
38
43
  :param endpoint: API endpoint. Will be appended to the base URL
39
- :param json: JSON data to send in the request body
44
+
45
+ Other parameters are the same as for the `HTTPClient.request` method
40
46
  """
41
47
  return self._http_client.request(
42
- method, self._build_url(endpoint), json, headers
48
+ method=method,
49
+ url=self._build_url(endpoint),
50
+ json=json,
51
+ headers=headers,
52
+ params=params,
53
+ auth=auth,
54
+ cert=cert,
43
55
  )
44
56
 
45
57
  def _build_url(self, endpoint: str) -> str:
46
58
  return f"{self._base_url}/{endpoint.strip('/')}"
59
+
60
+ def __str__(self) -> str:
61
+ return f"{self.__class__.__name__}(base_url='{self._base_url}')"
@@ -0,0 +1,8 @@
1
+ """Package for dealing with HTTP."""
2
+
3
+ from .base import HTTPClient, HTTPResponse
4
+
5
+ __all__ = [
6
+ "HTTPClient",
7
+ "HTTPResponse",
8
+ ]
@@ -0,0 +1,31 @@
1
+ """HTTP auth."""
2
+
3
+ import base64
4
+ from abc import ABC, abstractmethod
5
+
6
+
7
+ class BaseAuth(ABC):
8
+ """Auth."""
9
+
10
+ def apply(self, headers: dict) -> dict:
11
+ """Apply auth headers."""
12
+ headers["Authorization"] = self._get_auth_header()
13
+ return headers
14
+
15
+ @abstractmethod
16
+ def _get_auth_header(self) -> str:
17
+ """Get auth header."""
18
+
19
+
20
+ class BasicAuth(BaseAuth):
21
+ """HTTP basic auth."""
22
+
23
+ def __init__(self, username: str, password: str) -> None:
24
+ self.username = username
25
+ self.password = password
26
+
27
+ def _get_auth_header(self) -> str:
28
+ credentials = base64.b64encode(
29
+ f"{self.username}:{self.password}".encode("utf-8")
30
+ ).decode("utf-8")
31
+ return f"Basic {credentials}"
@@ -0,0 +1,68 @@
1
+ """Base client."""
2
+
3
+ import logging
4
+ from abc import ABC, abstractmethod
5
+ from typing import Optional
6
+ from urllib.parse import urlencode
7
+
8
+ from .auth import BaseAuth
9
+ from .cert import ClientCertificate
10
+ from .response import HTTPResponse
11
+
12
+
13
+ class HTTPClient(ABC):
14
+ """Base HTTP client."""
15
+
16
+ def __init__(self, request_timeout: float = 5) -> None:
17
+ self.request_timeout = request_timeout
18
+
19
+ @abstractmethod
20
+ def _request(
21
+ self,
22
+ method: str,
23
+ url: str,
24
+ json: Optional[dict] = None,
25
+ headers: Optional[dict] = None,
26
+ cert: Optional[ClientCertificate] = None,
27
+ ) -> HTTPResponse:
28
+ # pylint: disable=too-many-arguments
29
+ """Perform request.
30
+
31
+ This method must handle all possible HTTP exceptions and raise them
32
+ as `HTTPRequestError`.
33
+
34
+ Headers may be extended if necessary.
35
+
36
+ .. warning:: there is no unified handling for `cert`. The client must
37
+ raise NotImplementedError if client side certificates are not
38
+ supported
39
+ """
40
+
41
+ def request(
42
+ self,
43
+ method: str,
44
+ url: str,
45
+ json: Optional[dict] = None,
46
+ headers: Optional[dict] = None,
47
+ params: Optional[dict] = None,
48
+ auth: Optional[BaseAuth] = None,
49
+ cert: Optional[ClientCertificate] = None,
50
+ ) -> HTTPResponse:
51
+ # pylint: disable=too-many-arguments
52
+ """Perform HTTP request with a given HTTP method.
53
+
54
+ :param method: HTTP method to use
55
+ :param url: API URL
56
+ :param json: JSON data to post
57
+ :param headers: headers
58
+ :param params: query parameters. If provided, the url will be extended
59
+ :param auth: authorization to use. If provided, the headers will be
60
+ extended
61
+ :param cert: client side certificate
62
+ """
63
+ logging.info("%s %s", method.upper(), url)
64
+ if auth:
65
+ headers = auth.apply(headers or {})
66
+ if params:
67
+ url = f"{url}?{urlencode(params)}"
68
+ return self._request(method, url, json, headers=headers, cert=cert)
@@ -0,0 +1,11 @@
1
+ """Certificates."""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class ClientCertificate:
7
+ """Client certificate."""
8
+
9
+ def __init__(self, cert_path: str, key_path: Optional[str] = None) -> None:
10
+ self.cert_path = cert_path
11
+ self.key_path = key_path
@@ -0,0 +1,21 @@
1
+ """HTTP errors."""
2
+
3
+
4
+ class HTTPRequestError(Exception):
5
+ """Base HTTP request error."""
6
+
7
+
8
+ class HTTPConnectionError(HTTPRequestError):
9
+ """Any error related to connection."""
10
+
11
+
12
+ class HTTPTimeoutError(HTTPRequestError):
13
+ """HTTP request timed out."""
14
+
15
+
16
+ class HTTPInvalidResponseError(HTTPRequestError):
17
+ """HTTP response is invalid."""
18
+
19
+
20
+ class HTTPError(HTTPRequestError):
21
+ """HTTP error based on the status code."""
@@ -4,7 +4,9 @@ from typing import Any, Dict, List, Optional, Union
4
4
 
5
5
  from httprest.http.base import HTTPResponse
6
6
 
7
- from .base import HTTPClient, HTTPTimeoutError
7
+ from .base import HTTPClient
8
+ from .errors import HTTPTimeoutError
9
+ from .cert import ClientCertificate
8
10
 
9
11
 
10
12
  class FakeHTTPClient(HTTPClient):
@@ -23,7 +25,9 @@ class FakeHTTPClient(HTTPClient):
23
25
  url: str,
24
26
  json: Optional[dict] = None,
25
27
  headers: Optional[dict] = None,
28
+ cert: Optional[ClientCertificate] = None,
26
29
  ) -> HTTPResponse:
30
+ # pylint:disable=too-many-arguments
27
31
  self.history.append(
28
32
  {
29
33
  "_method": "_request",
@@ -31,6 +35,7 @@ class FakeHTTPClient(HTTPClient):
31
35
  "url": url,
32
36
  "json": json,
33
37
  "headers": headers,
38
+ "cert": cert,
34
39
  }
35
40
  )
36
41
  if not self._responses:
@@ -4,13 +4,10 @@ from typing import Optional
4
4
 
5
5
  import requests
6
6
 
7
- from .base import (
8
- HTTPClient,
9
- HTTPConnectionError,
10
- HTTPRequestError,
11
- HTTPResponse,
12
- HTTPTimeoutError,
13
- )
7
+ from httprest.http import errors as _errors
8
+
9
+ from .base import HTTPClient, HTTPResponse
10
+ from .cert import ClientCertificate
14
11
 
15
12
 
16
13
  class RequestsHTTPClient(HTTPClient):
@@ -26,17 +23,32 @@ class RequestsHTTPClient(HTTPClient):
26
23
  url: str,
27
24
  json: Optional[dict] = None,
28
25
  headers: Optional[dict] = None,
26
+ cert: Optional[ClientCertificate] = None,
29
27
  ) -> HTTPResponse:
28
+ # pylint: disable=too-many-arguments
29
+ client_cert = None
30
+ if cert:
31
+ client_cert = (
32
+ cert.cert_path
33
+ if cert.key_path is None
34
+ else (cert.cert_path, cert.key_path)
35
+ )
30
36
  try:
31
37
  response: requests.Response = getattr(
32
38
  self._session, method.lower()
33
- )(url, json=json, timeout=self.request_timeout, headers=headers)
39
+ )(
40
+ url,
41
+ json=json,
42
+ timeout=self.request_timeout,
43
+ headers=headers,
44
+ cert=client_cert,
45
+ )
34
46
  except ConnectionError as exc:
35
- raise HTTPConnectionError(exc) from exc
47
+ raise _errors.HTTPConnectionError(exc) from exc
36
48
  except requests.Timeout as exc:
37
- raise HTTPTimeoutError(exc) from exc
49
+ raise _errors.HTTPTimeoutError(exc) from exc
38
50
  except requests.RequestException as exc:
39
- raise HTTPRequestError(exc) from exc
51
+ raise _errors.HTTPRequestError(exc) from exc
40
52
 
41
53
  return HTTPResponse(
42
54
  response.status_code, response.content, dict(response.headers)
@@ -0,0 +1,59 @@
1
+ """HTTP response."""
2
+
3
+ import json as jsonlib
4
+ from typing import Optional
5
+
6
+ from .errors import HTTPError, HTTPInvalidResponseError
7
+
8
+
9
+ class HTTPResponse:
10
+ """HTTP response wrapper."""
11
+
12
+ def __init__(
13
+ self, status_code: int, body: Optional[bytes], headers: dict
14
+ ) -> None:
15
+ self.status_code = status_code
16
+ self.body = body or b""
17
+ self._headers = headers
18
+ self._json = None
19
+
20
+ @property
21
+ def ok(self) -> bool:
22
+ """Return whether the response is successful."""
23
+ return self.status_code >= 200 and self.status_code < 400
24
+
25
+ def raise_for_status(self) -> None:
26
+ """Raise exception if the response is not successful."""
27
+ if 400 <= self.status_code < 500:
28
+ raise HTTPError(f"Client error {self.status_code}")
29
+ if 500 <= self.status_code < 600:
30
+ raise HTTPError(f"Server error {self.status_code}")
31
+
32
+ @property
33
+ def json(self) -> Optional[dict]:
34
+ """Return body as JSON."""
35
+ if self._json is not None:
36
+ return self._json
37
+
38
+ headers = {key.lower(): val for key, val in self._headers.items()}
39
+ if "application/json" in headers.get("content-type", ""):
40
+ try:
41
+ self._json = jsonlib.loads(self.body)
42
+ except Exception as exc:
43
+ raise HTTPInvalidResponseError(
44
+ f"Invalid JSON in response: {exc}"
45
+ ) from exc
46
+
47
+ return self._json
48
+
49
+ def __str__(self) -> str:
50
+ return f"{self.__class__.__name__}(status={self.status_code})"
51
+
52
+ def __repr__(self) -> str:
53
+ return (
54
+ f"{self.__class__.__name__}("
55
+ f"status={self.status_code}, "
56
+ f"body={self.body!r}, "
57
+ f"headers={self._headers}"
58
+ ")"
59
+ )
@@ -7,13 +7,10 @@ import urllib.parse
7
7
  import urllib.request
8
8
  from typing import Optional
9
9
 
10
- from .base import (
11
- HTTPClient,
12
- HTTPConnectionError,
13
- HTTPRequestError,
14
- HTTPResponse,
15
- HTTPTimeoutError,
16
- )
10
+ from httprest.http import errors as _errors
11
+
12
+ from .base import HTTPClient, HTTPResponse
13
+ from .cert import ClientCertificate
17
14
 
18
15
 
19
16
  class UrllibHTTPClient(HTTPClient):
@@ -26,6 +23,7 @@ class UrllibHTTPClient(HTTPClient):
26
23
  url: str,
27
24
  json: Optional[dict] = None,
28
25
  headers: Optional[dict] = None,
26
+ cert: Optional[ClientCertificate] = None,
29
27
  ) -> HTTPResponse:
30
28
  headers = headers or {}
31
29
  data = None
@@ -48,15 +46,15 @@ class UrllibHTTPClient(HTTPClient):
48
46
  response.status, response.read(), dict(response.headers)
49
47
  )
50
48
  except ConnectionError as exc:
51
- raise HTTPConnectionError(exc) from exc
49
+ raise _errors.HTTPConnectionError(exc) from exc
52
50
  except TimeoutError as exc:
53
- raise HTTPTimeoutError(exc) from exc
51
+ raise _errors.HTTPTimeoutError(exc) from exc
54
52
  except urllib.error.HTTPError as exc:
55
53
  return HTTPResponse(
56
54
  exc.status or 500, exc.read(), dict(exc.headers)
57
55
  )
58
56
  except urllib.error.URLError as exc:
59
- raise HTTPRequestError(exc) from exc
57
+ raise _errors.HTTPRequestError(exc) from exc
60
58
 
61
59
  def __str__(self) -> str:
62
60
  return self.__class__.__name__
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "httprest"
3
- version = "0.1.2"
3
+ version = "0.2.0"
4
4
  description = "A library for making simple REST-like HTTP requests"
5
5
  authors = ["Andrii Nechaiev <andrewnech@gmail.com>"]
6
6
  readme = "README.md"
@@ -1,17 +0,0 @@
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
- ]
@@ -1,107 +0,0 @@
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)
File without changes
File without changes