API *******************************************************************
10835
public function build(): Html
	{
		$wrapper = Html::el();
		foreach ($this->tags as $property => $content) {
			$wrapper->addHtml(Html::el('meta')->addAttributes([
				'property' => $property,
				'content' => $content,
			]));
		}

		return $wrapper;
	}
265454
function setApi() {
            self.api = {};
            if(process && process.env && process.env.APPVEYOR_API_URL) {
                var fullUrl = process.env.APPVEYOR_API_URL;

                var urlParts = fullUrl.split("/")[2].split(":");
                self.api = {
                    host: urlParts[0],
                    port: urlParts[1],
                    endpoint: "/api/tests/batch"
                };
            }
            else {
                throw Error("Not running in AppVeyor environment");
            }
        }
1315412
private String getApiIndex(Api api) {
        return getApiIndex(api.getOrganizationId(), api.getApiId(), api.getVersion());
    }
157881
function RequestHooks_process(api) {
        var that = this, route = api.parsedUrl.pathname;
        logger.info('RequestHooks.process:', route);
        return new Promise(function (resolve, reject) {
            var hook;
            try {
                hook = that.get(route);
                logger.info('RequestHooks.hook:', hook);
                if (!!hook) {
                    resolve(hook.func(api));
                } else {
                    resolve(false);
                }
            } catch (e) {
                logger.error('RequestHooks.hook:', {
                    hook: hook,
                    e: e
                });
                reject(new error.HttpError(500, {hook: route}, 'Hook error', e));
            }
        });
    }
1173351
function apiService() {

    'use strict';

    /*jshint validthis: true */

    var service = this;

    /**
     * trace errors to console
     * @var {Boolean}
     */
    this.trace = false;

    /**
     * HTTP status for service
     * will be used only by REST service
     * @var {Number}
     */
    this.httpstatus = 200;

    /**
     * Path used in getService
     * defined withing the function app.getService
     * @var {String}
     */
    this.path = null;


    /**
     * Service outcome
     * contain success boolean
     * a list of alert messages
     * errfor: errors associated to fields
     */
    this.outcome = {
        success: true,
        alert: [],
        errfor: {}
    };

    this.Q = require('q');

    /**
     * Defered service result
     */
    this.deferred = this.Q.defer();

    /**
     * Services instances must implement
     * this method to resolve or reject the service promise
     *
     * @param {Object} params
     *
     * @return {Promise}
     */
    this.getResultPromise = function(params) {
        console.log('Not implemented');

        return this.deferred.promise;
    };

    /**
     * Set application
     * @param {Object} app
     */
    this.setApp = function(app) {
        service.app = app;
    };


    /**
     * Add alert to service
     * @param {string} type   One of boostrap alert types (danger|success|info)
     * @param {String|Error} err  Error message or object
     */
    this.addAlert = function(type, err) {

        var alert = { type: type };

        if (err instanceof Error) {
            alert.message = err.name+' : '+err.message;
            alert.stack = err.stack;

        } else if (typeof err === 'string') {
            alert.message = err;
        } else {
            console.error(err);
            throw new Error('Wrong error type, must be a string or Error, got '+(typeof err));
        }

        service.outcome.alert.push(alert);
    };


    /**
     * Get an error object from a mixed value
     * @param   {String|Error} err
     * @returns {Error}
     */
    this.getError = function(err) {
        if (err instanceof Error) {
            return err;
        }

        return new Error(err);
    };



    /**
     *  Reject the service promise with an forbidden status
     * The server understood the request, but is refusing to fulfill it.
     * Authorization will not help and the request SHOULD NOT be repeated.
     * If the request method was not HEAD and the server wishes to make public
     * why the request has not been fulfilled, it SHOULD describe the reason for
     * the refusal in the entity. If the server does not wish to make this
     * information available to the client, the status code 404 (Not Found)
     * can be used instead.
     * @param {String|Error} err
     */
    this.forbidden = function(err) {
        service.httpstatus = 403;
        service.outcome.success = false;
        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Reject the service promise with an error status
     * The HTTP server encountered an unexpected condition which prevented
     * it from fulfilling the request.
     * For example this error can be caused by a serveur misconfiguration,
     * or a resource exhausted or denied to the server on the host machine.
     *
     * @param {String|Error} err
     */
    this.error = function(err) {

        if (err.name === 'ValidationError') {
            return service.handleMongoError(err); // 400
        }

        service.httpstatus = 500;
        service.outcome.success = false;
        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Ouput a 404 error
     * with an outcome message
     *
     * @param {String|Error} err
     */
    this.notFound = function(err) {
        service.httpstatus = 404;
        service.outcome.success = false;

        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Ouput a 410 error
     * with an outcome message
     *
     * @param {String|Error} err
     */
    this.gone = function(err) {
        service.httpstatus = 410;
        service.outcome.success = false;

        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Set a success message into outcome
     * @param {String} message
     */
    this.success = function(message) {

        service.addAlert('success', message);

    };


    /**
     * output document and $outcome with a sucess message
     *
     * @param {Document} document           Mongoose document
     * @param {String} message              message for outcome
     */
    this.resolveSuccess = function(document, message) {

        service.outcome.success = true;
        service.success(message);

        var output;
        if (document.toObject) {
            output = document.toObject();
        } else {
            output = document;
        }
        output.$outcome = service.outcome;

        service.deferred.resolve(output);
    };


    /**
     * Get a document using the sibling get service
     * @param {String} param all parameters or document ID to get, this will set the 'id' param in the parameters given to GET service
     * @return {Promise} promise resolve to an object but without the $outcome property
     */
    this.get = function(param) {
        if (null === service.path) {
            throw new Error('The path need to be defined in the app.getService function');
        }

        var path = service.path.split('/');
        delete path[path.length-1];

        if (typeof param !== 'object' || param.constructor.name === 'ObjectID') {
            param = { id: param };
        }

        return service.app.getService(path.join('/')+'/get')
        .getResultPromise(param)
        .then(function(serviceObject) {
            delete serviceObject.$outcome;
            return serviceObject;
        });
    };


    /**
     * output document from the sibling get service and $outcome with a sucess message
     * @param {String} param       savedDocument ID or parameters
     * @param {String} message  message for outcome
     */
    this.resolveSuccessGet = function(param, message) {

        this.get(param).then(function(document) {
            service.resolveSuccess(document, message);
        })
        .catch(service.error);
    };


    /**
     * emit exception if parameter contain a mongoose error
     *
     * @param {Error|null} err - a mongoose error or no error
     * @param {Boolean} trace   set to false to disable console.trace of the error
     *
     * @return {Boolean}
     */
    this.handleMongoError = function(err) {
        if (err) {

            if (true === service.trace) {
                console.trace(err);
            }

            service.httpstatus = 400; // Bad Request

            if (err.errors) {
              for(var field in err.errors) {
                  var e = err.errors[field];
                  service.outcome.errfor[field] = e.type;
                  service.outcome.alert.push({ type:'danger' ,message: e.message});
              }
            }

            service.outcome.alert.push({ type:'danger' ,message: err.message});
            service.outcome.success = false;

            service.deferred.reject(new Error(err.message));
            return false;
        }

        return true;
    };



    /**
     * @return {Boolean}
     */
    this.hasErrors = function() {

        if (Object.keys(service.outcome.errfor).length !== 0) {
            return true;
        }

        for(var i=0; i<service.outcome.alert.length; i++) {
            if (service.outcome.alert[i].type === 'danger') {
                return true;
            }
        }

        return false;
    };


}
1129067
function selfapi (/* parent, …overrides, child */) {
  // Parent API instance or root server app.
  var parent = null;

  // Child API overrides.
  var path = null;
  var title = null;
  var description = null;

  // Child API instance.
  var child = null;

  if ((this instanceof API) || isServerApp(this)) {
    // Called from parent, e.g. `var api = parent.api(…)`.
    parent = this;
  } else if ((arguments[0] instanceof API) || isServerApp(arguments[0])) {
    // First argument is parent, e.g. `var api = selfapi(parent…)`.
    parent = [].shift.call(arguments);
  }

  if (typeof arguments[0] === 'string' /* || instanceof RegExp */) {
    // Next argument is path, e.g. `api(…path…)`.
    path = [].shift.call(arguments);
    if (typeof arguments[0] === 'string') {
      // Next argument is title, e.g. `api(…path, title…)`.
      title = [].shift.call(arguments);
      if (typeof arguments[0] === 'string') {
        // Next argument is description, e.g. `api(…path, title, description…)`.
        description = [].shift.call(arguments);
      }
    }
  }

  if (arguments[arguments.length - 1] instanceof API) {
    // Last argument is child API instance, e.g. `selfapi(…api)`.
    child = [].pop.call(arguments);
  } else if (typeof arguments[arguments.length - 1] === 'object') {
    // Last argument is parameters object, e.g. `selfapi(…parameters)`.
    var parameters = [].pop.call(arguments);
    child = new API(parameters);
  } else {
    // No further useful argument.
    child = new API({});
  }

  // Apply any overrides.
  if (path) {
    child.path = path;
  }
  if (title) {
    child.title = title;
  }
  if (description) {
    child.description = description;
  }

  // Associate child and parent, triggering the `set parent` function if needed.
  if (parent) {
    child.parent = parent;
  }

  return child;
}
818728
public ApiResponse apiRequest(HttpMethod method,
            Map<String, Object> params, Object data, String... segments) {
        ApiResponse response = null;
        try {
            response = httpRequest(method, ApiResponse.class, params, data,
                    segments);
            log.info("Client.apiRequest(): Response: " + response);
        } catch (HttpClientErrorException e) {
            log.error("Client.apiRequest(): HTTP error: "
                    + e.getLocalizedMessage());
            response = parse(e.getResponseBodyAsString(), ApiResponse.class);
            if ((response != null) && !isEmpty(response.getError())) {
                log.error("Client.apiRequest(): Response error: "
                        + response.getError());
                if (!isEmpty(response.getException())) {
                    log.error("Client.apiRequest(): Response exception: "
                            + response.getException());
                }
            }
        }
        return response;
    }
462899
public function api()
    {
        if (is_null($this->api)) {
            $this->api = app(Api::class);
        }

        return $this->api;
    }
1374696
function(apiClient) {
    this.apiClient = apiClient || ApiClient.instance;



    /**
     * Finds a code
     * Finds a code
     * @param {String} codeId Id of the code
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code}
     */
    this.findCode = function(codeId) {
      var postBody = null;

      // verify the required parameter 'codeId' is set
      if (codeId == undefined || codeId == null) {
        throw "Missing the required parameter 'codeId' when calling findCode";
      }


      var pathParams = {
        'codeId': codeId
      };
      var queryParams = {
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['basicAuth'];
      var contentTypes = ['application/json;charset=utf-8'];
      var accepts = ['application/json;charset=utf-8'];
      var returnType = Code;

      return this.apiClient.callApi(
        '/codes/{codeId}', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }


    /**
     * Lists codes
     * Lists codes
     * @param {Object} opts Optional parameters
     * @param {Array.<String>} opts.types Filter results by types
     * @param {String} opts.search Search codes by free-text query
     * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE
     * @param {String} opts.sortDir ASC or DESC. Default is ASC
     * @param {Integer} opts.firstResult First result
     * @param {Integer} opts.maxResults Max results
     * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>}
     */
    this.listCodes = function(opts) {
      opts = opts || {};
      var postBody = null;


      var pathParams = {
      };
      var queryParams = {
        'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'),
        'search': opts['search'],
        'sortBy': opts['sortBy'],
        'sortDir': opts['sortDir'],
        'firstResult': opts['firstResult'],
        'maxResults': opts['maxResults']
      };
      var headerParams = {
      };
      var formParams = {
      };

      var authNames = ['basicAuth'];
      var contentTypes = ['application/json;charset=utf-8'];
      var accepts = ['application/json;charset=utf-8'];
      var returnType = [Code];

      return this.apiClient.callApi(
        '/codes', 'GET',
        pathParams, queryParams, headerParams, formParams, postBody,
        authNames, contentTypes, accepts, returnType
      );
    }
  }
370004
function fetch(publicAPI, model, name) {
  let fetchCallback = null;
  const requestQueue = [];

  publicAPI[`set${capitalize(name)}FetchCallback`] = (fetchMethod) => {
    if (requestQueue.length) {
      fetchMethod(requestQueue);
    }
    fetchCallback = fetchMethod;
  };

  return {
    addRequest(request) {
      requestQueue.push(request);
      if (fetchCallback) {
        fetchCallback(requestQueue);
      }
    },
    resetRequests(requestList) {
      while (requestQueue.length) {
        requestQueue.pop();
      }
      if (requestList) {
        // Rebuild request list
        requestList.forEach((req) => {
          requestQueue.push(req);
        });
        // Also trigger a request
        if (fetchCallback) {
          fetchCallback(requestQueue);
        }
      }
    },
  };
}
43404
function RequestApi(constructorOptions) {

    LOG.debug('Instantiating new Request object');
    LOG.debug('Validating options');

    try {

        this.options =
            new requestOptions.Constructor().validate(constructorOptions);

    } catch (err) {

        LOG.error('Received error: %s', err);

        throw(
            err
        );

    }

    this.requests = [];
    this.batchId = 1;

}
348502
public JsonResponse apiPost(ApiParams data, ApiFileParams fileParams) throws IOException {
        return httpRequestJson(HttpRequestMethod.POST, data, fileParams);
    }
989270
function API(method, url, data, callback) {
    if (typeof callback === 'undefined') {
        callback  = data;
        data  = {};
    }

    url             = this.prepareUrl(url);
    this.callback   = callback || noop;
    this.data       = data;

    this.options          = extend({}, requestOptions);
    this.options.encoding = this.options.encoding || 'utf-8';

    // these particular set of options should be immutable
    this.options.method         = method;
    this.options.uri            = url;
    this.options.followRedirect = false;

    this[method.toLowerCase()]();

    return this;
}
572932
def perform_api_request(
        self,
        url,
        method='POST',
        headers=None,
        body=None,
        **kwargs
    ):
        '''
        
        '''
        assert method in ('GET', 'POST')
        if method == 'GET':
            response = self._perform_get(url, headers=headers, **kwargs)
        elif method == 'POST':
            response = self._perform_post(url, headers=headers, data=body, **kwargs)
        return response
1035552
public function execute()
    {
        $params = $this->getRequest()->getParams();

        //if no value to any of the required params send error response
        if (empty($params['apiUser']) ||
            empty($params['pass']) ||
            empty($params['code']) ||
            ! $this->isCodeValid($params['code'])
        ) {
            $this->sendAjaxResponse(true);
        } else {
            $this->processAccountCallback($params);
        }
    }
104015
def _make_api_call(self, api_method, **kwargs):
        '''
        '''
        api_url = '/'.join((self.api_base_url, api_method))
        parameters = dict()
        parameters.update(self.default_parameters)
        parameters.update(kwargs)
        post_params = urlencode(parameters).encode('utf-8')
        response = self.opener.open(api_url, post_params)
        return json.loads(response.read().decode('utf-8'))
341076
public T execute() throws ApiException, IOException {
        return client.executeRequest(this.builder, expectedCode, responseClass, needAuth);
    }