def __init__(self, access_key: str = None, secret_key: str = None, **kwargs): arg_config = kwargs.get("config") arg_spec_uri = kwargs.get("spec_uri") config = { "also_return_response": False, "validate_responses": False, "use_models": False, "host": HOST } if not arg_config else arg_config spec_uri = SPEC_URI if not arg_spec_uri else arg_spec_uri if access_key and secret_key: request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator( host=config["host"], access_key=access_key, secret_key=secret_key) self.__client = SwaggerClient.from_url(spec_url=spec_uri, http_client=request_client, config=config) else: self.__client = SwaggerClient.from_url(spec_url=spec_uri, config=config)
def __init__(self, api_address, api_token): self.api_address = api_address self.api_token = api_token self._http_client = RequestsClient() self.backend_swagger_client = SwaggerClient.from_url( '{}/api/backend/swagger.json'.format(self.api_address), config=dict(validate_swagger_spec=False, validate_requests=False, validate_responses=False, formats=[uuid_format]), http_client=self._http_client) self.leaderboard_swagger_client = SwaggerClient.from_url( '{}/api/leaderboard/swagger.json'.format(self.api_address), config=dict(validate_swagger_spec=False, validate_requests=False, validate_responses=False, formats=[uuid_format]), http_client=self._http_client) self.authenticator = NeptuneAuthenticator( self.backend_swagger_client.api.exchangeApiToken( X_Neptune_Api_Token=api_token).response().result) self._http_client.authenticator = self.authenticator
def __init__(self, API_KEY, API_SECRET): print("websocket start 1") self.initTradeSide = "Buy" HOST = "https://www.bitmex.com" SPEC_URI = HOST + "/api/explorer/swagger.json" config = { 'use_models': False, 'validate_responses': False, 'also_return_response': True, } bitMEX = SwaggerClient.from_url(SPEC_URI, config=config) self.API_KEY = API_KEY self.API_SECRET = API_SECRET request_client = RequestsClient() print("websocket start 2") request_client.authenticator = APIKeyAuthenticator( HOST, self.API_KEY, self.API_SECRET) self.bitMEXAuthenticated = SwaggerClient.from_url( SPEC_URI, config=config, http_client=request_client) print("websocket end") # Basic authenticated call print('\n---A basic Position GET:---') print( 'The following call requires an API key. If one is not set, it will throw an Unauthorized error.' ) self.avgPrice = 0 self.pos = 0
def __init__(self, access_key: str = None, secret_key: str = None, **kwargs): arg_config = kwargs.get('config') arg_spec_uri = kwargs.get('spec_uri') config = { 'also_return_response': False, 'validate_responses': False, 'use_models': False, 'host': HOST } if not arg_config else arg_config spec_uri = SPEC_URI if not arg_spec_uri else arg_spec_uri if access_key and secret_key: request_client = rc() request_client.authenticator = APIKeyAuthenticator( config['host'], access_key, secret_key) self.__client = sc.from_url(spec_url=spec_uri, http_client=request_client, config=config) else: self.__client = sc.from_url(spec_url=spec_uri, config=config)
def test_invalid_spec_raises_SwaggerValidationError(httprettified, swagger_dict): swagger_dict['paths']['/test_http']['get']['parameters'][0]['type'] = 'X' register_spec(swagger_dict) with pytest.raises(SwaggerValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL) assert 'is not valid' in str(excinfo.value)
def bitmex(test=True, config=None, api_key=None, api_secret=None): print('test status: %s' % test) if config is None: # See full config options at http://bravado.readthedocs.io/en/latest/configuration.html config = { # Don't use models (Python classes) instead of dicts for #/definitions/{models} 'use_models': False, # bravado has some issues with nullable fields 'validate_responses': False, # Returns response in 2-tuple of (body, response); if False, will only return body 'also_return_response': True, } if test: host = 'https://testnet.bitmex.com' else: host = 'https://www.bitmex.com' spec_uri = host + '/api/explorer/swagger.json' api_key = api_key api_secret = api_secret if api_key and api_secret: request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator( host, api_key, api_secret) return SwaggerClient.from_url(spec_uri, config=config, http_client=request_client) else: return SwaggerClient.from_url(spec_uri, config=config)
def test_invalid_type_in_response_raises_ValidationError( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) register_get("http://localhost/test_http", body='"NOT_COMPLEX_TYPE"') with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'NOT_COMPLEX_TYPE' is not of type" in str(excinfo.value)
def bybit(test=True, config=None, api_key=None, api_secret=None): host = TESTNET if test else MAINNET config = { # Don't use models (Python classes) instead of dicts for #/definitions/{models} 'use_models': False, # bravado has some issues with nullable fields 'validate_responses': False, # Returns response in 2-tuple of (body, response); if False, will only return body 'also_return_response': True, 'host': host } if not config else config spec_uri = urljoin(host, "/doc/swagger/v_0_2_10.txt") if api_key and api_secret: request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator( host, api_key, api_secret) return SwaggerClient.from_url(spec_uri, config=config, http_client=request_client) else: return SwaggerClient.from_url(spec_uri, config=config)
def test_invalid_type_in_response_raises_ValidationError( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) register_get("http://localhost/test_http", body='"NOT_COMPLEX_TYPE"') with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'NOT_COMPLEX_TYPE' is not of type" in str(excinfo.value)
def test_invalid_spec_raises_SwaggerValidationError( httprettified, swagger_dict): swagger_dict['paths']['/test_http']['get']['parameters'][0]['type'] = 'X' register_spec(swagger_dict) with pytest.raises(SwaggerValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL) assert 'is not valid' in str(excinfo.value)
def bitmex(test=True, config=None, api_key=None, api_secret=None): if config is None: # See full config options at http://bravado.readthedocs.io/en/latest/configuration.html config = { # Don't use models (Python classes) instead of dicts for #/definitions/{models} 'use_models': False, # bravado has some issues with nullable fields 'validate_responses': False, # Returns response in 2-tuple of (body, response); if False, will only return body 'also_return_response': True, } if test: host = 'https://testnet.bitmex.com' else: host = 'https://www.bitmex.com' spec_uri = host + '/api/explorer/swagger.json' api_key = api_key api_secret = api_secret if api_key and api_secret: request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret) return SwaggerClient.from_url(spec_uri, config=config, http_client=request_client) else: return SwaggerClient.from_url(spec_uri, config=config)
def bybit(test=True, config=None, api_key=None, api_secret=None): if test: host = 'https://api-testnet.bybit.com' else: host = 'https://api.bybit.com' if config is None: # See full config options at http://bravado.readthedocs.io/en/latest/configuration.html config = { # Don't use models (Python classes) instead of dicts for #/definitions/{models} 'use_models': False, # bravado has some issues with nullable fields 'validate_responses': False, # Returns response in 2-tuple of (body, response); if False, will only return body 'also_return_response': True, "host": host } api_key = api_key api_secret = api_secret spec_uri = host + "/doc/swagger/v_0_2_6.txt" if api_key and api_secret: request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret) return SwaggerClient.from_url(spec_uri, config=config, http_client=request_client) else: return SwaggerClient.from_url(spec_uri, config=config)
def __init__(self, package_info, remote): """Plugin for building docker container on guay registry Args: package_info (dict): Contains information about the package to execute inside the plugin remote (bool): Define if the plugin will be execute in remote or not Raises: CIBuildPackageFail: when one of the steps for packaging or uploading the package failed """ ComplexPlugin.__init__(self, package_info, { "command": { "run": None, "clean": "make clean" } }, remote=remote) self.timeline = { 11: self.get_next_version, 31: self.create_archive, 51: self.store_archive, 71: self.trigger_build, 91: self.wait_build } self.guay = SwaggerClient.from_url("{}/swagger.json".format(GUAY["host"])) self.storage_proxy = SwaggerClient.from_url("{}:{}/v1/swagger.json".format(STORAGE_PROXY["host"], STORAGE_PROXY["port"]))
def test_error_on_wrong_type_inside_complex_type(httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model["id"] = "Not Integer" register_get("http://localhost/test_http", body=json.dumps(sample_model)) with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'Not Integer' is not of type" in str(excinfo.value)
def test_error_on_wrong_type_inside_complex_type( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model["id"] = "Not Integer" register_get("http://localhost/test_http", body=simplejson.dumps(sample_model)) with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'Not Integer' is not of type" in str(excinfo.value)
def test_error_on_missing_type_in_model( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model["schools"][0] = {} # Omit 'name' register_get("http://localhost/test_http", body=simplejson.dumps(sample_model)) with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'name' is a required property" in str(excinfo.value)
def test_model_missing_required_property_in_response_raises_ValidationError( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model.pop("id") register_get("http://localhost/test_http", body=json.dumps(sample_model)) with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'id' is a required property" in str(excinfo.value)
def test_model_missing_required_property_in_response_raises_ValidationError( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model.pop("id") register_get("http://localhost/test_http", body=simplejson.dumps(sample_model)) with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'id' is a required property" in str(excinfo.value)
def test_error_on_missing_type_in_model(httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model["schools"][0] = {} # Omit 'name' register_get("http://localhost/test_http", body=json.dumps(sample_model)) with pytest.raises(ValidationError) as excinfo: SwaggerClient.from_url(API_DOCS_URL).api_test.testHTTP().result() assert "'name' is a required property" in str(excinfo.value)
def get_clients(): HOST = "https://www.bitmex.com" SPEC_URI = HOST + "/api/explorer/swagger.json" bitMEX = SwaggerClient.from_url(SPEC_URI, config=config) API_KEY = 'emjo2LdiVdhwmTqMESEcO9ut' API_SECRET = 'DspbFr4sWjnxUPY4L5yDh13b0MZ1oDGs4kr94EcdJcSH2QkR' request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator(HOST, API_KEY, API_SECRET) bitMEXAuthenticated = SwaggerClient.from_url(SPEC_URI, config=config, http_client=request_client) return bitMEX, bitMEXAuthenticated
def test_hostname_if_passed_overrides_origin_url(httprettified, swagger_dict): register_get("http://foo/test_http?", body='') swagger_dict['host'] = 'foo' register_spec(swagger_dict) resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP(test_param="foo").result() assert ["foo"] == httpretty.last_request().querystring['test_param']
def test_basePath_works(httprettified, swagger_dict): swagger_dict["basePath"] = "/append" register_spec(swagger_dict) register_get("http://localhost/append/test_http?test_param=foo") resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP(test_param="foo").result() assert ["foo"] == httpretty.last_request().querystring['test_param']
def _get_swagger_client(self, url): return SwaggerClient.from_url(url, config=dict(validate_swagger_spec=False, validate_requests=False, validate_responses=False, formats=[uuid_format]), http_client=self._http_client)
def init_client( url, disable_fallback_results=False, validate_responses=False, validate_requests=False, validate_swagger_spec=False, use_models=False, ssl_verify=True, ): """Init client""" # Create a new Requests client instance http_client = RequestsClient() http_client.session.verify = ssl_verify swagger_client = SwaggerClient.from_url( url, http_client=http_client, config={ 'disable_fallback_results': disable_fallback_results, 'validate_responses': validate_responses, 'validate_requests': validate_requests, 'validate_swagger_spec': validate_swagger_spec, 'use_models': use_models, # 'also_return_response': True, # 'force_fallback_result': True }) return swagger_client
def get(api_key, api_hash, release='latest', source='tranquility'): """ Get a Swagger client for the Proxied EVE Swagger Interface :param api_key: Proxy api key. :param api_hash: Proxy api hash. :param release: ESI release. One of 'latest', 'legacy' or 'dev'. :param source: ESI source. One of 'tranquility' or 'singularity'. :return: a SwaggerClient for the EVE Swagger Interface """ global __external_clients__ key = __mk_key__(api_key, api_hash, release, source) existing = __external_clients__.get('ESIProxy', key) if existing is None: pair_auth = ApiKeyPairAuthenticator( 'esi-proxy.orbital.enterprises', 'esiProxyKey', api_key, 'esiProxyHash', api_hash) http_client = AuthRequestsClient() http_client.set_auth(pair_auth) url = "https://esi-proxy.orbital.enterprises/%s/swagger.json?datasource=%s" % ( release, source) existing = SwaggerClient.from_url(url, http_client=http_client, config={ 'use_models': False, 'validate_responses': False, 'also_return_response': True }) __external_clients__.set('ESIProxy', key, existing) return existing
def __init__(self, source, history_path, output_format=formatter.JSON, headers=None): """Initialize the CLI processor.""" self.history_path = history_path self.output_format = output_format self.logger = logging.getLogger("open-cli") self.logger.debug("Creating a python client based on %s, headers: %s", source, headers) headers = self._parse_headers(headers) # Handle non-url sources if os.path.exists(source): source = "file://" + source self.client = SwaggerClient.from_url( source, request_headers=headers, config={ 'use_models': False, 'validate_responses': False, 'validate_swagger_spec': False, } ) # Get the CLI prompt name from the spec title self.name = self.client.swagger_spec.spec_dict["info"].get("title", u"Open-CLI") # Initialize a command parser based on the client self.command_parser = parser.CommandParser(client=self.client)
def start(self): print('Fetching open API from: ' + self.url) client = SwaggerClient.from_url(self.url) spec = client.swagger_spec.spec_dict host_basepath = spec['host'] + spec['basePath'] paths = spec['paths'] type_definitions = spec['definitions'] for path_key in paths.keys(): path = paths[path_key] for op_code in path.keys(): operation = HttpOperation(op_code, 'http://' + host_basepath, path_key, op_infos=path[op_code], use_fuzzing=True) for x in range(self.iterations): response = operation.execute(type_definitions) validator = ResultValidator() log = validator.evaluate(response, path[op_code]['responses'], self.log_unexpected_errors_only) curlcommand = CurlCommand(self.url, operation.op_code, operation.request_body) # log to screen for now self.log_operation(operation.op_code, response.url, log, curlcommand)
def test_correct_route_with_basePath_no_slash(httprettified, swagger_dict): register_get("http://localhost/lame/test/test_http?test_param=foo", body=u'""') swagger_dict["basePath"] = "/lame/test" register_spec(swagger_dict) resource = SwaggerClient.from_url(API_DOCS_URL).api_test assert resource.testHTTP(test_param="foo").result() is None
def setClientAPIFromEnv(env): global swaggerClient if env == None: swaggerClient = None else: print("Initializing SwaggerClient with " + env['url'] + "/api/rest/documentation") config = { # === bravado config === # Determines what is returned by the service call. 'also_return_response': False, # === bravado-core config ==== # validate incoming responses 'validate_responses': False, # validate outgoing requests 'validate_requests': False, # validate the swagger spec 'validate_swagger_spec': False, # Use models (Python classes) instead of dicts for #/definitions/{models} 'use_models': True, # # List of user-defined formats # 'formats': [my_super_duper_format], } swaggerClient = SwaggerClient.from_url(env['url'] + "/api/rest/documentation", config=config)
def test_basePath_works(httprettified, swagger_dict): swagger_dict["basePath"] = "/append" register_spec(swagger_dict) register_get("http://localhost/append/test_http?test_param=foo") resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP(test_param="foo").result() assert ["foo"] == httpretty.last_request().querystring['test_param']
def __init__(self, url): self._client = SwaggerClient.from_url(url + '/swagger.json', config={ 'validate_swagger_spec': False, 'use_models': False, })
def swagger_client(self, swagger_http_server): return SwaggerClient.from_url( spec_url='{server_address}/swagger.json'.format( server_address=swagger_http_server), http_client=self.http_client, config={'use_models': False, 'also_return_response': True} )
def cerise_client(): # Disable Bravado warning about uri format not being registered # It's all done by frameworks, so we're not testing that here uri_format = SwaggerFormat(description='A Uniform Resource Identifier', format='uri', to_wire=lambda uri: uri, to_python=lambda uri: uri, validate=lambda uri_string: True) bravado_config = {'also_return_response': True, 'formats': [uri_format]} service = None start_time = time.perf_counter() cur_time = start_time while cur_time < start_time + 10: try: service = SwaggerClient.from_url( 'http://localhost:29593/swagger.json', config=bravado_config) _, response = service.jobs.get_jobs().result() if response.status_code == 200: break except HTTPBadGateway: pass except requests.exceptions.ConnectionError: pass time.sleep(0.1) cur_time = time.perf_counter() if cur_time >= start_time + 10: print("Warning: Cerise container failed to come up") return service
def create_client(origin_url=None, config=None, api_url=None, authenticator=None): """ Create the Bravado swagger client from the specified origin url and config. For the moment, the Swagger specification for Dart is actually bundled with this client since Dart does not have an endpoint that exposes it dynamically. :param origin_url: The location of the Swagger specification. If not specified, then api_url must be specified will assume that swagger.json is present at that location. :param config: An optional configuration dictionary to pass to the Bravado SwaggerClient. :param api_url: The base URL for the API endpoints. :param authenticator: An authenticator instance to use when making API requests :return: The Bravado SwaggerClient instance. """ if origin_url: spec_url = origin_url elif api_url: spec_url = api_url + '/swagger.json' else: raise RuntimeError('One of origin_url or api_url must be specified') client = SwaggerClient.from_url(spec_url=spec_url, config=config) if api_url: client.swagger_spec.api_url = api_url if authenticator: client.swagger_spec.http_client.authenticator = authenticator return client
def test_default_value_in_request(httprettified, swagger_dict): swagger_dict['paths']['/test_http']['get']['parameters'][0]['default'] = 'X' register_spec(swagger_dict) register_get("http://localhost/test_http?") resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP().result() assert ['X'] == httpretty.last_request().querystring['test_param']
def _make_bravado_client(self): http_client = GssapiHttpClient(principal=self._principal) try: api = SwaggerClient.from_url( self._spec_url, http_client=http_client, config=self._bravado_config, ) except (HTTPError, RequestException) as e: data = { "exc": e, "message": str(e), } if getattr(e, "status_code", None): data["status_code"] = e.status_code raise ClientError("error loading remote spec", errno.ECONNABORTED, data=data) except SwaggerValidationError as e: raise ClientError("schema validation failed", errno.EPROTO, data={"exc": e}) except ValueError as e: raise ClientError("remote data validation failed", errno.EPROTO, data={"exc": e}) return api
def swagger_client(self, swagger_http_server): return SwaggerClient.from_url( spec_url='{server_address}/swagger.json'.format( server_address=swagger_http_server), http_client=self.http_client, config={'use_models': False, 'also_return_response': True} )
def external_api(name): if not name in EXT_API: url = SETUP[name]['api_url'] client_config = {'validate_responses': False} EXT_API[name] = SwaggerClient.from_url(url, config=client_config).external return EXT_API[name]
def get_swagger_client(server_url, http_client_instance): spec_url = "{}/swagger.yaml".format(server_url) return SwaggerClient.from_url( spec_url, http_client=http_client_instance, config={"also_return_response": True}, )
def __init__(self, service_url: str, token: str) -> None: """Create a Swagger API client, load the Swagger definition from the provided service url, and set the authentication token for the domain name in the url. :param service_url: The base URL for the service, e.g. 'https://mon.hausnet.io/api', without a trailing slash. :param token: The access token provided by the HausNet service. :raises: Any exceptions that were raised during the Swagger client initialization, including connection to the service. """ host = urlparse(service_url).hostname http_client = RequestsClient() http_client.set_api_key(host=host, api_key=f'Token {token}', param_in='header', param_name='Authorization') # noinspection PyBroadException try: self.client = SwaggerClient.from_url(f'{service_url}/swagger.json', http_client=http_client) log.info(f"Connected to Heartbeat client at: url={service_url}") except Exception as e: log.exception( f"Failed to connect to Heartbeat client: url={service_url}") self.client = None raise e
def test_hostname_if_passed_overrides_origin_url(httprettified, swagger_dict): register_get("http://foo/test_http?", body='') swagger_dict['host'] = 'foo' register_spec(swagger_dict) resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP(test_param="foo").result() assert ["foo"] == httpretty.last_request().querystring['test_param']
def setup_client( url: str, schema: Optional[Dict[str, Any]] = None, ) -> Optional[str]: """ :returns: error message, if appropriate. """ if get_abstraction().client: return None try: config = {'internally_dereference_refs': True} if not schema: client = SwaggerClient.from_url(url, config=config) else: client = SwaggerClient.from_spec(schema, origin_url=url, config=config) except requests.exceptions.ConnectionError: return 'Unable to connect to server.' except ( simplejson.errors.JSONDecodeError, # type: ignore yaml.YAMLError, HTTPError, ): return ('Invalid swagger file. Please check to make sure the ' 'swagger file can be found at: {}.'.format(url)) except SwaggerValidationError: return 'Invalid swagger format.' get_abstraction().client = client return None
def test_correct_route_with_basePath_no_slash(httprettified, swagger_dict): register_get( "http://localhost/lame/test/test_http?test_param=foo", body=u'""') swagger_dict["basePath"] = "/lame/test" register_spec(swagger_dict) resource = SwaggerClient.from_url(API_DOCS_URL).api_test assert resource.testHTTP(test_param="foo").result() is None
def test_additionalProperty_in_model_in_response( httprettified, swagger_dict, sample_model): register_spec(swagger_dict) sample_model["extra"] = 42 register_get("http://localhost/test_http", body=simplejson.dumps(sample_model)) resource = SwaggerClient.from_url(API_DOCS_URL).api_test result = resource.testHTTP().result() assert result.extra == 42
def get_request_client(): global _request_client if not _request_client: rc = RequestsClient() rc.authenticator = APIKeyAuthenticator(HOST, config.settings.bitmex_api_key, config.settings.bitmex_secret_key) _request_client = SwaggerClient.from_url(SPEC_URI, config=api_config, http_client=rc) return _request_client
def schematizer_client(self): """Returns a bravado client for the schematizer api. By default, this will connect to a schematizer instance running in the included docker-compose file. """ return SwaggerClient.from_url( 'http://{0}/swagger.json'.format(self.schematizer_host_and_port) )
def test_default_value_not_in_request(httprettified, swagger_dict): # Default should be applied on the server side so no need to send it in # the request. swagger_dict['paths']['/test_http']['get']['parameters'][0]['default'] = 'X' register_spec(swagger_dict) register_get("http://localhost/test_http?") resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP().result() assert 'test_param' not in httpretty.last_request().querystring
def __init__( self, url, config=DEFAULT_CONFIG, http_client=None, request_headers=None): swagger_path = '{}/swagger.json'.format(url.rstrip("/")) config['formats'] = [int64_format] self._config = config self.models = SwaggerClient.from_url(swagger_path, config=config, http_client=http_client, request_headers=request_headers) self.client = self.models.WorkflowExecutionService
def test_parameter_in_path_of_request(httprettified, swagger_dict): path_param_spec = { "in": "path", "name": "param_id", "type": "string" } paths_spec = swagger_dict['paths'] paths_spec['/test_http/{param_id}'] = paths_spec.pop('/test_http') paths_spec['/test_http/{param_id}']['get']['parameters'].append( path_param_spec) register_spec(swagger_dict) register_get('http://localhost/test_http/42?test_param=foo') resource = SwaggerClient.from_url(API_DOCS_URL).api_test assert resource.testHTTP(test_param="foo", param_id="42").result() is None
def test_parameter_in_path_of_request(httprettified, swagger_dict): path_param_spec = { 'in': 'path', 'name': 'param_id', 'required': True, 'type': 'string', } paths_spec = swagger_dict['paths'] paths_spec['/test_http/{param_id}'] = paths_spec.pop('/test_http') paths_spec['/test_http/{param_id}']['get']['parameters'].append( path_param_spec) register_spec(swagger_dict) register_get('http://localhost/test_http/42?test_param=foo') resource = SwaggerClient.from_url(API_DOCS_URL).api_test assert resource.testHTTP(test_param='foo', param_id='42').result() is None
def setUp(self): httpretty.register_uri( httpretty.GET, "http://localhost/api-docs", body=open('test-data/1.2/simple/resources.json', 'r').read()) httpretty.register_uri( httpretty.GET, "http://localhost/api-docs/simple", body=open('test-data/1.2/simple/simple.json', 'r').read()) httpretty.register_uri( httpretty.GET, "http://localhost/api-docs/simple1", body=open('test-data/1.2/simple/simple1.json', 'r').read()) # Default handlers for all swagger.py access self.client = SwaggerClient.from_url(u'http://localhost/api-docs')
def test_model_in_response(httprettified, swagger_dict, sample_model): register_spec(swagger_dict) register_get("http://localhost/test_http", body=json.dumps(sample_model)) client = SwaggerClient.from_url(API_DOCS_URL) result = client.api_test.testHTTP().result() User = client.get_model('User') School = client.get_model('School') assert isinstance(result, User) for school in result.schools: assert isinstance(school, School) assert User( id=42, schools=[ School(name="School1"), School(name="School2") ]) == result
def test_array_with_collection_format_in_path_of_request( httprettified, swagger_dict): path_param_spec = { 'in': 'path', 'name': 'param_ids', 'type': 'array', 'items': { 'type': 'integer' }, 'collectionFormat': 'csv', } swagger_dict['paths']['/test_http/{param_ids}'] = \ swagger_dict['paths'].pop('/test_http') swagger_dict['paths']['/test_http/{param_ids}']['get']['parameters'] = \ [path_param_spec] register_spec(swagger_dict) register_get('http://localhost/test_http/40,41,42') resource = SwaggerClient.from_url(API_DOCS_URL).api_test assert resource.testHTTP(param_ids=[40, 41, 42]).result() is None
def test_model_in_body_of_request(httprettified, swagger_dict, sample_model): param_spec = { "in": "body", "name": "body", "schema": { "$ref": "#/definitions/User" } } swagger_dict["paths"]["/test_http"]['post']["parameters"] = [param_spec] register_spec(swagger_dict) httpretty.register_uri(httpretty.POST, "http://localhost/test_http") client = SwaggerClient.from_url(API_DOCS_URL) resource = client.api_test User = client.get_model('User') School = client.get_model('School') user = User(id=42, schools=[School(name='s1')]) resource.testHTTPPost(body=user).result() body = simplejson.loads(httpretty.last_request().body.decode('utf-8')) assert {'schools': [{'name': 's1'}], 'id': 42} == body
def download_table(self, symbol, start_time=None, price_func=None, store_symbol=None): # Get bravado client on first download call if self.client is None: if self.auth: self.client = get_request_client() else: self.client = SwaggerClient.from_url(SPEC_URI, config=api_config) # In general we may need separate symbol strings for storage and to pass to API # (as for futures), but they also may be equal (as for currencies) if store_symbol is None: store_symbol = symbol if price_func is None: price_func = self._augment_trades store = Store(self.library, '', store_symbol) df = pd.DataFrame() i = 0 n = 0 while True: try: res = pd.DataFrame(self.client.Trade.Trade_getBucketed(count=500, start=i*500, symbol=symbol, binSize='1d', startTime=start_time).result()) except bravado.exception.HTTPTooManyRequests: logger.info('Requests limit exceeded, sleeping for 5 mins...') sleep(300) logger.info('Resuming download') continue if len(res) == 0: break # keep track of total records count for calling functions to know if we got any data n += len(res) df = df.append(res) # send data to db each 150K rows and empty local df so it won't get too big if len(df) > 150000: # make this number a class property? store.write(price_func(df.fillna(value=np.nan))) df = pd.DataFrame() i += 1 if len(df) > 0: store.write(price_func(df.fillna(value=np.nan))) return n
def from_url(cls, spec_url, http_client=None, privkey=None, **kwargs): """ Build a :class:`SwaggerClient` from a url to the Swagger specification for a RESTful API. :param spec_url: url pointing at the swagger API specification :type spec_url: str :param http_client: an HTTP client used to perform requests :type http_client: :class:`bravado.http_client.HttpClient` """ if privkey is None: privkey = bitjws.PrivateKey() elif isinstance(privkey, str): privkey = bitjws.PrivateKey(bitjws.wif_to_privkey(privkey)) if http_client is None: host = urlparse.urlsplit(spec_url).hostname http_client = BitJWSRequestsClient() private_key = bitjws.privkey_to_wif(privkey.private_key) http_client.set_bitjws_key(host, private_key) return SwaggerClient.from_url(spec_url, http_client=http_client, **kwargs)
def test_form_params_in_request(httprettified, swagger_dict): param1_spec = { "in": "formData", "name": "param_id", "type": "integer" } param2_spec = { "in": "formData", "name": "param_name", "type": "string" } path_spec = swagger_dict['paths']['/test_http'] path_spec['post'] = path_spec.pop('get') path_spec['post']['parameters'] = [param1_spec, param2_spec] register_spec(swagger_dict) httpretty.register_uri(httpretty.POST, "http://localhost/test_http?") resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP(param_id=42, param_name='foo').result() content_type = httpretty.last_request().headers['content-type'] assert 'application/x-www-form-urlencoded' == content_type body = urlparse.parse_qs(httpretty.last_request().body) assert {b'param_name': [b'foo'], b'param_id': [b'42']} == body
def test_file_upload_in_request(httprettified, swagger_dict): param1_spec = { "in": "formData", "name": "param_id", "type": "integer" } param2_spec = { "in": "formData", "name": "file_name", "type": "file" } path_spec = swagger_dict['paths']['/test_http'] path_spec['post'] = path_spec.pop('get') path_spec['post']['parameters'] = [param1_spec, param2_spec] path_spec['post']['consumes'] = ['multipart/form-data'] register_spec(swagger_dict) httpretty.register_uri(httpretty.POST, "http://localhost/test_http?") resource = SwaggerClient.from_url(API_DOCS_URL).api_test resource.testHTTP(param_id=42, file_name=cStringIO('boo')).result() content_type = httpretty.last_request().headers['content-type'] assert content_type.startswith('multipart/form-data') assert b"42" in httpretty.last_request().body assert b"boo" in httpretty.last_request().body
def UpdateAPIMapping(self, swagger_path="/swagger/swagger.json"): api = SwaggerClient.from_url(base_url + swagger_path)
from bravado.client import SwaggerClient client = SwaggerClient.from_url("http://localhost:1234/books_api.json") print client.books.getAllBooks().result() idType = client.get_model('idType') bookType = client.get_model('bookType') book = bookType(identifier=idType(ISBN10='12345'), title='title goes here') client.books.addBook(body=book).result() print client.books.getAllBooks().result()