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, 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, 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_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 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 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_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 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 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 before_scenario(context, step): context.account_ids = {} context.player_ids = {} config = { 'also_return_response': True, 'validate_responses': True, 'validate_requests': True, 'validate_swagger_spec': True, 'use_models': True, 'formats': [] } env = context.config.userdata.get('env') context.env_urls = get_environment_variables(env) context.clients = Dict() context.clients.game_service = SwaggerClient.from_spec( load_file('specs/dukedoms_game_service_api.yaml', ), origin_url=context.env_urls.game_service, config=config) context.clients.account_service = SwaggerClient.from_spec( load_file('specs/dukedoms_account_service_api.yaml', ), origin_url=context.env_urls.account_service, config=config)
def bitmex(test=True, config=None, api_key=None, api_secret=None): # config options at http://bravado.readthedocs.io/en/latest/configuration.html if not config: 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, # 'validate_swagger_spec': True, # 'validate_requests': True, # 'formats': [], } host = 'https://www.bitmex.com' if test: host = 'https://testnet.bitmex.com' spec_uri = host + '/api/explorer/swagger.json' spec_dict = get_swagger_json(spec_uri, exclude_formats=EXCLUDE_SWG_FORMATS) if api_key and api_secret: request_client = RequestsClient() request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret) return SwaggerClient.from_spec(spec_dict, origin_url=spec_uri, http_client=request_client, config=config) else: return SwaggerClient.from_spec(spec_dict, origin_url=spec_uri, http_client=None, 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 __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 __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_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_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=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 test_also_return_response(mock_spec): with mock.patch('bravado.client.SwaggerClient.__init__') as mock_init: mock_init.return_value = None SwaggerClient.from_spec({}, config={'also_return_response': True}) mock_init.assert_called_once_with( mock_spec.from_dict.return_value, also_return_response=True, )
def get_client(token=None): if token == None: return SwaggerClient.from_spec(load_file(swagger_json_file)) # Set up client http_client = RequestsClient() return SwaggerClient.from_spec(load_file(swagger_json_file), http_client=http_client)
def __init__(self, url=None, config=DEFAULT_CONFIG, http_client=None, request_headers=None, local=False): """ Instantiates :class:`~bravado.client.SwaggerClient`. For further documentation, refer to the documentation for :meth:`bravado.client.SwaggerClient.from_url` and :meth:`bravado.client.SwaggerClient.from_spec`. :param str url: the URL of a Swagger specification. If ``local`` is True, this should be the base URL of a DOS implementation (see ``local``). :param dict config: see :meth:`bravado.client.SwaggerClient` :param http_client: see :meth:`bravado.client.SwaggerClient` :param request_headers: see :meth:`beravado.client.SwaggerClient` :param bool local: set this to True to load the local schema. If this is True, the ``url`` parameter should point to the host and base path of the implementation under test:: Client(url='https://example.com/ga4gh/dos/v1/', local=True) If False, the ``url`` parameter should point to a Swagger specification (``swagger.json``). """ self._config = config config['formats'] = [int64_format] if local: # :meth:`bravado.client.SwaggerClient.from_spec` takes a schema # as a Python dictionary, which we can conveniently expose # via :func:`ga4gh.dos.schema.present_schema`. schema = ga4gh.dos.schema.present_schema() # Set schema['host'] and schema['basePath'] to the provided # values if specified, otherwise leave them as they are url = urlparse.urlparse(url) schema['host'] = url.netloc or schema['host'] schema['basePath'] = url.path or schema['basePath'] self.models = SwaggerClient.from_spec(spec_dict=schema, config=config, http_client=http_client) else: # If ``local=False``, ``url`` is expected to be a ``swagger.json`` swagger_path = '{}/swagger.json'.format(url.rstrip("/")) self.models = SwaggerClient.from_url( swagger_path, config=config, http_client=http_client, request_headers=request_headers) self.client = self.models.DataObjectService
def test_dereferenced_swagger_schema_bravado_client( schema_format, test_app_deref, ): from bravado.client import SwaggerClient response = test_app_deref.get('/swagger.{0}'.format(schema_format)) deserializer = DESERIALIZERS[schema_format] specs = deserializer(response) SwaggerClient.from_spec(specs)
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 get_paasta_api_client( cluster: str = None, system_paasta_config: SystemPaastaConfig = None, http_res: bool = False, ) -> Any: if not system_paasta_config: system_paasta_config = load_system_paasta_config() if not cluster: cluster = system_paasta_config.get_cluster() api_endpoints = system_paasta_config.get_api_endpoints() if cluster not in api_endpoints: log.error("Cluster %s not in paasta-api endpoints config", cluster) return None url = str(api_endpoints[cluster]) parsed = urlparse(url) if not parsed: log.error("Unsupported paasta-api url %s", url) return None api_server = parsed.netloc # Get swagger spec from file system instead of the api server paasta_api_path = os.path.dirname(paasta_tools.api.__file__) swagger_file = os.path.join(paasta_api_path, "api_docs/swagger.json") if not os.path.isfile(swagger_file): log.error("paasta-api swagger spec %s does not exist", swagger_file) return None with open(swagger_file) as f: spec_dict = json.load(f) # replace localhost in swagger.json with actual api server spec_dict["host"] = api_server spec_dict["schemes"] = [parsed.scheme] # sometimes we want the status code requests_client = PaastaRequestsClient( scheme=parsed.scheme, cluster=cluster, system_paasta_config=system_paasta_config) if http_res: config = {"also_return_response": True} c = SwaggerClient.from_spec(spec_dict=spec_dict, config=config, http_client=requests_client) else: c = SwaggerClient.from_spec(spec_dict=spec_dict, http_client=requests_client) return paasta_tools.api.auth_decorator.AuthClientDecorator( c, cluster_name=cluster)
def test_remove_bravado_configs(mock_spec, processed_default_config): config = CONFIG_DEFAULTS.copy() config['validate_swagger_spec'] = False # bravado_core config SwaggerClient.from_spec({}, config=config) mock_spec.from_dict.assert_called_once_with( {}, # spec_dict None, # spec_url mock.ANY, # http_client { 'bravado': processed_default_config, 'validate_swagger_spec': False, }, # config )
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 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_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_paasta_api_client(cluster=None, system_paasta_config=None): if not system_paasta_config: system_paasta_config = load_system_paasta_config() if not cluster: cluster = system_paasta_config.get_cluster() api_endpoints = system_paasta_config.get_api_endpoints() if cluster not in api_endpoints: log.error('Cluster %s not in paasta-api endpoints config', cluster) return None url = str(api_endpoints[cluster]) parsed = urlparse(url) if not parsed: log.error('Unsupported paasta-api url %s', url) return None api_server = parsed.netloc # Get swagger spec from file system instead of the api server paasta_api_path = os.path.dirname(sys.modules['paasta_tools.api'].__file__) swagger_file = os.path.join(paasta_api_path, 'api_docs/swagger.json') if not os.path.isfile(swagger_file): log.error('paasta-api swagger spec %s does not exist', swagger_file) return None with open(swagger_file) as f: spec_dict = json.load(f) # replace localhost in swagger.json with actual api server spec_dict['host'] = api_server return SwaggerClient.from_spec(spec_dict=spec_dict)
def __init__(self, swagger_spec: Spec): """ :param swagger_spec: Complete swagger specification for the API to test. """ self.host = "localhost" self.swagger_spec = swagger_spec self.base_path = swagger_spec.client_spec_dict.get("basePath", "") self.swagger_spec.spec_dict['host'] = f'{self.host}:{TEST_PORT}' # setting validate requests to false since we only care about # responses config = { "also_return_response": True, "use_models": False, "validate_requests": False, "formats": swagger_spec.config.get("formats", []) } self.config = config # Bravado provides an async client, but it doesnt run on ioloop? from docs: # Fido is a simple, asynchronous HTTP client built on top of Crochet and Twisted with an implementation # inspired by the book "Twisted Network Programming Essentials". It is intended to be used in environments # where there is no event loop, and where you cannot afford to spin up lots of threads (otherwise you # could just use a ThreadPoolExecutor). self.swagger_client = SwaggerClient.from_spec( self.swagger_spec.spec_dict, http_client=RequestsClient(), config=config)
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 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 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 from_spec(cls, spec_dict, origin_url=None, http_client=None, privkey=None, **kwargs): """ Build a :class:`SwaggerClient` from swagger api docs :param spec_dict: a dict with a Swagger spec in json-like form :param origin_url: the url used to retrieve the spec_dict :type origin_url: str :param http_client: an HTTP client used to perform requests :type http_client: :class:`bravado.http_client.HttpClient` :param str privkey: The WIF private key to use for bitjws signing """ 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(origin_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_spec(spec_dict, http_client=http_client, **kwargs)
def __init__(self, service, http_client=None): """Create an OpenAPI client.""" server_url, spec_file = OPENAPI_SPECS[service] json_spec = self._get_spec(spec_file) current_instance = BaseAPIClient._bravado_client_instance # We reinstantiate the bravado client instance if # 1. The current instance doesn't exist, or # 2. We're passing an http client (likely a mock), or # 3. The current instance is a Mock, meaning that either we want to # use the `RequestClient` or we're passing a different mock. if ( current_instance is None or http_client or isinstance(current_instance.swagger_spec.http_client, Mock) ): BaseAPIClient._bravado_client_instance = SwaggerClient.from_spec( json_spec, http_client=http_client or RequestsClient(ssl_verify=False), config={"also_return_response": True}, ) self._load_config_from_env() self._client = BaseAPIClient._bravado_client_instance if server_url is None: raise MissingAPIClientConfiguration( "Configuration to connect to {} is missing.".format(service) ) self._client.swagger_spec.api_url = server_url self.server_url = server_url
def get_api_client(config, validation=False): if config.has_key('client'): return config['client'] url = "https://%s/api/v1/spec/openapi/nsx_api.json" % config['nsxManager'][ 'ip'] base64string = base64.encodestring( ('%s:%s' % (config['nsxManager']['username'], config['nsxManager']['password'])).encode("utf-8"))[:-1] headers = {"Authorization": "Basic %s" % base64string.decode("utf-8")} context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE req = urllib2.Request(url=url, headers=headers) response = urllib2.urlopen(req, context=context) raw_spec = json.loads(response.read()) raw_spec['host'] = config['nsxManager']['ip'] http_client = RequestsClient() http_client.session.verify = False http_client.set_basic_auth(config['nsxManager']['ip'], config['nsxManager']['username'], config['nsxManager']['password']) config = { 'also_return_response': True, 'validate_swagger_spec': validation, 'validate_responses': False, 'validate_requests': False, 'use_models': False } client = SwaggerClient.from_spec(raw_spec, http_client=http_client, config=config) config['client'] = client return client
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 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 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 test_headers(self): self.uut = SwaggerClient.from_resource_listing(self.resource_listing) httpretty.register_uri( httpretty.GET, "http://swagger.py/swagger-test/pet", body='[]') self.uut.pet.listPets( _request_options={'headers': {'foo': 'bar'}}).result() self.assertEqual('bar', httpretty.last_request().headers['foo'])
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 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_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 load_client(apikey=None): host = 'api.mpcontribs.org' if apikey else 'localhost:5000' protocol = 'https' if apikey else 'http' spec_url = f'{protocol}://{host}/apispec.json' http_client = RequestsClient() if apikey: http_client.set_api_key( host, apikey, param_in='header', param_name='x-api-key' ) loader = Loader(http_client) spec_dict = loader.load_spec(spec_url) spec_dict['host'] = host spec_dict['schemes'] = [protocol] return SwaggerClient.from_spec(spec_dict, spec_url, http_client, {'validate_responses': False})
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_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