Serves the Swagger UI which allows you to try out the documented endpoints. Sets the url
parameter to the swagger yaml that describes the REST API. Creates an apiKey token for the
current user.
421480
@GetMapping
  public String init(Model model) {

    final UriComponents uriComponents =
        ServletUriComponentsBuilder.fromCurrentContextPath().build();
    model.addAttribute("molgenisUrl", uriComponents.toUriString() + URI + "/swagger.yml");
    model.addAttribute("baseUrl", uriComponents.toUriString());

    final String currentUsername = SecurityUtils.getCurrentUsername();
    if (currentUsername != null) {
      model.addAttribute(
          "token", tokenService.generateAndStoreToken(currentUsername, "For Swagger UI"));
    }
    return "view-swagger-ui";
  }
313433
def swaggerify(app, parse_module_info=True, **kwargs):
    

    async def swagger_handler(request):
        """
        Request handler to serve swagger json config for given app
        """
        return web.json_response(app["_swagger_config"])

    # Populate configs for paths from app routes
    paths_config = defaultdict(dict)
    for r in app.router.routes():
        # Title and description are retrieved from docstring of a handler
        docstrings = parse_docstring(r.handler.__doc__ or "")
        if len(docstrings["title"]) > 120:
            # TODO: logging
            docstrings["title"] = docstrings["title"][:120]

        # Some information is just hardcoded as we have strict requirements
        # to input and output format of ws endpoints
        desc = {
            "summary": docstrings["title"],
            "description": docstrings["description"],
            "consumes": ["application/json"],
            "produces": ["application/json"],
            "responses": {
                "400": {"description": "Request is malformed or invalid"},
                "500": {"description": "Response malformed or invalid"},
                "405": {"description": "Method is not allowed"},
            }
        }

        if hasattr(r.handler, "_request_schema"):
            desc["parameters"] = [{
                "in": "body",
                "name": "body",
                "required": True,
                "schema": r.handler._request_schema
            }]
        else:
            desc["parameters"] = [{
                "in": "body",
                "name": "body"
            }]

        if hasattr(r.handler, "_swg_input"):
            desc["parameters"][0].update(r.handler._swg_input)

        if hasattr(r.handler, "_response_schema"):
            desc["responses"]["200"] = {
                # TODO: think how to override
                "description": "Results of the request",
                "schema": r.handler._response_schema
            }
        else:
            desc["responses"]["200"] = {
                "description": "Results of the request"
            }

        if hasattr(r.handler, "_swg_output"):
            desc["responses"]["200"].update(r.handler._swg_output)

        if hasattr(r.handler, "_swg_info"):
            desc.update(r.handler._swg_info)

        paths_config[r._resource._path][r.method.lower()] = desc

    # Populate complete config

    # Get optional information that overrides info part of the config
    swagger_config_info = kwargs.pop("info", {})
    # Some sane defaults
    swagger_config = {
        "swagger": "2.0",
        "schemes": ["http"],
        "paths": paths_config
    }

    # That can be overriden with kwargs
    swagger_config.update(kwargs)

    # Some sane defaults for info part of the config
    swagger_config_info_default = {
        "version": "1.0.0",
    }

    # Which we now can try to extend using introspection, docstrings and
    # global variables of the main module of the app
    if parse_module_info:
        try:
            caller = inspect.currentframe().f_back
            mod = sys.modules[caller.f_globals['__name__']]

            # Try to pull information from docstrings
            swagger_config_info_default.update(parse_docstring(mod.__doc__))

            # As well as global variables
            if hasattr(mod, "__version__"):
                swagger_config_info_default["version"] = mod.__version__

            if hasattr(mod, "__license__"):
                swagger_config_info_default["license"] = {
                    "name": mod.__license__
                    # TODO: add urls for well-known licenses
                }

            # And map it to swagger definitions
            contact_info = {}
            if hasattr(mod, "__author__"):
                contact_info["name"] = mod.__author__
            if hasattr(mod, "__maintainer__"):
                contact_info["name"] = mod.__maintainer__
            if hasattr(mod, "__email__"):
                contact_info["email"] = mod.__email__

            if contact_info:
                swagger_config_info_default["contact"] = contact_info
        except:
            # TODO: logging
            pass

    swagger_config["info"] = swagger_config_info_default

    # override it with data from kwargs["info"]
    swagger_config["info"].update(swagger_config_info)

    app["_swagger_config"] = swagger_config

    app.router.add_route("GET", "/swagger.json", swagger_handler)

    return app
1214796
def post_api url, params
        uri = URI.parse(url)
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = self.secure
        form_params = params.to_query
        res = http.post(uri.request_uri, form_params)
        res.body
      end
480764
def add_swagger_api_route(app, target_route, swagger_json_route):
    
    static_root = get_swagger_static_root()
    swagger_body = generate_swagger_html(
        STATIC_ROOT, swagger_json_route
    ).encode("utf-8")

    async def swagger_ui(request):
        return web.Response(body=swagger_body, content_type="text/html")

    app.router.add_route("GET", target_route, swagger_ui)
    app.router.add_static(STATIC_ROOT, static_root)
315299
private function configure_api()
    {

        // ensure current annotations setting is an array of path or transform into it
        $current_annotations = config('l5-swagger.paths.annotations');
        if (! is_array($current_annotations))
            $current_annotations = [$current_annotations];

        // merge paths together and update config
        config([
            'l5-swagger.paths.annotations' => array_unique(array_merge($current_annotations, [
                __DIR__ . '/Models',
            ])),
        ]);
    }
1123399
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None):
        
        if not self.token:
            raise RuntimeError("You do not have an API token!")

        if not method:
            raise ValueError("Method is required for API calls!")

        if model:
            endpoint = endpoint.format(**vars(model))
        url = '{}{}'.format(self.base_url, endpoint)
        headers = {
            'Authorization': "Bearer {}".format(self.token),
            'Content-Type': 'application/json',
            'User-Agent': self._user_agent,
        }

        if filters:
            headers['X-Filter'] = json.dumps(filters)

        body = None
        if data is not None:
            body = json.dumps(data)

        response = method(url, headers=headers, data=body)

        warning = response.headers.get('Warning', None)
        if warning:
            logger.warning('Received warning from server: {}'.format(warning))

        if 399 < response.status_code < 600:
            j = None
            error_msg = '{}: '.format(response.status_code)
            try:
                j = response.json()
                if 'errors' in j.keys():
                    for e in j['errors']:
                        error_msg += '{}; '.format(e['reason']) \
                                if 'reason' in e.keys() else ''
            except:
                pass
            raise ApiError(error_msg, status=response.status_code, json=j)

        if response.status_code != 204:
            j = response.json()
        else:
            j = None # handle no response body

        return j
1250667
def register_swaggerui_app(app, swagger_uri, api_url, page_title='Swagger UI', favicon_url=None, config=None, uri_prefix=""):

    """"""

    templates_folder = 'templates'
    static_folder = 'dist'

    default_config = {
        'client_realm': 'null',
        'client_id': 'null',
        'client_secret': 'null',
        'app_name': 'null',
        'docExpansion': "none",
        'jsonEditor': False,
        'defaultModelRendering': 'schema',
        'showRequestHeaders': False,
        'supportedSubmitMethods': ['get', 'post', 'put', 'delete', 'patch'],
    }

    if config:
        default_config.update(config)

    default_context = {
        'page_title': page_title,
        'favicon_url': favicon_url,
        'base_url': uri_prefix + swagger_uri,
        'api_url': api_url,
        'app_name': default_config.pop('app_name'),
        'client_realm': default_config.pop('client_realm'),
        'client_id': default_config.pop('client_id'),
        'client_secret': default_config.pop('client_secret'),
        # Rest are just serialized into json string
        # for inclusion in the .js file
        'config_json': json.dumps(default_config)
    }

    app.add_sink(
        StaticSinkAdapter(static_folder),
        r'%s/(?P<filepath>.*)\Z' % swagger_uri,
    )

    app.add_route(
        swagger_uri,
        SwaggerUiResource(templates_folder, default_context)
    )
406856
def json_call(cls, method, url, **kwargs):
        
        # retrieve api key if needed
        empty_key = kwargs.pop('empty_key', False)
        send_key = kwargs.pop('send_key', True)
        return_header = kwargs.pop('return_header', False)
        try:
            apikey = cls.get('apirest.key')
            if not apikey and not empty_key:
                cls.echo("No apikey found for REST API, please use "
                         "'gandi setup' command")
                sys.exit(1)
            if send_key:
                if 'headers' in kwargs:
                    kwargs['headers'].update({'X-Api-Key': apikey})
                else:
                    kwargs['headers'] = {'X-Api-Key': apikey}
        except MissingConfiguration:
            if not empty_key:
                return []
        # make the call
        cls.debug('calling url: %s %s' % (method, url))
        cls.debug('with params: %r' % kwargs)
        try:
            resp, resp_headers = JsonClient.request(method, url, **kwargs)
            cls.dump('responded: %r' % resp)
            if return_header:
                return resp, resp_headers
            return resp
        except APICallFailed as err:
            cls.echo('An error occured during call: %s' % err.errors)
            sys.exit(1)
1372821
function Api(spec, options) {
  if (!(this instanceof Api)) {
    return new Api(spec, options);
  }

  if (typeof spec !== 'object') {
    throw new Error('api spec must be an object');
  }

  options = options || {};

  // path alias for both resourcePath and doc path
  if (spec.path) {
    if (!spec.resourcePath) spec.resourcePath = spec.path;
    if (!options.path) options.path = spec.path;
    delete spec.path;
  }

  // allow user to pass description in spec
  if (spec.description) {
    if (!options.description) options.description = spec.description;
    delete spec.description;
  }

  // user resourcePath for doc path if not set
  if (!options.path && spec.resourcePath) {
    options.path = spec.resourcePath;
  }

  debug('create api %s', spec.resourcePath, spec);

  this.env = new Environment();

  this.spec = spec;
  this.list = [];
  this.options = options;

  this.middleware = {};
  this.models = {};
  this.nicknames = {};
  this.resources = {};
}
897056
def wrap(http_method, url, params)
      params = params.merge(:appid => @appid)
      params[:sig] = Gateway.signature( "#{@appkey}&", Gateway.make_source(http_method.to_s.upcase, url, params) )
      params
    end
527704
def post(url, parameters = {})
      response = connection.post do |req|
        req.url "#{api_endpoint}#{url}"
        req.headers['Content-Type'] = 'application/json'
        req.body = parameters.to_json
      end
      on_complete(response)
      response
    end
506358
def post(self, url, postParameters=None, urlParameters=None):
        
        if not self.access_token:
            raise IOError("No authorized client available.")
        if not self.action_token:
            raise IOError("Need to generate action token.")
        if urlParameters is None:
            urlParameters = {}
        headers = {'Authorization': 'Bearer ' + self.access_token,
                   'Content-Type': 'application/x-www-form-urlencoded'}
        postParameters.update({'T':self.action_token})
        request = requests.post(url + '?' + self.getParameters(urlParameters),
                                data=postParameters, headers=headers)
        if request.status_code != 200:
            return None
        else:
            return toUnicode(request.text)
936326
public void route(HttpMethods meth, String path, API api, Code code) throws Exception {
		String version = "1.0";
		// Get Correct API Class from Mapper
		Class<?> respCls = facade1_0.mapper().getClass(api); 
		if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name());
		// setup Application API HTML ContentTypes for JSON and Route
		String application = applicationJSON(respCls, version);
		route(env,meth,path,code,application,"application/json;version="+version,"*/*");

		// setup Application API HTML ContentTypes for XML and Route
		application = applicationXML(respCls, version);
		route(env,meth,path,code.clone(facade1_0_XML),application,"application/xml;version="+version);
		
		// Add other Supported APIs here as created
	}
270070
def endpoint_parameter(name, description, how_to_pass, required, type, params = {})
      parameters = settings.swagger_current_endpoint_parameters
      check_if_not_duplicate(name, parameters, 'Parameter')
      parameters[name] = Sinatra::SwaggerExposer::Configuration::SwaggerEndpointParameter.new(
        name,
        description,
        how_to_pass,
        required,
        type,
        params,
        settings.swagger_types.types_names)
    end
658520
def request_show(self, id, **kwargs):
        ""
        api_path = "/api/v2/requests/{id}.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
202357
def execute(self, method, path, **kwargs):
        

        url = "{}{}".format(self.host, path)
        kwargs.update(self._client_kwargs)
        response = requests.request(
            method,
            url,
            headers={"Authorization": "Bearer {}".format(self.api_key)},
            **kwargs)
        return response
1062084
@POST
    @Consumes("application/x.json-create-api-key")
    public Response createApiKey(CreateEmoApiKeyRequest request, @QueryParam("key") String key,
                                 @Authenticated Subject subject) {
        if (key != null) {
            request.setCustomRequestParameter("key", key);
        }
        CreateEmoApiKeyResponse response = _uac.createApiKey(subject, request);

        return Response.created(URI.create(response.getId()))
                .entity(response)
                .build();
    }