Package: rest3client
rest3clientrest3client is an abstraction of the HTTP requests library (https://pypi.org/project/requests/) providing a simpler API for consuming HTTP REST APIs.The library further abstracts the underlying HTTP requests methods providing equivalent methods for GET, POST, PATCH, PUT and DELETE. The library includes a RESTclient class that implements a consistent approach for processing request responses, extracting error messages from responses, providing standard headers to request methods, and enabling resiliency through integration with the retrying library. It also supports paging for REST APIs that leverage link headers. The abstraction enables the consumer to focus on their business logic and less on the complexites of setting up requests and processing request responses.A subclass inheriting RESTclient can override the base methods providing further customization and flexibility including the ability to automatically retry on exceptions.Supported Authentication SchemesThe library supports most popular authentication schemes:No authenticationBasic authenticationAPI Key-based authenticationBearer token authenticationToken authenticationCertificate-based authenticationJWT authenticationInstallationpipinstallrest3clientAPI UsageThe examples below show how RESTclient can be used to consume the GitHub REST API. However RESTclient can be used to consume just about any REST API.>>>fromrest3clientimportRESTclientRESTclientAuthentication# no authentication>>>client=RESTclient('api.github.com')# basic authentication>>>client=RESTclient('my-api.my-company.com',username='--my-user--',password='--my-password--')# bearer token authentication>>>client=RESTclient('api.github.com',bearer_token='--my-token--')# token authentication>>>client=RESTclient('codecov.io',token='--my-token--')# certificate-based authentication using certificate and password>>>client=RESTclient('my-api.my-company.com',certfile='/path/to/my-certificate.pem',certpass='--my-certificate-password--')# certificate-based authentication using certificate and private key>>>client=RESTclient('my-api.my-company.com',certfile='/path/to/my-certificate.pem',certkey='/path/to/my-certificate-private.key')# jwt authentication>>>client=RESTclient('my-api.my-company.com',jwt='--my-jwt--')GETrequest# return json response>>>client.get('/rate_limit')['resources']['core']{'limit':60,'remaining':37,'reset':1588898701}# return raw resonse>>>client.get('/rate_limit',raw_response=True)<Response[200]>POSTrequest>>>client.post('/user/repos',json={'name':'test-repo1'})['full_name']'soda480/test-repo1'>>>client.post('/repos/soda480/test-repo1/labels',json={'name':'label1'})['url']'https://api.github.com/repos/soda480/test-repo1/labels/label1'PATCHrequest>>>client.patch('/repos/soda480/test-repo1/labels/label1',json={'description':'my label'})['url']'https://api.github.com/repos/soda480/test-repo1/labels/label1'PUTrequest>>>client.put(endpoint,data=None,json=None,**kwargs)DELETErequest>>>client.delete('/repos/soda480/test-repo1')HEADrequest>>>response=client.head('/user/repos',raw_response=True)>>>response.headersPagingPaging is provided for REST APIs that make use oflink headers.GET alldirective - Get all pages from an endpoint and return list containing only matching attributesforrepoinclient.get('/orgs/edgexfoundry/repos',_get='all',_attributes=['full_name']):print(repo['full_name'])GET pagedirective - Yield a page from endpointforpageinclient.get('/user/repos',_get='page'):forrepoinpage:print(repo['full_name'])RetriesAdd support for retry using theretryinglibrary:https://pypi.org/project/retrying/Instantiating RESTclient with aretrieskey word argument will decorate all request methods (get,put,post,deleteandpatch) with a retry decorator using the provided arguments. For example, to retry on any error waiting 2 seconds between retries and limiting retry attempts to 3.>>>client=RESTclient('api.github.com',retries=[{'wait_fixed':2000,'stop_max_attempt_number':3}])Multiple retry specifications can be provided, however the arguments providedmustadhere to the retrying specification.Specifying retries for specific exceptions in subclasses is simple. RESTclient will automatically discover all retry methods defined in subclasses and decorate all request methods accordingly. Arguments for the retry decorator must be provided in the docstring for the respective retry method. Retry methods must begin withretry_.For example:@staticmethoddefretry_connection_error(exception):""" return True if exception is ProxyError False otherwiseretry:wait_random_min:10000wait_random_max:20000stop_max_attempt_number:6"""ifisinstance(exception,ProxyError):returnTruereturnFalseAdding the method above to a subclass of RESTclient will have the affect of decorating all the request methods with the following decorator:@retry(retry_on_exception=retry_connection_error,'wait_random_min'=10000,'wait_random_max'=20000,'stop_max_attempt_number'=6)You also have the option of overriding any of the retry argument with environment variables. The environment variable must be of the form${retry_method_name}_${argument}in all caps. For example, setting the following environment variables will override the static settings in theretry_connection_errormethod docstring:exportRETRY_CONNECTION_ERROR_WAIT_RANDOM_MIN=5000exportRETRY_CONNECTION_ERROR_WAIT_RANDOM_MAX=15000Certificate Authority (CA) BundleTherest3clientmodule's default location for the CA Bundle is/etc/ssl/certs/ca-certificates.crt. This location can be overridden in two different ways:setting theREQUESTS_CA_BUNDLEenvironment variable to the desired locationspecifying thecabundleparameter to the RESTclient constructor:client=RESTclient(bearer_token="--token--",cabundle='/location/to/your/cabundle')Real EamplesSeeGitHub3APIfor an example of how RESTclient can be subclassed to provide further custom functionality for a specific REST API (including retry on exceptions).CLI UsageRESTclient comes packaged with a command line interace (CLI) that can be used to consume REST APIs using the RESTclient class. To consume the CLI simply build and run the Docker container as described below, except when building the image exclude the--target build-imageargument.usage:rest[-h][--addressADDRESS][--jsonJSON_DATA][--headersHEADERS_DATA][--attributesATTRIBUTES][--debug][--raw][--key]methodendpoint

ACLIforrest3client

positionalarguments:methodHTTPrequestmethodendpointRESTAPIendpoint

optionalarguments:-h,--helpshowthishelpmessageandexit--addressADDRESSHTTPrequestwebaddress--jsonJSON_DATAstringrepresentingJSONserializableobjecttosendtoHTTPrequestmethod--headersHEADERS_DATAstringrepresentingheadersdictionarytosendtoHTTPrequestmethod--attributesATTRIBUTESattributestofilterfromresponse-ifusedwith--rawwillfilterfromheadersotherwisewillfilterfromJSONresponse--debugdisplaydebugmessagestostdout--rawreturnrawresponsefromHTTPrequestmethod--keyreturnkeyvalueinresponse-onlyifresponseisadictionarycontainingasinglekeyvalueSet environment variables prefixed withR3C_.To set the web address of the API:exportR3C_ADDRESS=my-api.my-company.comFor bearer token authentication:exportR3C_BEARER_TOKEN=--my-token--For token authentication:exportR3C_TOKEN=--my-token--For basic authentication:exportR3C_USERNAME='--my-username--'exportR3C_PASSWORD='--my-password--'For certificate-based authentication:exportR3C_CERTFILE='/path/to/my-certificate.pem'exportR3C_CERTPASS='--certificate-password--'For jwt-based authentication:exportR3C_JWT=--my-jwt--Some examples for how to execute the CLI to consume the GitHUB API:restPOST/user/repos--json"{'name': 'test-repo1'}"--attributes"name, private, description, permissions"restGET/user/repos--attributes"name, full_name, private, description, permissions"restPOST/repos/soda480/test-repo1/labels--json"{'name': 'label1', 'color': 'C7EFD5'}"--attributesurl

restPATCH/repos/soda480/test-repo1/labels/label1--json"{'description': 'my label'}"--attributesurl

restDELETE/repos/soda480/test-repo1/labels/label1

restGET/repos/soda480/test-repo1/labels--attributesname

restDELETE/repos/soda480/test-repo1--debug

restGET/rate_limit--rawDevelopmentEnsure the latest version of Docker is installed on your development server. Fork and clone the repository.Build the Docker image:dockerimagebuild\--targetbuild-image\--build-arghttp_proxy\--build-arghttps_proxy\-t\rest3client:latest.Run the Docker container:dockercontainerrun\--rm\-it\-ehttp_proxy\-ehttps_proxy\-v$PWD:/code\rest3client:latest\bashExecute the build:pyb-XNOTE: commands above assume working behind a proxy, if not then the proxy arguments to both the docker build and run commands can be removed.