rest-tools
This project contains REST tools in python, as common code for multiple other projects under https://github.com/WIPACrepo.
All code uses python asyncio, so is fully asyncronous.
Note that both the client and server assume starting the asyncio loop happens elsewhere - they do not start the loop themselves.
Client
A REST API client exists under rest_tools.client. Use as:
from rest_tools.client import RestClient
api = RestClient('http://my.site.here/api', token='XXXX')
ret = await api.request('GET', '/fruits/apple')
ret = await api.request('POST', '/fruits', {'name': 'banana'})
There are several variations of the client for OAuth2/OpenID support:
-
OpenIDRestClient: A child ofRestClientthat supports OAuth2 token refresh using the OpenID Connect Discovery protocol for an authentication server. -
ClientCredentialsAuth: UsesOpenIDRestClientin combination with OAuth2 client credentials (client ID and secret) for service-based auth. Use this for long-lived services that need to perform REST API calls. -
DeviceGrantAuth/SavedDeviceGrantAuth: UsesOpenIDRestClientto perform a "device" login for a user. Use this for user-based terminal applications that need to perform REST API calls. TheSavedDeviceGrantAuthcan save the refresh token to disk, allowing repeated application sessions without having to log in again.
Server
A REST API server exists under rest_tools.server. Use as:
import asyncio
from rest_tools.server import RestServer, RestHandler
class Fruits(RestHandler):
def post(self):
# handle a new fruit
self.write({})
server = RestServer()
server.add_route('/fruits', Fruits)
server.startup(address='my.site.here', port=8080)
asyncio.get_event_loop().run_forever()
The server uses Tornado to handle HTTP connections. It is recommended to use Apache or Nginx as a front-facing proxy, to handle TLS sessions and non-standard HTTP requests in production.
Handling Arguments Server-side
server.ArgumentHandler is a robust wrapper around argparse.ArgumentParser, extended for use in handling REST arguments, both query arguments and JSON-encoded body arguments. The intended design of this class is to follow the argparse pattern as closely as possible.
from rest_tools.server import RestHandler, ArgumentHandler, ArgumentSource
class Fruits(RestHandler):
def get(self):
argo = ArgumentHandler(ArgumentSource.QUERY_ARGUMENTS, self)
argo.add_argument('name', type=str) # de-facto required
argo.add_argument('alias', dest='other_names', type=str, nargs='*', default=[]) # list
argo.add_argument('is-citrus', type=bool, default=False)
argo.add_argument('amount', type=float, required=True)
args = argo.parse_args()
fruit = get_fruit(args.name, args.other_names, args.is_citrus, args.amount)
...
def post(self):
argo = ArgumentHandler(ArgumentSource.JSON_BODY_ARGUMENTS, self)
argo.add_argument('name', type=str) # de-facto required
argo.add_argument('other-names', type=list, default=[])
argo.add_argument('supply', type=dict, required=True)
def _origin(val):
try:
return {'USA': 'United States of America', 'MEX': 'Mexico'}[val]
except KeyError:
# raise a ValueError or TypeError to propagate a 400 Error
raise ValueError('Invalid origin')
argo.add_argument('country_code', dest='origin', type=_origin, required=True)
args = argo.parse_args()
add_to_basket(args.name, args.other_names, args.supply, args.origin)
...
Metadata
Release files for wipac-rest-tools 1.7.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| wipac-rest-tools-1.7.6.tar.gz | 32.3 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| wipac_rest_tools-1.7.6-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 69.8 kB
Release files / wipac-rest-tools-1.7.6.tar.gz
| Download URL | wipac-rest-tools-1.7.6.tar.gz |
|---|---|
| Size | 32.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9aa744df2be582ee210ea7dd3613a3dac4981995e8edff6002f1326b651e3d91
|
|
BLAKE2b-256 checksum How to use checksums |
bf784afdd8ba1e1b74d1cf7fcd769a19cbf49b1ea7321ee6090bb8148a0b0c44
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.8.0 pkginfo/1.11.1 readme-renderer/43.0 requests/2.32.3 requests-toolbelt/1.0.0 urllib3/2.2.2 tqdm/4.66.4 importlib-metadata/8.0.0 keyring/25.2.1 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.14
|
Release files / wipac_rest_tools-1.7.6-py3-none-any.whl
| Download URL | wipac_rest_tools-1.7.6-py3-none-any.whl |
|---|---|
| Size | 37.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
235580547c7d8829bcbcd598252e9b1317cb8b9149ca2512e3fea1bc59ca83a7
|
|
BLAKE2b-256 checksum How to use checksums |
d9ecc87a6dcee9f3466224f5a54d11c11c5a2285022089ad1fb4627a321812d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.8.0 pkginfo/1.11.1 readme-renderer/43.0 requests/2.32.3 requests-toolbelt/1.0.0 urllib3/2.2.2 tqdm/4.66.4 importlib-metadata/8.0.0 keyring/25.2.1 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.14
|