REST tools in python - common code for client and server
Project description
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 ofRestClient
that supports OAuth2 token refresh using the OpenID Connect Discovery protocol for an authentication server. -
ClientCredentialsAuth
: UsesOpenIDRestClient
in 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
: UsesOpenIDRestClient
to perform a "device" login for a user. Use this for user-based terminal applications that need to perform REST API calls. TheSavedDeviceGrantAuth
can 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)
...
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file wipac-rest-tools-1.8.2.tar.gz
.
File metadata
- Download URL: wipac-rest-tools-1.8.2.tar.gz
- Upload date:
- Size: 32.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.11.2 readme-renderer/44.0 requests/2.32.3 requests-toolbelt/1.0.0 urllib3/2.2.3 tqdm/4.66.5 importlib-metadata/8.5.0 keyring/25.4.1 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.15
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | f21221565d06db9aaacb2cea0056ac2b0a79c5feefe2ff67db82898590fec850 |
|
MD5 | 1cc1bf488c249e532d9bdbe850301a18 |
|
BLAKE2b-256 | 8732bdf8db7a9db90d786ffeebb74a33727691a844f0b2193e3627b8ee720913 |
File details
Details for the file wipac_rest_tools-1.8.2-py3-none-any.whl
.
File metadata
- Download URL: wipac_rest_tools-1.8.2-py3-none-any.whl
- Upload date:
- Size: 38.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.11.2 readme-renderer/44.0 requests/2.32.3 requests-toolbelt/1.0.0 urllib3/2.2.3 tqdm/4.66.5 importlib-metadata/8.5.0 keyring/25.4.1 rfc3986/2.0.0 colorama/0.4.6 CPython/3.10.15
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 70990ebf8d1be6e2c17278d116f7ea2f7fa37f0034b144dc0e2fd1ce0acb057e |
|
MD5 | 03eb6cf4f9d622be8d2e97e4f81c796a |
|
BLAKE2b-256 | 76661b50eed263aeb55e3af49449fd80fd401b41fa4655d3a6314c5d4c758057 |