diff --git a/README.md b/README.md index 5129b9b..bf77d62 100644 --- a/README.md +++ b/README.md @@ -19,34 +19,51 @@ import blockscore client = blockscore.Client({'api_key':'Your API Key'}) ``` -## Verifications - -### List all verifications +## People + +### List all people ```python -verification_list = client.verification.all() -verification_list = verification_list.body +people_list = client.people.all() +people_list = people_list.body ``` -### List `5` verifications +### List `5` people ```python -verification_list = client.verification.all(count=5) -verification_list = verification_list.body +people_list = client.people.all(count=5) +people_list = people_list.body ``` - -### View a verification by ID + +### View a person by ID ```python -verification = client.verification.retrieve(verification_id) -verification = verification.body +person = client.people.retrieve(person_id) +person = person.body ``` -### Create a new verification +### Create a new person ```python -verification = client.verification.create('1980-01-01',{'ssn': '0000'},{'first': 'john', 'last': 'doe'},{'street1': '1 Infinite Loop', 'city': 'Palo Alto', 'state': 'ca', 'postal_code': '94309', 'country_code': 'us'}) -verification = verification.body +test_identity = { + "name_first": "John", + "name_middle": "Pearce", + "name_last": "Doe", + "birth_day": "23", + "birth_month": "8", + "birth_year": "1980", + "document_type": "ssn", + "document_value": "0000", + "address_street1": "1 Infinite Loop", + "address_street2": "Apt 6", + "address_city": "Cupertino", + "address_subdivision": "CA", + "address_postal_code": "95014", + "address_country_code": "US", + } + +person = client.people.create(test_identity) +person = person.body ``` ## Question Sets @@ -54,14 +71,14 @@ verification = verification.body ### Create a new question set ```python -question_set = client.question_set.create(verification_id) +question_set = client.question_sets.create(person_id) question_set = question_set.body ``` ### Score a question set ```python -score = self.client.question_set.score(verif_id, qset_id, [ +score = self.client.question_sets.score(qset_id, [ {'question_id':1, 'answer_id':1}, {'question_id':2, 'answer_id':1}, {'question_id':3, 'answer_id':1}, @@ -90,7 +107,7 @@ score = score.body ## Contributing to BlockScore - + * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet. * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it. * Fork the project. diff --git a/blockscore/__init__.py b/blockscore/__init__.py index c475573..feef1d4 100644 --- a/blockscore/__init__.py +++ b/blockscore/__init__.py @@ -1,2 +1,3 @@ -from .client import Client -api_key = None # use blockscore.api_key = 'your_api_key' after importing blockscore \ No newline at end of file +from blockscore.client import Client +api_key = None # use blockscore.api_key = 'your_api_key' after importing blockscore + diff --git a/blockscore/api/__init__.py b/blockscore/api/__init__.py index 1bfe644..aaf4af7 100644 --- a/blockscore/api/__init__.py +++ b/blockscore/api/__init__.py @@ -1,3 +1,4 @@ # Import all the classes into api module -from . import verification -from . import question_set +from blockscore.api import people +from blockscore.api import question_sets +from blockscore.api import companies diff --git a/blockscore/api/companies.py b/blockscore/api/companies.py index a42e414..d045ca2 100644 --- a/blockscore/api/companies.py +++ b/blockscore/api/companies.py @@ -4,32 +4,32 @@ class Companies(): - def __init__(self, client): - self.client = client - - # - # '/companies' POST - # - def create(self, options = {}): - return self.client.post(COMPANIES_PATH, options) - - # - # '/companies/:id' GET - # - def retrieve(self, id, options = {}): - body = options['query'] if 'query' in options else {} - return self.client.get('%s/%s' % (COMPANIES_PATH, str(id)), body) - - # - # '/companies' GET - # - def all(self, count = None, offset = None, options = {}): - body = options['body'] if 'body' in options else {} - - if count: - body['count'] = count - if offset: - body['offset'] = offset - - return self.client.get(COMPANIES_PATH, body) + def __init__(self, client): + self.client = client + + # + # '/companies' POST + # + def create(self, options = {}): + return self.client.post(COMPANIES_PATH, options) + + # + # '/companies/:id' GET + # + def retrieve(self, id, options = {}): + body = options['query'] if 'query' in options else {} + return self.client.get('%s/%s' % (COMPANIES_PATH, str(id)), body) + + # + # '/companies' GET + # + def all(self, count = None, offset = None, options = {}): + body = options['body'] if 'body' in options else {} + + if count: + body['count'] = count + if offset: + body['offset'] = offset + + return self.client.get(COMPANIES_PATH, body) diff --git a/blockscore/api/people.py b/blockscore/api/people.py new file mode 100644 index 0000000..608485d --- /dev/null +++ b/blockscore/api/people.py @@ -0,0 +1,43 @@ +# Returns user api instance + +PEOPLE_PATH = '/people' + +class People(): + + def __init__(self, client): + self.client = client + + # + # '/people' POST + # + # date_of_birth - + # identification - + # name - + # address - + def create(self, options = {}): + response = self.client.post(PEOPLE_PATH, options) + return response + + # + # '/people/:id' GET + # + # id - + def retrieve(self, id, options = {}): + body = options['query'] if 'query' in options else {} + response = self.client.get('%s/%s' % (PEOPLE_PATH, str(id)), body) + return response + + # + # '/people' GET + # + def all(self, count=None, offset=None, options = {}): + body = options['body'] if 'body' in options else {} + + if count != None: + body['count'] = count + if offset != None: + body['offset'] = offset + + response = self.client.get(PEOPLE_PATH, body) + return response + diff --git a/blockscore/api/question_set.py b/blockscore/api/question_set.py deleted file mode 100644 index db29ac7..0000000 --- a/blockscore/api/question_set.py +++ /dev/null @@ -1,43 +0,0 @@ -import json -# -# -class QuestionSet(): - - def __init__(self, client): - self.client = client - - # - # '/questions' POST - # - # verification_id - - def create(self, verification_id, options = {}): - body = options['body'] if 'body' in options else {} - body['verification_id'] = verification_id - - response = self.client.post('/questions', body, options) - - return response - - # - # '/questions/score' POST - # - # verification_id - - # question_set_id - - # answers - - def score(self, verification_id, question_set_id, answers, options = {}): - body = options['body'] if 'body' in options else {} - - # set request type to json for this as server parses questions as json - options['request_type'] = 'json' - - # make the body one json object - body = { - 'verification_id': verification_id, - 'question_set_id': question_set_id, - 'answers': answers - } - - response = self.client.post('/questions/score', body, options) - - return response - diff --git a/blockscore/api/question_sets.py b/blockscore/api/question_sets.py new file mode 100644 index 0000000..d632a66 --- /dev/null +++ b/blockscore/api/question_sets.py @@ -0,0 +1,56 @@ + +QUESTION_SET_PATH = '/question_sets' + +class QuestionSets(): + + def __init__(self, client): + self.client = client + + # + # '/question_sets' POST + # + # verification_id - + def create(self, person_id, options = {}): + body = options['body'] if 'body' in options else {} + body['person_id'] = person_id + + response = self.client.post(QUESTION_SET_PATH, body) + return response + + # + # '/question_sets/:id/:score' POST + # + # answers - + def score(self, id, answers): + body = {} + body['answers'] = answers + + options = {} + options['request_type'] = 'json' + + response = self.client.post('%s/%s/score' % (QUESTION_SET_PATH, str(id)), body, options) + return response + + # + # '/question_sets/:id' GET + # + # id - + def retrieve(self, id): + body = {} + response = self.client.get('%s/%s' % (QUESTION_SET_PATH, str(id)), body) + return response + + # + # '/question_sets' GET + # + def all(self, count=None, offset=None, options = {}): + body = options['body'] if 'body' in options else {} + + if count: + body['count'] = count + if offset: + body['offset'] = offset + + response = self.client.get(QUESTION_SET_PATH, body) + return response + diff --git a/blockscore/api/verification.py b/blockscore/api/verification.py deleted file mode 100644 index 663efff..0000000 --- a/blockscore/api/verification.py +++ /dev/null @@ -1,50 +0,0 @@ -# Returns user api instance -# -class Verification(): - - def __init__(self, client): - self.client = client - - # - # '/verifications' POST - # - # date_of_birth - - # identification - - # name - - # address - - def create(self, date_of_birth, identification, name, address, options = {}): - body = options['body'] if 'body' in options else {} - body['date_of_birth'] = date_of_birth - body['identification'] = identification - body['name'] = name - body['address'] = address - - response = self.client.post('/verifications', body, options) - - return response - - # - # '/verifications/:id' GET - # - # id - - def retrieve(self, id, options = {}): - body = options['query'] if 'query' in options else {} - - response = self.client.get('/verifications/'+str(id), body, options) - - return response - - # - # '/verifications' GET - # - def all(self, count=None, offset=None, options = {}): - body = options['query'] if 'query' in options else {} - - if count != None: - body['count'] = count - if offset != None: - body['offset'] = offset - - response = self.client.get('/verifications', body, options) - - return response diff --git a/blockscore/client.py b/blockscore/client.py index c3c79e7..70bb172 100644 --- a/blockscore/client.py +++ b/blockscore/client.py @@ -1,15 +1,15 @@ -from .http_client import HttpClient +from blockscore.http_client import HttpClient # Assign all the api classes -from .api.verification import Verification -from .api.question_set import QuestionSet -from .api.companies import Companies +from blockscore.api.people import People +from blockscore.api.question_sets import QuestionSets +from blockscore.api.companies import Companies class Client(): - def __init__(self, auth = {}, options = {}): - self.http_client = HttpClient(auth, options) - self.verification = Verification(self.http_client) - self.question_set = QuestionSet(self.http_client) - self.companies = Companies(self.http_client) + def __init__(self, auth = {}, options = {}): + self.http_client = HttpClient(auth, options) + self.people = People(self.http_client) + self.question_sets = QuestionSets(self.http_client) + self.companies = Companies(self.http_client) diff --git a/blockscore/error.py b/blockscore/error.py index bba1812..1863b17 100644 --- a/blockscore/error.py +++ b/blockscore/error.py @@ -1,92 +1,92 @@ -import json STATUS_CODES = { - 'ValidationError': 400, - 'ParameterError': 400, - 'AuthError': 401, - 'NotFoundError': 404, - 'InternalError': 500 + 'ValidationError': 400, + 'ParameterError': 400, + 'AuthError': 401, + 'NotFoundError': 404, + 'InternalError': 500 } # Generic Exception class BlockscoreError(Exception): - - def __init__(self, message=None, json_body=None, http_status=None, - error_type=None, param=None, error_code=None): - super(BlockscoreError, self).__init__(message) - self.error_type = error_type + def __init__(self, message=None, json_body=None, http_status=None, + error_type=None, param=None, error_code=None): + super(BlockscoreError, self).__init__(message) - self.http_status = http_status - self.json_body = json_body + self.error_type = error_type - def __str__(self): - return "Status: {0}. Type: {1}, Message: {2}" \ - .format(self.http_status, self.error_type, self.message) + self.http_status = http_status + self.json_body = json_body + + def __str__(self): + return "Status: {0}. Type: {1}, Message: {2}" \ + .format(self.http_status, self.error_type, self.message) # Input could not be validated. class ValidationError(BlockscoreError): - def __init__(self, message=None, json_body=None, param=None, - error_type=None, error_code=None): + def __init__(self, message=None, json_body=None, param=None, + error_type=None, error_code=None): - status_code = STATUS_CODES['ValidationError'] + status_code = STATUS_CODES['ValidationError'] - super(ValidationError, self).__init__( - message=message, error_type=error_type, - http_status=status_code, json_body=json_body, param=param) + super(ValidationError, self).__init__( + message=message, error_type=error_type, + http_status=status_code, json_body=json_body, param=param) - self.error_code = error_code - self.param = param + self.error_code = error_code + self.param = param - def __str__(self): - return "Status: {0}. Type: {1}, Param: {2}, Code: {3}, Message: {4}" \ - .format(self.http_status, self.error_type, self.param, - self.error_code, self.message) + def __str__(self): + return "Status: {0}. Type: {1}, Param: {2}, Code: {3}, Message: {4}" \ + .format(self.http_status, self.error_type, self.param, + self.error_code, self.message) # Required parameter missing class ParameterError(BlockscoreError): - def __init__(self, message=None, json_body=None, error_type=None): - status_code = STATUS_CODES['ParameterError'] + def __init__(self, message=None, json_body=None, error_type=None): + status_code = STATUS_CODES['ParameterError'] - super(ParameterError, self).__init__( - message=message, error_type=error_type, - http_status=status_code, json_body=json_body) + super(ParameterError, self).__init__( + message=message, error_type=error_type, + http_status=status_code, json_body=json_body) # Invalid API Key class AuthorizationError(BlockscoreError): - def __init__(self, message=None, json_body=None, error_type=None): - status_code = STATUS_CODES['AuthError'] + def __init__(self, message=None, json_body=None, error_type=None): + status_code = STATUS_CODES['AuthError'] - super(AuthorizationError, self).__init__( - message=message, error_type=error_type, - http_status=status_code, json_body=json_body) + super(AuthorizationError, self).__init__( + message=message, error_type=error_type, + http_status=status_code, json_body=json_body) # Tried to reference a nonexistent endpoint class NotFoundError(BlockscoreError): - def __init__(self, message=None, json_body=None, error_type=None): - status_code = STATUS_CODES['NotFoundError'] + def __init__(self, message=None, json_body=None, error_type=None): + status_code = STATUS_CODES['NotFoundError'] - super(NotFoundError, self).__init__( - message=message, error_type=error_type, - http_status=status_code, json_body=json_body) + super(NotFoundError, self).__init__( + message=message, error_type=error_type, + http_status=status_code, json_body=json_body) # Error on the Blockscore API class InternalServerError(BlockscoreError): - def __init__(self, message=None, json_body=None, error_type=None): - status_code = STATUS_CODES['InternalError'] + def __init__(self, message=None, json_body=None, error_type=None): + status_code = STATUS_CODES['InternalError'] + + super(InternalServerError, self).__init__( + message=dict(), error_type=error_type, + http_status=status_code, json_body=json_body) - super(InternalServerError, self).__init__( - message=dict(), error_type=error_type, - http_status=status_code, json_body=json_body) + pass - pass \ No newline at end of file diff --git a/blockscore/http_client/__init__.py b/blockscore/http_client/__init__.py index 754a9e4..9508539 100644 --- a/blockscore/http_client/__init__.py +++ b/blockscore/http_client/__init__.py @@ -2,132 +2,133 @@ import copy try: - import urlparse + import urlparse except ImportError: - import urllib.parse as urlparse + import urllib.parse as urlparse -from .auth_handler import AuthHandler -from .error_handler import ErrorHandler -from .request_handler import RequestHandler -from .response import Response -from .response_handler import ResponseHandler -from ..error import BlockscoreError +from blockscore.error import BlockscoreError +from blockscore.http_client.auth_handler import AuthHandler +from blockscore.http_client.error_handler import ErrorHandler +from blockscore.http_client.request_handler import RequestHandler +from blockscore.http_client.response import Response +from blockscore.http_client.response_handler import ResponseHandler # Main HttpClient which is used by Api classes class HttpClient(): - def __init__(self, auth, options): + def __init__(self, auth, options): - self.options = { - 'base': 'https://api.blockscore.com/', - 'user_agent': 'blockscore-python/3.0.0 (https://github.com/BlockScore/blockscore-python)' - } + self.options = { + 'base': 'https://api.blockscore.com/', + 'user_agent': 'blockscore-python/4.0.0 (https://github.com/BlockScore/blockscore-python)' + } - self.options.update(options) + self.options.update(options) - self.base = self.options['base'] + self.base = self.options['base'] - self.headers = { - 'Accept': 'application/vnd.blockscore+json;version=3', - 'user-agent': self.options['user_agent'] - } + self.headers = { + 'Accept': 'application/vnd.blockscore+json;version=4', + 'user-agent': self.options['user_agent'] + } - if 'headers' in self.options: - self.headers.update(self.dict_key_lower(self.options['headers'])) - del self.options['headers'] + if 'headers' in self.options: + self.headers.update(self.dict_key_lower(self.options['headers'])) + del self.options['headers'] - self.auth = AuthHandler(auth) + self.auth = AuthHandler(auth) - def get(self, path, params={}, options={}): - options.update({ 'query': params }) - return self.request(path, None, 'get', options) + def get(self, path, params={}, options={}): + options.update({ 'query': params }) + return self.request(path, None, 'get', options) - def post(self, path, body={}, options={}): - return self.request(path, body, 'post', options) + def post(self, path, body={}, options={}): + return self.request(path, body, 'post', options) - def patch(self, path, body={}, options={}): - return self.request(path, body, 'patch', options) + def patch(self, path, body={}, options={}): + return self.request(path, body, 'patch', options) - def delete(self, path, body={}, options={}): - return self.request(path, body, 'delete', options) + def delete(self, path, body={}, options={}): + return self.request(path, body, 'delete', options) - def put(self, path, body={}, options={}): - return self.request(path, body, 'put', options) + def put(self, path, body={}, options={}): + return self.request(path, body, 'put', options) - # Intermediate function which does three main things - # - # - Transforms the body of request into correct format - # - Creates the requests with give parameters - # - Returns response body after parsing it into correct format - def request(self, path, body, method, options): - kwargs = copy.deepcopy(self.options) - kwargs.update(options) + # Intermediate function which does three main things + # + # - Transforms the body of request into correct format + # - Creates the requests with give parameters + # - Returns response body after parsing it into correct format + def request(self, path, body, method, options): + kwargs = copy.deepcopy(self.options) + kwargs.update(options) - kwargs['headers'] = copy.deepcopy(self.headers) + kwargs['headers'] = copy.deepcopy(self.headers) - if 'headers' in options: - kwargs['headers'].update(self.dict_key_lower(options['headers'])) + if 'headers' in options: + kwargs['headers'].update(self.dict_key_lower(options['headers'])) - kwargs['data'] = body - kwargs['allow_redirects'] = True + kwargs['data'] = body + kwargs['allow_redirects'] = True - kwargs['params'] = kwargs['query'] if 'query' in kwargs else {} + kwargs['params'] = kwargs['query'] if 'query' in kwargs else {} - if 'query' in kwargs: - del kwargs['query'] + if 'query' in kwargs: + del kwargs['query'] - if 'body' in kwargs: - del kwargs['body'] + if 'body' in kwargs: + del kwargs['body'] - del kwargs['base'] - del kwargs['user_agent'] + del kwargs['base'] + del kwargs['user_agent'] - kwargs['verify'] = False + kwargs['verify'] = False - if method != 'get': - kwargs = self.set_body(kwargs) + if method != 'get': + kwargs = self.set_body(kwargs) - kwargs['hooks'] = dict(response=ErrorHandler().check_error) + kwargs['hooks'] = dict(response=ErrorHandler().check_error) - kwargs = self.auth.set(kwargs) + kwargs = self.auth.set(kwargs) - response = self.create_request(method, path, kwargs) + response = self.create_request(method, path, kwargs) - return Response(self.get_body(response), response.status_code, response.headers) + return Response(self.get_body(response), response.status_code, response.headers) - # Creating a request with the given arguments - # - # If api_version is set, appends it immediately after host - def create_request(self, method, path, options): - version = '/' + options['api_version'] if 'api_version' in options else '' + # Creating a request with the given arguments + # + # If api_version is set, appends it immediately after host + def create_request(self, method, path, options): + version = '/' + options['api_version'] if 'api_version' in options else '' - path = urlparse.urljoin(self.base, version + path) + path = urlparse.urljoin(self.base, version + path) - if 'api_version' in options: - del options['api_version'] + if 'api_version' in options: + del options['api_version'] - if 'response_type' in options: - del options['response_type'] + if 'response_type' in options: + del options['response_type'] - try: - response = requests.request(method, path, **options) - except BlockscoreError as e: - raise - - return response + try: + response = requests.request(method, path, **options) + except BlockscoreError: + raise - # Get response body in correct format - def get_body(self, response): - return ResponseHandler.get_body(response) + return response - # Set request body in correct format - def set_body(self, request): - return RequestHandler.set_body(request) + # Get response body in correct format + def get_body(self, response): + return ResponseHandler.get_body(response) - # Make dict keys all lowercase - def dict_key_lower(self, dic): - return dict(zip(map(self.key_lower, dic.keys()), dic.values())) + # Set request body in correct format + def set_body(self, request): + return RequestHandler.set_body(request) + + # Make dict keys all lowercase + def dict_key_lower(self, dic): + return dict(zip(map(self.key_lower, dic.keys()), dic.values())) + + # Make a function for lowercase + def key_lower(self, key): + return key.lower() - # Make a function for lowercase - def key_lower(self, key): - return key.lower() \ No newline at end of file diff --git a/blockscore/http_client/auth_handler.py b/blockscore/http_client/auth_handler.py index 033483d..4979e68 100644 --- a/blockscore/http_client/auth_handler.py +++ b/blockscore/http_client/auth_handler.py @@ -1,38 +1,38 @@ # AuthHandler takes care of devising the auth type and using it class AuthHandler(): - HTTP_PASSWORD = 0 + HTTP_PASSWORD = 0 - def __init__(self, auth): - self.auth = auth + def __init__(self, auth): + self.auth = auth - # Calculating the Authentication Type - def get_auth_type(self): + # Calculating the Authentication Type + def get_auth_type(self): - if 'api_key' in self.auth: - self.auth['password'] = '' # Password is not checked/required at the moment - return self.HTTP_PASSWORD + if 'api_key' in self.auth: + self.auth['password'] = '' # Password is not checked/required at the moment + return self.HTTP_PASSWORD - return -1 + return -1 - def set(self, request): - if len(self.auth.keys()) == 0: - return request + def set(self, request): + if len(self.auth.keys()) == 0: + return request - auth = self.get_auth_type() - flag = False + auth = self.get_auth_type() + flag = False - if auth == self.HTTP_PASSWORD: - request = self.http_password(request) - flag = True + if auth == self.HTTP_PASSWORD: + request = self.http_password(request) + flag = True - if not flag: - raise StandardError("Unable to calculate authorization method. Please check") + if not flag: + raise StandardError("Unable to calculate authorization method. Please check") - return request + return request - # Basic Authorization with api_key and password - def http_password(self, request): - request['auth'] = (self.auth['api_key'], self.auth['password']) - return request + # Basic Authorization with api_key and password + def http_password(self, request): + request['auth'] = (self.auth['api_key'], self.auth['password']) + return request diff --git a/blockscore/http_client/error_handler.py b/blockscore/http_client/error_handler.py index b74528f..ea4c0a0 100644 --- a/blockscore/http_client/error_handler.py +++ b/blockscore/http_client/error_handler.py @@ -1,71 +1,71 @@ -from ..error import BlockscoreError, AuthorizationError, \ - InternalServerError, ValidationError, ParameterError, NotFoundError -from .response_handler import ResponseHandler - +from blockscore.error import BlockscoreError, AuthorizationError, \ + InternalServerError, ValidationError, ParameterError, NotFoundError +from blockscore.http_client.response_handler import ResponseHandler + # ErrorHanlder takes care of selecting the error message from response body class ErrorHandler(): - def check_error(self, response, *args, **kwargs): - code = response.status_code - typ = response.headers.get('content-type') - - # No error found - if (200 <= code < 300): - return - self.body = ResponseHandler.get_body(response) - self.message = self.get_message(self.body) - self.error_type = self.error_code = self.param = None - - # determines if an error is in the response's body - if 'error' in self.body.keys(): - error = self.body['error'] - self.error_type = self.get_value(error, 'type') - self.error_code = self.get_value(error, 'code') - self.param = self.get_value(error, 'param') - - # raises the appropriate error if necessary - self.process_code(code) - - def process_code(self, code): - - if code == 400: - # Inputs could not be validated - if self.param is not None: - raise ValidationError(self.message, self.body, self.param, \ - self.error_type, self.error_code) - # Required parameter missing - else: - raise ParameterError(self.message, self.body, self.error_type) - # Trying to access nonexistent endpoint - elif code == 404: - raise NotFoundError(self.message, self.body, self.error_type) - # Error with an API Key - elif code == 401: - raise AuthorizationError(self.message, self.body, self.error_type) - # Internal API Error - elif code == 500: - raise InternalServerError(self.message, self.body, self.error_type) - # Generic BlockscoreError (fallback) - else: - raise BlockscoreError(self.message, self.body) - - @staticmethod - def get_message(body): - message = '' - # If HTML, whole body is taken - if isinstance(body, str): - message = body - elif isinstance(body, dict): # body not str - if 'error' in body.keys(): - message = body['error']['message'] - else: - message = 'Unable to select error message from json returned by request responsible for error' - - else: # body not str or dict - message = 'Unable to understand the content type of response returned by request responsible for error' - return message - - @staticmethod - def get_value(obj, key): - if key in obj.keys(): - return obj[key] - return None \ No newline at end of file + def check_error(self, response, *args, **kwargs): + code = response.status_code + + # No error found + if (200 <= code < 300): + return + self.body = ResponseHandler.get_body(response) + self.message = self.get_message(self.body) + self.error_type = self.error_code = self.param = None + + # determines if an error is in the response's body + if 'error' in self.body.keys(): + error = self.body['error'] + self.error_type = self.get_value(error, 'type') + self.error_code = self.get_value(error, 'code') + self.param = self.get_value(error, 'param') + + # raises the appropriate error if necessary + self.process_code(code) + + def process_code(self, code): + + if code == 400: + # Inputs could not be validated + if self.param is not None: + raise ValidationError(self.message, self.body, self.param, \ + self.error_type, self.error_code) + # Required parameter missing + else: + raise ParameterError(self.message, self.body, self.error_type) + # Trying to access nonexistent endpoint + elif code == 404: + raise NotFoundError(self.message, self.body, self.error_type) + # Error with an API Key + elif code == 401: + raise AuthorizationError(self.message, self.body, self.error_type) + # Internal API Error + elif code == 500: + raise InternalServerError(self.message, self.body, self.error_type) + # Generic BlockscoreError (fallback) + else: + raise BlockscoreError(self.message, self.body) + + @staticmethod + def get_message(body): + message = '' + # If HTML, whole body is taken + if isinstance(body, str): + message = body + elif isinstance(body, dict): # body not str + if 'error' in body.keys(): + message = body['error']['message'] + else: + message = 'Unable to select error message from json returned by request responsible for error' + + else: # body not str or dict + message = 'Unable to understand the content type of response returned by request responsible for error' + return message + + @staticmethod + def get_value(obj, key): + if key in obj.keys(): + return obj[key] + return None + diff --git a/blockscore/http_client/request_handler.py b/blockscore/http_client/request_handler.py index 285673e..b95299e 100644 --- a/blockscore/http_client/request_handler.py +++ b/blockscore/http_client/request_handler.py @@ -1,58 +1,58 @@ -import urllib import json # RequestHandler takes care of encoding the request body into format given by options class RequestHandler(): - @staticmethod - def renderKey(parents): - depth, new = 0, '' + @staticmethod + def renderKey(parents): + depth, new = 0, '' - for x in parents: - old = "[%s]" if depth > 0 else "%s" - new += old % x - depth += 1 + for x in parents: + old = "[%s]" if depth > 0 else "%s" + new += old % x + depth += 1 - return new + return new - @staticmethod - def urlencode(data, parents=None, pairs=None): - if pairs is None: - pairs = {} + @staticmethod + def urlencode(data, parents=None, pairs=None): + if pairs is None: + pairs = {} - if parents is None: - parents = [] + if parents is None: + parents = [] - if isinstance(data, dict): - for key, value in data.items(): - RequestHandler.urlencode(value, parents + [key], pairs) - elif isinstance(data, list): - for key, value in enumerate(data): - RequestHandler.urlencode(value, parents + [key], pairs) - else: - pairs[RequestHandler.renderKey(parents)] = data + if isinstance(data, dict): + for key, value in data.items(): + RequestHandler.urlencode(value, parents + [key], pairs) + elif isinstance(data, list): + for key, value in enumerate(data): + RequestHandler.urlencode(value, parents + [key], pairs) + else: + pairs[RequestHandler.renderKey(parents)] = data - return pairs + return pairs - @staticmethod - def set_body(request): - typ = request['request_type'] if 'request_type' in request else 'form' + @staticmethod + def set_body(request): + typ = request['request_type'] if 'request_type' in request else 'form' - # Encoding request body into JSON format - if typ == 'json': - request['data'] = json.dumps(request['data']) - request['headers']['content-type'] = 'application/json' + # Encoding request body into JSON format + if typ == 'json': + request['data'] = json.dumps(request['data']) + request['headers']['content-type'] = 'application/json' - # Encoding body into form-urlencoded format - if typ == 'form': - request['data'] = RequestHandler.urlencode(request['data']) - request['headers']['content-type'] = 'application/x-www-form-urlencoded' + # Encoding body into form-urlencoded format + if typ == 'form': + request['data'] = RequestHandler.urlencode(request['data']) + request['headers']['content-type'] = 'application/x-www-form-urlencoded' - if typ == 'raw': - if 'content-type' in request['headers']: - del request['headers']['content-type'] + if typ == 'raw': + if 'content-type' in request['headers']: + del request['headers']['content-type'] - if 'request_type' in request: - del request['request_type'] + if 'request_type' in request: + del request['request_type'] + + return request - return request diff --git a/blockscore/http_client/response.py b/blockscore/http_client/response.py index cbd92da..7cce87b 100644 --- a/blockscore/http_client/response.py +++ b/blockscore/http_client/response.py @@ -1,6 +1,7 @@ # Response object contains the response returned by the client class Response(): - def __init__(self, body, code, headers): - self.body = body - self.code = code - self.headers = headers + def __init__(self, body, code, headers): + self.body = body + self.code = code + self.headers = headers + diff --git a/blockscore/http_client/response_handler.py b/blockscore/http_client/response_handler.py index 34d9711..d1f0fa0 100644 --- a/blockscore/http_client/response_handler.py +++ b/blockscore/http_client/response_handler.py @@ -1,13 +1,14 @@ # ResponseHandler takes care of decoding the response body into suitable type class ResponseHandler(): - @staticmethod - def get_body(response): - typ = response.headers.get('content-type') - body = response.text + @staticmethod + def get_body(response): + typ = response.headers.get('content-type') + body = response.text - # Response body is in JSON - if typ.find('json') != -1: - body = response.json() + # Response body is in JSON + if typ.find('json') != -1: + body = response.json() + + return body - return body diff --git a/setup.py b/setup.py index 1dec9a3..d95ef8c 100644 --- a/setup.py +++ b/setup.py @@ -7,29 +7,30 @@ from distutils.core import setup setup( - name='blockscore', - version='3.0.0', - description='Official BlockScore API library client for python', - author='John Backus', - author_email='john@blockscore.com', - url='https://blockscore.com', - license='MIT', - install_requires=[ - 'requests >= 2.1.0' - ], - packages=[ - 'blockscore' - ], - package_data = {'blockscore': ['api/*', 'error/*','http_client/*']}, - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3', - 'Topic :: Software Development :: Libraries :: Python Modules', - ] + name='blockscore', + version='4.0.0', + description='Official BlockScore API library client for python', + author='John Backus', + author_email='john@blockscore.com', + url='https://blockscore.com', + license='MIT', + install_requires=[ + 'requests >= 2.1.0' + ], + packages=[ + 'blockscore' + ], + package_data = {'blockscore': ['api/*', 'error/*','http_client/*']}, + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', + 'Topic :: Software Development :: Libraries :: Python Modules', + ] ) + diff --git a/test/companies.py b/test/companies.py index 92cb30e..51c3567 100644 --- a/test/companies.py +++ b/test/companies.py @@ -1,66 +1,64 @@ if __name__ == '__main__' and __package__ is None: - from os import sys, path - sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) + from os import sys, path + sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) import blockscore import unittest import os, sys class TestBlockscoreCompanies(unittest.TestCase): - def setUp(self): - try: - self.client = blockscore.Client({'api_key': os.environ['BLOCKSCORE_API']}) - except KeyError: - sys.stderr.write("To run tests, you must have a BLOCKSCORE_API environment variable with a test api key\n") - sys.exit(2) + def setUp(self): + try: + self.client = blockscore.Client({'api_key': os.environ['BLOCKSCORE_API']}) + except KeyError: + sys.stderr.write("To run tests, you must have a BLOCKSCORE_API environment variable with a test api key\n") + sys.exit(2) - self.test_company = { - "entity_name": "BlockScore", - "tax_id": "123410000", - "incorp_date": "1980-08-25", - "incorp_state": "DE", - "incorp_country_code": "US", - "incorp_type": "corporation", - "dbas": "BitRemite", - "registration_number": "123123123", - "email": "test@example.com", - "url": "https://blockscore.com", - "phone_number": "6505555555", - "ip_address": "67.160.8.182", - "address": { - "street1": "1 Infinite Loop", - "street2": None, - "city": "Cupertino", - "state": "CA", - "postal_code": "95014", - "country_code": "US", - } - } + self.test_company = { + "entity_name": "BlockScore", + "tax_id": "123410000", + "incorporation_date": "1980-08-25", + "incorporation_state": "DE", + "incorporation_country_code": "US", + "incorporation_type": "corporation", + "dbas": "BitRemite", + "registration_number": "123123123", + "email": "test@example.com", + "url": "https://blockscore.com", + "phone_number": "6505555555", + "ip_address": "67.160.8.182", + "address_street1": "1 Infinite Loop", + "address_street2": None, + "address_city": "Cupertino", + "address_subdivision": "CA", + "address_postal_code": "95014", + "address_country_code": "US", + } - def test_list_companies(self): - response = self.client.companies.all() - self.assertEqual(200, response.code) + def test_list_companies(self): + response = self.client.companies.all() + self.assertEqual(200, response.code) - response = self.client.companies.all(count=2) - self.assertEqual(200, response.code) + response = self.client.companies.all(count=2) + self.assertEqual(200, response.code) - response = self.client.companies.all(count=2, offset=2) - self.assertEqual(200, response.code) + response = self.client.companies.all(count=2, offset=2) + self.assertEqual(200, response.code) - def test_retrieve_company(self): - response = self.client.companies.create(self.test_company) - body = response.body + def test_retrieve_company(self): + response = self.client.companies.create(self.test_company) + body = response.body - response = self.client.companies.retrieve(body['id']) - body = response.body + response = self.client.companies.retrieve(body['id']) + body = response.body - self.assertEqual(200, response.code) - self.assertEqual(self.test_company['entity_name'], body['entity_name']) + self.assertEqual(200, response.code) + self.assertEqual(self.test_company['entity_name'], body['entity_name']) - def test_create_company(self): - response = self.client.companies.create(self.test_company) - self.assertEqual(201, response.code) + def test_create_company(self): + response = self.client.companies.create(self.test_company) + self.assertEqual(201, response.code) if __name__ == '__main__': - unittest.main() + unittest.main() diff --git a/test/people.py b/test/people.py new file mode 100644 index 0000000..45a45d5 --- /dev/null +++ b/test/people.py @@ -0,0 +1,106 @@ +if __name__ == '__main__' and __package__ is None: + from os import sys, path + sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) +import blockscore +import unittest +import os, sys + +class TestBlockscore(unittest.TestCase): + + def setUp(self): + try: + self.client = blockscore.Client({'api_key': os.environ['BLOCKSCORE_API']}) + except KeyError: + sys.stderr.write("To run tests, you must have a BLOCKSCORE_API environment variable with a test api key\n") + sys.exit(2) + + self.test_identity = { + "name_first": "John", + "name_middle": "Pearce", + "name_last": "Doe", + "birth_day": "23", + "birth_month": "8", + "birth_year": "1980", + "document_type": "ssn", + "document_value": "0000", + "address_street1": "1 Infinite Loop", + "address_street2": "Apt 6", + "address_city": "Cupertino", + "address_subdivision": "CA", + "address_postal_code": "95014", + "address_country_code": "US", + } + def test_create_person(self): + response = self.client.people.create(self.test_identity) + self.assertEqual(response.body['name_first'], self.test_identity['name_first']) + self.assertEqual(response.body['name_last'], self.test_identity['name_last']) + + def test_retrieve_person(self): + verif = self.client.people.create(self.test_identity) + verif_id = verif.body['id'] + verif2 = self.client.people.retrieve(verif_id) + self.assertEqual(verif.body, verif2.body) + + def test_list_people(self): + self.client.people.create(self.test_identity) + self.client.people.create(self.test_identity) + self.client.people.create(self.test_identity) + verif_list = self.client.people.all(count=3) + verif_list = verif_list.body + self.assertTrue(len(verif_list) >= 3) + verif_list2 = self.client.people.all(count=3,offset=3) + verif_list2 = verif_list2.body + self.assertNotEqual(verif_list, verif_list2) + + + + def test_create_questions(self): + verif = self.client.people.create(self.test_identity) + verif = verif.body + verif_id = verif['id'] + qset = self.client.question_sets.create(verif_id) + qset = qset.body + self.assertEqual(qset['person_id'],verif_id) + + def test_score_questions(self): + verif = self.client.people.create(self.test_identity) + verif = verif.body + verif_id = verif['id'] + qset = self.client.question_sets.create(verif_id) + qset = qset.body + qset_id = qset['id'] + score = self.client.question_sets.score(qset_id, [ + {'question_id':1, 'answer_id':1}, + {'question_id':2, 'answer_id':1}, + {'question_id':3, 'answer_id':1}, + {'question_id':4, 'answer_id':1}, + {'question_id':5, 'answer_id':1} + ]) + score = score.body + self.assertEqual(score['id'],qset_id) + self.assertIsInstance(score['score'],float) + + + + # make sure the shuffled sequence does not lose any elements + # random.shuffle(self.seq) + # self.seq.sort() + # self.assertEqual(self.seq, range(10)) + # self.assertEqual(1,1) + + # should raise an exception for an immutable sequence + # self.assertRaises(TypeError, random.shuffle, (1,2,3)) + + # def test_choice(self): + # element = random.choice(self.seq) + # self.assertTrue(element in self.seq) + + # def test_sample(self): + # with self.assertRaises(ValueError): + # random.sample(self.seq, 20) + # for element in random.sample(self.seq, 5): + # self.assertTrue(element in self.seq) + +if __name__ == '__main__': + unittest.main() + diff --git a/test/verifications.py b/test/verifications.py deleted file mode 100644 index 624a176..0000000 --- a/test/verifications.py +++ /dev/null @@ -1,89 +0,0 @@ -if __name__ == '__main__' and __package__ is None: - from os import sys, path - sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) -import blockscore -import unittest -import os, sys - -class TestBlockscore(unittest.TestCase): - - def setUp(self): - try: - self.client = blockscore.Client({'api_key': os.environ['BLOCKSCORE_API']}) - except KeyError: - sys.stderr.write("To run tests, you must have a BLOCKSCORE_API environment variable with a test api key\n") - sys.exit(2) - self.test_identity = ['1980-01-01',{'ssn': '0000'},{'first': 'john', 'last': 'doe'},{'street1': '1 Infinite Loop', 'city': 'Palo Alto', 'state': 'ca', 'postal_code': '94309', 'country_code': 'us'}] - - def test_create_verification(self): - verif = self.client.verification.create(*self.test_identity) - self.assertEqual(verif.body['date_of_birth'], self.test_identity[0]) - - def test_retrieve_verification(self): - verif = self.client.verification.create(*self.test_identity) - verif_id = verif.body['id'] - verif2 = self.client.verification.retrieve(verif_id) - self.assertEqual(verif.body, verif2.body) - - def test_list_verification(self): - verif1 = self.client.verification.create(*self.test_identity) - verif2 = self.client.verification.create(*self.test_identity) - verif3 = self.client.verification.create(*self.test_identity) - verif_list = self.client.verification.all(count=3) - verif_list = verif_list.body - self.assertTrue(len(verif_list) >= 3) - verif_list2 = self.client.verification.all(count=3,offset=3) - verif_list2 = verif_list2.body - self.assertNotEqual(verif_list, verif_list2) - - - - def test_create_questions(self): - verif = self.client.verification.create(*self.test_identity) - verif = verif.body - verif_id = verif['id'] - qset = self.client.question_set.create(verif_id) - qset = qset.body - self.assertEqual(qset['verification_id'],verif_id) - - def test_score_questions(self): - verif = self.client.verification.create(*self.test_identity) - verif = verif.body - verif_id = verif['id'] - qset = self.client.question_set.create(verif_id) - qset = qset.body - qset_id = qset['id'] - score = self.client.question_set.score(verif_id, qset_id, [ - {'question_id':1, 'answer_id':1}, - {'question_id':2, 'answer_id':1}, - {'question_id':3, 'answer_id':1}, - {'question_id':4, 'answer_id':1}, - {'question_id':5, 'answer_id':1} - ]) - score = score.body - self.assertEqual(score['id'],qset_id) - self.assertIsInstance(score['score'],float) - - - - # make sure the shuffled sequence does not lose any elements - # random.shuffle(self.seq) - # self.seq.sort() - # self.assertEqual(self.seq, range(10)) - # self.assertEqual(1,1) - - # should raise an exception for an immutable sequence - # self.assertRaises(TypeError, random.shuffle, (1,2,3)) - - # def test_choice(self): - # element = random.choice(self.seq) - # self.assertTrue(element in self.seq) - - # def test_sample(self): - # with self.assertRaises(ValueError): - # random.sample(self.seq, 20) - # for element in random.sample(self.seq, 5): - # self.assertTrue(element in self.seq) - -if __name__ == '__main__': - unittest.main() \ No newline at end of file