Client allows for quick and easy access any REST or REST-like API.
763491
function Client (globalRequest, maxSockets) {
  var emptyResponse = JSON.parse(JSON.stringify(response))
  var body = ''
  var httpAgent = null
  var httpsAgent = null

  if (maxSockets) {
    httpAgent = new http.Agent({ maxSockets: maxSockets })
    httpsAgent = new https.Agent({ maxSockets: maxSockets })
  }

  // utility function to create an empty request object
  this.emptyRequest = function () {
    return JSON.parse(JSON.stringify(request))
  }

  // utility function to detect empty objects
  function isEmpty (obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        return false
      }
    }
    return true
  }

  // add query paramaters to a URL
  function buildPath (basePath, queryParams) {
    basePath = basePath.concat('?')
    var url = basePath.concat(queryString.stringify(queryParams))
    return url
  }

  function buildRequest (globalRequest, endpointRequest) {
    var request = JSON.parse(JSON.stringify(globalRequest))
    request.host = endpointRequest.host || globalRequest.host
    request.method = endpointRequest.method

    if (endpointRequest.port) {
      request.port = endpointRequest.port
    }

    // build URL
    request.path = !isEmpty(endpointRequest.queryParams)
      ? buildPath(endpointRequest.path, endpointRequest.queryParams)
      : endpointRequest.path

    // add headers
    if (!isEmpty(endpointRequest.headers)) {
      for (var attrname in endpointRequest.headers) {
        request.headers[attrname] = endpointRequest.headers[attrname]
      }
    }

    // add the request body's content length
    if (!isEmpty(endpointRequest.body)) {
      body = JSON.stringify(endpointRequest.body)
      request.headers['Content-Length'] = Buffer.byteLength(body)
      request.headers['Content-Type'] = 'application/json'
    }

    // if maxsockets where provided use the apropriate agent
    if (maxSockets) {
      request.agent = endpointRequest.test === true ? httpAgent : httpsAgent
    }
    return request
  }

  // API is the main interface to the API.
  this.API = function (endpointRequest, callback) {
    var request = buildRequest(globalRequest, endpointRequest)

    var requestProtocol = null;

    if (endpointRequest.test === true) {
      requestProtocol = http
      request.port = endpointRequest.port
    } else {
      requestProtocol = https
    }

    var httpRequest = requestProtocol.request(request, function (httpResponse) {
      var responseBody = ''

      // cature the response from the API
      httpResponse.on('data', function (chunk) {
        responseBody += chunk
      })

      // after the call is complete, build the response object
      httpResponse.on('end', function () {
        var response = JSON.parse(JSON.stringify(emptyResponse))
        response.statusCode = httpResponse.statusCode
        response.body = responseBody
        response.headers = httpResponse.headers
        callback(response)
      })
    })

    httpRequest.on('error', function (e) {
      var response = JSON.parse(JSON.stringify(emptyResponse))
      response.statusCode = e.statusCode || 500
      response.body = JSON.stringify({
        message: e.message,
        name: e.name,
        stack: e.stack
      })
      callback(response)
    })

    // if thre is a request body, sent it
    if (!isEmpty(endpointRequest.body)) {
      httpRequest.write(body)
    }

    httpRequest.end()
  }

  return this
}
1351822
def _request(self, method, url, params, headers, content, form_content):
        # type: (str, str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
        
        request = ClientRequest(method, self.format_url(url))

        if params:
            request.format_parameters(params)

        if headers:
            request.headers.update(headers)
        # All requests should contain a Accept.
        # This should be done by Autorest, but wasn't in old Autorest
        # Force it for now, but might deprecate it later.
        if "Accept" not in request.headers:
            _LOGGER.debug("Accept header absent and forced to application/json")
            request.headers['Accept'] = 'application/json'

        if content is not None:
            request.add_content(content)

        if form_content:
            request.add_formdata(form_content)

        return request
1257085
function API(opts) {
  opts = opts || {};

  this.request = opts.request || request;
  this.baseUrl = opts.baseUrl || BASE_URL;
  this.payProHttp = null; // Only for testing
  this.doNotVerifyPayPro = opts.doNotVerifyPayPro;
  this.timeout = opts.timeout || 50000;
  this.logLevel = opts.logLevel || 'silent';
  this.supportStaffWalletId = opts.supportStaffWalletId;

  log.setLevel(this.logLevel);
}
995473
function Client(transport, fastPathTransport) {
	Sec.call(this, transport, fastPathTransport);
	// for basic RDP layer (in futur)
	this.enableSecureCheckSum = false;
	var self = this;
	this.transport.on('connect', function(gccClient, gccServer, userId, channels) {
		self.connect(gccClient, gccServer, userId, channels);
	}).on('close', function() {
		self.emit('close');
	}).on('error', function (err) {
		self.emit('error', err);
	});
}
574451
def get_rest_api():
    
    assert _has_local_install

    url=[]
    ok = _run_st(['geturl', '--api'], lines=url)
    if not ok:
        raise ChildProcessError('streamtool geturl')
    return url[0]
863913
public function getClient()
    {
        $options = [
            'base_uri' => $this->base_url . 'rest/api/',
            'auth' => [$this->user, $this->pass],
        ];

        return new Client($options);
    }
1195073
def makeAuthAPICall(url = API_BASE)
      request_url = "#{url}/client/#{@client_id}/authenticate?apikey=#{@api_key}"
      begin
        response = RestClient.get(request_url)
        return response
      rescue RestClient::Exception => error
        begin
          response = JSON.parse(error.response)

          unless response
            raise InvalidRequestException, "The Import API returned: #{error.http_code} #{error.message}"
          end

          raise InvalidRequestException,
            "The Import API returned: #{response['code']} #{response['message']}. Reasons: #{response['reasons']}"
        rescue JSON::ParserError, TypeError => json_parse_error
          raise InvalidResponseException,
            "RestClientError: #{error.class}\n Message: #{error.message}\n Response Code: #{error.http_code}\n Full Response: #{error.response}"
        end
      end
    end
13508
def _api_post(path, data, server=None):
    '''
    
    '''
    server = _get_server(server)
    response = requests.post(
            url=_get_url(server['ssl'], server['url'], server['port'], path),
            auth=_get_auth(server['user'], server['password']),
            headers=_get_headers(),
            data=salt.utils.json.dumps(data),
            verify=False
    )
    return _api_response(response)
559772
def _requests(self, url, method='GET', headers=None, params=None, data=None, errors=None):

        '''  '''

        title = '%s._requests' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # validate access token
        if not self._access_token:
            self.access_token()
            if self.retrieve_details:
                self._get_products()
    
    # refresh token
        current_time = time()
        if current_time > self.expires_at:
            self.access_token()
            if self.retrieve_details:
                self._get_products()

    # construct request kwargs
        request_kwargs = {
            'url': url,
            'headers': { 
                'Authorization': 'Bearer %s' % self._access_token,
                'Accept': 'application/json;v=2'
            },
            'params': {},
            'data': {}
        }
        if headers:
            request_kwargs['headers'].update(headers)
        if params:
            request_kwargs['params'].update(params)
        if data:
            request_kwargs['data'].update(data)

    # send request
        if method == 'POST':
            try:
                response = requests.post(**request_kwargs)
            except Exception:
                if self.requests_handler:
                    request_kwargs['method'] = 'POST'
                    request_object = requests.Request(**request_kwargs)
                    return self.requests_handler(request_object)
                else:
                    raise
        elif method == 'GET':
            try:
                response = requests.get(**request_kwargs)
            except Exception:
                if self.requests_handler:
                    request_kwargs['method'] = 'GET'
                    request_object = requests.Request(**request_kwargs)
                    return self.requests_handler(request_object)
                else:
                    raise
        else:
            raise ValueError('%s(method='') must be either GET or POST' % title)

    # handle response
        response_details = self.response_handler.handle(response, errors)
        
        return response_details
1015166
function server()
    {
        if(isset($this->data['openid_assoc_handle'])) {
            $this->assoc = $this->getAssoc($this->data['openid_assoc_handle']);
            if(isset($this->assoc['data'])) {
                # We have additional data stored for setup.
                $this->data += $this->assoc['data'];
                unset($this->assoc['data']);
            }
        }
            
        if (isset($this->data['openid_ns'])
            && $this->data['openid_ns'] == $this->ns
        ) {
            if(!isset($this->data['openid_mode'])) $this->errorResponse();
            
            switch($this->data['openid_mode'])
            { 
            case 'checkid_immediate':
            case 'checkid_setup':
                $this->checkRealm();
                # We support AX xor SREG.
                $attributes = $this->ax();
                if(!$attributes) {
                    $attributes = $this->sreg();
                }
                
                # Even if some user is authenticated, we need to know if it's
                # the same one that want's to authenticate.
                # Of course, if we use select_id, we accept any user.
                if (($identity = $this->checkid($this->data['openid_realm'], $attrValues))
                    && ($this->select_id || $identity == $this->data['openid_identity'])
                ) {
                    $this->positiveResponse($identity, $attrValues);
                } elseif($this->data['openid_mode'] == 'checkid_immediate') {
                    $this->redirect($this->response(array('openid.mode' => 'setup_needed')));
                } else {
                    if(!$this->assoc) {
                        $this->generateAssociation();
                        $this->assoc['private'] = true;
                    }
                    $this->assoc['data'] = $this->data;
                    $this->setAssoc($this->assoc['handle'], $this->assoc);
                    $this->setup($this->data['openid_identity'],
                                 $this->data['openid_realm'],
                                 $this->assoc['handle'],
                                 $attributes);
                }
                break;
            case 'associate':
                $this->associate();
                break;
            case 'check_authentication':
                $this->checkRealm();
                if($this->verify()) {
                    echo "ns:$this->ns\nis_valid:true";
                    if(strpos($this->data['openid_signed'],'invalidate_handle') !== false) {
                        echo "\ninvalidate_handle:" . $this->data['openid_invalidate_handle'];
                    }
                } else {
                    echo "ns:$this->ns\nis_valid:false";
                }
                die();
                break;
            default:
                $this->errorResponse();
            }
        } else {
            $this->xrds();
        }
    }
1366860
def basic_client():
    """"""
    es_connected = False
    while not es_connected:
        try:
            ES = Elasticsearch(
                hosts=[HOSTNAME]
            )
            es_connected = True
        except TransportError as e:
            logging.info('Not yet connected: %s, sleeping for 1s', e)
            time.sleep(1)
    return ES
1147315
function Library(options) {
  options = options || {};

  /**
   * `Client` instance that handles the library's API access.
   *
   * @property client
   * @type Client
   */
  this.client = options.client || new Client();

  /**
   * The library's group id. Note that the `user` property
   * takes precedence over `group`; thus, if changing a user
   * library instance to a group library, the `user` id
   * must be deleted.
   *
   * @property group
   * @type Number
   */
  if (options.group) this.group = options.group;

  /**
   * The library's user id. A library should have either this
   * or a `group` id defined.
   *
   * @property user
   * @type Number
   */
  if (options.user) this.user = options.user;

  /**
   * The API key to use for this library. The key will be
   * added automatically to every request made for this
   * library.
   *
   * @property key
   * @type String
   */
  if (options.key) this.key = options.key;

  /**
   * All options will be sent as parameters with every API call
   * issued by the library.
   *
   * @property options
   * @type Object
   */
  this.options = omit(options, 'client', 'user', 'group', 'key', 'headers');


  Object.defineProperties(this, {

    /**
     * HTTP headers to be included in
     * every request for this library.
     *
     * @property headers
     * @type Object
     */
    headers: {
      enumerable: true,
      value: extend({}, options.headers)
    },

    /**
     * Items proxy. Calls the library's `get` method and injects
     * 'items' into the path argument. The proxy accepts exactly
     * the same arguments as `get`.
     *
     * @example
     *     lib.items();
     *     //-> calls lib.get('items');
     *
     *     lib.items(42);
     *     //-> calls lib.get('items/42');
     *
     *     lib.items.top();
     *     //-> calls lib.get('items/top');
     *
     *     lib.items.top({ format: 'versions' });
     *     //-> calls lib.get('items/top', { format: 'versions' });
     *
     * @method items
     */
    items: {
      value: items(this)
    },

    collections: {
      value: collections(this)
    },

    tags: {
      value: proxy(this, 'get', 'tags', '', true)
    },

    searches: {
      value: proxy(this, 'get', 'searches')
    },

    groups: {
      value: proxy(this, 'get', 'groups')
    },

    keys: {
      value: proxy(this, 'get', 'keys')
    }
  });
}
431378
function API (parameters) {
  // Own API resource prefix (e.g. '/resource').
  this.path = parameters.path || null;

  // Own documentation.
  this.title = parameters.title || null;
  this.description = parameters.description || null;

  // Own test setup functions.
  this.beforeEachTest = parameters.beforeEachTest || null;
  this.afterEachTest = parameters.afterEachTest || null;

  // Parent API resource (or root server app).
  this.parent = parameters.parent || null;

  // API sub-resources (API instances) by relative path (e.g. '/subresource').
  this.children = {};

  // Own request handlers (handler parameters) by method (e.g. 'post').
  this.handlers = {};
}
678588
public Client get( Client client ) {
    return RestfulUtils.show( ClientService.PATH, client, Client.class, super.httpClient );
  }
136272
function ApiclientAdapter(resource) {
    this.admin = admin;
    this.resource = resource || {};

    // loop through API interface for resource to get methods to expose
    var me = this;
    _.each(resource.api, function (methodInfo, httpMethod) {
        _.each(methodInfo, function (operation, path) {
            me[operation] = function (req) {
                return me.send(httpMethod, path, req);
            };
        });
    });
}
35980
def get_client(provider, token=''):
    ""
    cls = OAuth2Client
    if provider.request_token_url:
        cls = OAuthClient
    return cls(provider, token)
656864
function Client() {
	this._host = '127.0.0.1'; // localhost
	this._port = 4242; // default OpenTSDB port

	// Output: (opinionated defaults)
	this._ms = true;
	this._arrays = true;
	this._tsuids = false;
	this._annotations = 'none'; // ["none","local","all"]

	// Time:
	this._start = null; // required
	this._end = null;

	// Queries:
	this._queries = null; // required

	// URL generator:
	this._url = urlFactory( this );

	return this;
}