Serves the fully-dereferenced Swagger API in JSON format.
514844
function serveDereferencedSwaggerFile (req, res, next) {
    if (req.method === "GET" || req.method === "HEAD") {
      let configPath = getConfiguredPath(options.apiPath);
      configPath = util.normalizePath(configPath, router);
      let reqPath = util.normalizePath(req.path, router);

      if (reqPath === configPath) {
        if (context.api) {
          util.debug("%s %s => Sending the Swagger API as JSON", req.method, req.path);
          res.json(context.api);
        }
        else {
          util.warn("WARNING! The Swagger API is empty. Sending an HTTP 500 response to %s %s", req.method, req.path);
          res.status(500).json({});
        }
        return;
      }
    }

    next();
  }
595999
def put_json(self, url, data, cls=None, **kwargs):
        
        kwargs['data'] = to_json(data, cls=cls)
        kwargs['headers'] = self.default_headers
        return self.put(url, **kwargs).json()
1307226
function handler(req, res) {

        var path = cog.getConfig('options.api_data');
        var urlRegex = cog.getConfig('options.api_url_regex');
        var url = req.url.replace(/^\//, '').replace(/\/$/, '');

        console.log(req.method + ' ' + req.url);

        // Find the JSON-data file and serve it, if URL points to the API.
        if (path && urlRegex && urlRegex.test(url)) {
            var file = path + '/' + url + '.json';
            if (grunt.file.exists(file)) {
                res.end(grunt.file.read(file));
                return;
            }
        }

        if (req.method == 'POST') {
            // TODO: This needs fixing, since it throws an error.
            res.end('{"message": "OK"}');
        }

    }
1066075
def _single_resource_json_response(resource, depth=0):
    
    links = resource.links()
    response = jsonify(**resource.as_dict(depth))
    response.headers['Link'] = ''
    for link in links:
        response.headers['Link'] += '<{}>; rel="{}",'.format(
            link['uri'], link['rel'])
    response.headers['Link'] = response.headers['Link'][:-1]
    return response
1153972
def get_swagger(self, request):
        
        api_base = self.parent
        paths, definitions = self.parse_operations()
        codecs = getattr(self.cenancestor, 'registered_codecs', CODECS)  # type: dict
        return dict_filter({
            'swagger': '2.0',
            'info': {
                'title': self.title,
                'version': str(getattr(api_base, 'version', 0))
            },
            'host': self.host or request.host,
            'schemes': list(self.schemes) or None,
            'basePath': str(self.base_path),
            'consumes': list(codecs.keys()),
            'produces': list(codecs.keys()),
            'paths': paths,
            'definitions': definitions,
            'securityDefinitions': self.security_definitions(),
        })
378323
def _from_json(cls, response_raw, wrapper=None):
        

        json = response_raw.body_bytes.decode()
        obj = converter.json_to_class(dict, json)
        value = converter.deserialize(
            cls,
            cls._unwrap_response_single(obj, wrapper)
        )

        return client.BunqResponse(value, response_raw.headers)
890438
def render_json(json, options = {})
      # Setup data from options
      self.status       = options[:status] if options[:status]
      self.content_type = options[:content_type] if options[:content_type]
      options = options.slice(*RENDERING_OPTIONS)
      # Don't convert raw strings to JSON.
      json = encode_to_json(json) unless json.respond_to?(:to_str)
      # Encode the object to json.
      self.status        ||= :ok
      self.content_type  ||= Mime::JSON
      self.response_body   = json
      headers['Content-Length'] = Rack::Utils.bytesize(json).to_s
    end
330441
def read_spec(path, http_client=None):
    
    with open(path, 'r') as f:
        spec_dict = json.loads(f.read())

    return SwaggerClient.from_spec(spec_dict, http_client=http_client, config=SPEC_CONFIG)
1032081
function returnJSON(finalResp, res) {
    if (JSONformat === 'JSON') {
      res.set('Content-Type', `application/json; charset=${encoding}`);
      res.json(finalResp);
    } else {
      res.set('Content-Type', `text/plain; charset=${encoding}`);
      res.send(JSON.stringify(finalResp));
    }
  }
14033
function(apiId, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.putRestApi({
                    restApiId: apiId,
                    body: data,
                    mode: 'overwrite'
                }).promise());
            });
        });
    }
628432
def requires_application_json(f):
    """"""

    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        from flask import request
        if request.get_json(silent=True) is None:
            er = ErrorResponse(description='Improper Content-Type header. Expecting "application/json"')
            return to_json_response(er), HTTPStatus.BAD_REQUEST
        else:
            return f(*args, **kwargs)

    return wrapped
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)
536553
def _responsify(api_spec, error, status):
    """"""
    result_json = api_spec.model_to_json(error)
    r = jsonify(result_json)
    r.status_code = status
    return r
1119052
def returns_json(func):
    
    def decorator(*args, **kwargs):
        instance = args[0]
        request = getattr(instance, 'request', None)
        request.response.setHeader("Content-Type", "application/json")
        result = func(*args, **kwargs)
        return json.dumps(result)
    return decorator
493086
def to_json(template, clean_up=False):
    

    data = load_yaml(template)

    if clean_up:
        data = clean(data)

    return dump_json(data)
437914
def as_json(context):
    """"""
    info = {
        'info': cgi.escape(pprint.pformat(context.context)),
    }
    return Response(content_type='application/json', body=json.dumps(info))
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