The specification of an API endpoint
@param {Object} spec - Swagger/OpenAPI specification of the endpoint
@param {string} resourcePath - path of the endpoint
@param {string} method - HTTP method of the endpoint
@constructor
161078
function Endpoint(spec, resourcePath, method) {
  this.method = method;
  this.resourcePath = resourcePath || '/';
  this.spec = spec;
}
301600
def call_on_each_endpoint(self, callback):
        

        if 'paths' not in self.swagger_dict:
            return

        for path, d in list(self.swagger_dict['paths'].items()):
            for method, op_spec in list(d.items()):
                data = EndpointData(path, method)

                # Which server method handles this endpoint?
                if 'x-bind-server' not in op_spec:
                    if 'x-no-bind-server' in op_spec:
                        # That route should not be auto-generated
                        log.info("Skipping generation of %s %s" % (method, path))
                        continue
                    else:
                        raise Exception("Swagger api defines no x-bind-server for %s %s" % (method, path))
                data.handler_server = op_spec['x-bind-server']

                # Make sure that endpoint only produces 'application/json'
                if 'produces' not in op_spec:
                    raise Exception("Swagger api has no 'produces' section for %s %s" % (method, path))
                if len(op_spec['produces']) != 1:
                    raise Exception("Expecting only one type under 'produces' for %s %s" % (method, path))
                if op_spec['produces'][0] == 'application/json':
                    data.produces_json = True
                elif op_spec['produces'][0] == 'text/html':
                    data.produces_html = True
                else:
                    raise Exception("Only 'application/json' or 'text/html' are supported. See %s %s" % (method, path))

                # Which client method handles this endpoint?
                if 'x-bind-client' in op_spec:
                    data.handler_client = op_spec['x-bind-client']

                # Should we decorate the server handler?
                if 'x-decorate-server' in op_spec:
                    data.decorate_server = op_spec['x-decorate-server']

                # Should we manipulate the requests parameters?
                if 'x-decorate-request' in op_spec:
                    data.decorate_request = op_spec['x-decorate-request']

                # Generate a bravado-core operation object
                data.operation = Operation.from_spec(self.spec, path, method, op_spec)

                # Figure out how parameters are passed: one json in body? one or
                # more values in query?
                if 'parameters' in op_spec:
                    params = op_spec['parameters']
                    for p in params:
                        if p['in'] == 'body':
                            data.param_in_body = True
                        if p['in'] == 'query':
                            data.param_in_query = True
                        if p['in'] == 'path':
                            data.param_in_path = True

                    if data.param_in_path:
                        # Substitute {...} with <...> in path, to make a Flask friendly path
                        data.path = data.path.replace('{', '<').replace('}', '>')

                    if data.param_in_body and data.param_in_query:
                        raise Exception("Cannot support params in both body and param (%s %s)" % (method, path))

                else:
                    data.no_params = True

                callback(data)
946381
function RegisterEndpoint(method, path, _desc, _callback) {
    if(!_.isString(path)) {
      throw new Error("Invalid path for " + path + " (" + method + ")");
    }
    var desc = (typeof _desc === 'string' ? _desc : null),
      callback = (typeof _desc === 'function' ? _desc : (typeof _callback === 'function' ? _callback : null));
    var name = method + ":" + path.replace(/\//g, '.');
    if(name.charAt(0) === '.') name = name.substr(1);
    if(typeof this.__endpoints[name] !== 'undefined') {
      throw new Error("Previously registered endpoint " + path + " in namespace "+ this.__namespace + "(" + method + ")");
    }
    ENDPOINT_COUNTER++;
    var endpointChain = new RouteChain(name, path, method, SERVER);
    endpointChain.__namespace = this.__namespace;
    if(desc) endpointChain['desc'] = desc;
    if(callback) endpointChain.then(callback);
    this.__endpoints[name] = endpointChain;
    /* We allow route chaining of utility functions. After a route endpoint has been created,
     * we can attach additional data / utility functions to it. */
    return endpointChain;
  }
1129965
async function buildRequest(method, url, params, options) {
  let param = {};
  let config = {};
  if (noneBodyMethod.indexOf(method) >= 0) {
    param = { params: { ...params }, ...reqConfig, ...options };
  } else {
    param = JSON.stringify(params);
    config = {
      ...reqConfig,
      headers: {
        'Content-Type': 'application/json',
        ...csrfConfig,
      },
    };
    config = Object.assign({}, config, options);
  }
  return axios[method](url, param, config);
}
1016622
function checkMethods(spec) {
  assert(spec.method, 'missing route methods');

  if (typeof spec.method === 'string') {
    spec.method = spec.method.split(' ');
  }

  if (!Array.isArray(spec.method)) {
    throw new TypeError('route methods must be an array or string');
  }

  if (spec.method.length === 0) {
    throw new Error('missing route method');
  }

  spec.method.forEach((method, i) => {
    assert(typeof method === 'string', 'route method must be a string');
    spec.method[i] = method.toLowerCase();
  });
}
884415
function Framework(spec, options) {
  if (!(this instanceof Framework)) {
    return new Framework(spec, options);
  }

  debug('create framework', spec, options);

  spec = lodash.cloneDeep(spec || {});
  options = lodash.cloneDeep(options || {});

  spec = lodash.defaults(spec, {
    swaggerVersion: '1.2',
    apis: [],
  });

  options = lodash.defaults(options,
    lodash.pick(spec, 'basePath')
  );
  delete spec.basePath;

  schema.validateThrow('ResourceListing', spec);
  schema.validateThrow(frameworkOptions, options);

  if (spec.swaggerVersion !== '1.2') {
    throw new Error('swaggerVersion not supported: ' + spec.swaggerVersion);
  }

  this.spec = spec;
  this.options = options;
  this.docs = new Docs(this);
  this.router = new Router(this);

  this.apis = {};
  this.middleware = {};
}
23447
def save_swagger_spec(self, filepath=None):
        
        if filepath is True or filepath is None:
            filepath = self.file_spec.format(server=self.server)

        json.dump(self.origin_spec, open(filepath, 'w+'), indent=3)
1128970
def _handler_swagger_ui(self, request, spec, version):
        
        version = version or self._version_ui
        if self._spec_url:
            spec_url = self._spec_url
        else:
            spec_url = request.url.with_path(self['swagger:spec'].url())
            proto = request.headers.get(hdrs.X_FORWARDED_PROTO)
            if proto:
                spec_url = spec_url.with_scheme(proto)
            if isinstance(spec, str):
                spec_url = spec_url.with_query(spec=spec)
            elif len(self._swagger_data) == 1:
                for basePath in self._swagger_data:
                    spec_url = spec_url.with_query(spec=basePath)
            else:
                spec_url = spec_url.with_query(spec='/')
            spec_url = spec_url.human_repr()
        return web.Response(
            text=ui.rend_template(spec_url,
                                  prefix=self._swagger_ui,
                                  version=version),
            content_type='text/html')
1316447
function $httpBackend(method, url, data, callback, headers) {
    var xhr = new MockXhr(),
        expectation = expectations[0],
        wasExpected = false;

    function prettyPrint(data) {
      return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
          ? data
          : angular.toJson(data);
    }

    if (expectation && expectation.match(method, url)) {
      if (!expectation.matchData(data))
        throw Error('Expected ' + expectation + ' with different data\n' +
            'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT:      ' + data);

      if (!expectation.matchHeaders(headers))
        throw Error('Expected ' + expectation + ' with different headers\n' +
            'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT:      ' +
            prettyPrint(headers));

      expectations.shift();

      if (expectation.response) {
        responses.push(function() {
          var response = expectation.response(method, url, data, headers);
          xhr.$$respHeaders = response[2];
          callback(response[0], response[1], xhr.getAllResponseHeaders());
        });
        return;
      }
      wasExpected = true;
    }

    var i = -1, definition;
    while ((definition = definitions[++i])) {
      if (definition.match(method, url, data, headers || {})) {
        if (definition.response) {
          // if $browser specified, we do auto flush all requests
          ($browser ? $browser.defer : responsesPush)(function() {
            var response = definition.response(method, url, data, headers);
            xhr.$$respHeaders = response[2];
            callback(response[0], response[1], xhr.getAllResponseHeaders());
          });
        } else if (definition.passThrough) {
          $delegate(method, url, data, callback, headers);
        } else throw Error('No response defined !');
        return;
      }
    }
    throw wasExpected ?
        Error('No response defined !') :
        Error('Unexpected request: ' + method + ' ' + url + '\n' +
              (expectation ? 'Expected ' + expectation : 'No more request expected'));
  }
42098
function (method, path, parameters) {
    if (!this.parent) {
      return;
    }
    var fullPath = normalizePath(path, this.path);
    this.parent.exportHandler(method, fullPath, parameters);
  }
140792
public void route(HttpMethods meth, String path, API api, GwCode code) throws Exception {
		String version = "1.0";
		// Get Correct API Class from Mapper
		Class<?> respCls = facade.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(facade_1_0_XML,false),application,"text/xml;version="+version);
		
		// Add other Supported APIs here as created
	}
1301920
function ExpectedRequest(method, path, data) {
    this.method = method;
    this.path = path;
    this.data = data;
    this.response = null;
    this.checks = [];
}
860481
function RouteRule_parseRequest(method, url) {

        var matches,
            route,
            key,
            result = [],
            escape = [],
            params = {},
            current;
        //match pathname
        matches = this.match(this.pattern, this.trim(url.pathname, '/'));


        if (!matches.length || !this.checkMethod(method)) {
            return false;
        }
        params = url.query;


        for (key in params) {
            current = this.find(matches, key);
            if (!current || current.value === '') {
                matches.push({
                    key: key,
                    value: params[key]
                });
            }
        }

        matches.forEach(function (item) {
            var current = this.find(this.routeParams, item.key);
            if (current) {
                escape.push({
                    key: '<' + current.key + '>',
                    value: item.value
                });
                delete params[item.name];
            } else if (this.find(this.paramRules, item.key)) {
                params[item.key] = item.value;
            }
        }.bind(this));


        if (this.routeParams.length) {
            route = this.escape(this.route, escape);
        } else {
            route = this.route;
        }

        result.push(route);
        result.push(params);

        return result;
    }
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);
            };
        });
    });
}
75071
private void parseControllerMethod(JaxrsApplicationParser.Result result, JaxrsApplicationParser.ResourceContext context, Class<?> controllerClass, Method method) {
        final RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
        if (requestMapping != null) {

            // subContext
            context = context.subPath(requestMapping.path().length == 0 ? "" : requestMapping.path()[0]);
            final Map<String, Type> pathParamTypes = new LinkedHashMap<>();
            for (Parameter parameter : method.getParameters()) {
                final PathVariable pathVariableAnnotation = parameter.getAnnotation(PathVariable.class);
                if (pathVariableAnnotation != null) {
                    pathParamTypes.put(pathVariableAnnotation.value(), parameter.getParameterizedType());
                }
            }
            context = context.subPathParamTypes(pathParamTypes);
            final RequestMethod httpMethod = requestMapping.method().length == 0 ? RequestMethod.GET : requestMapping.method()[0];

            // path parameters
            final PathTemplate pathTemplate = PathTemplate.parse(context.path);
            final Map<String, Type> contextPathParamTypes = context.pathParamTypes;
            final List<MethodParameterModel> pathParams = pathTemplate.getParts().stream()
                    .filter(PathTemplate.Parameter.class::isInstance)
                    .map(PathTemplate.Parameter.class::cast)
                    .map(parameter -> {
                        final Type type = contextPathParamTypes.get(parameter.getOriginalName());
                        final Type paramType = type != null ? type : String.class;
                        foundType(result, paramType, controllerClass, method.getName());
                        return new MethodParameterModel(parameter.getValidName(), paramType);
                    })
                    .collect(Collectors.toList());

            // query parameters
            final List<RestQueryParam> queryParams = new ArrayList<>();
            for (Parameter param : method.getParameters()) {
                final RequestParam requestParamAnnotation = param.getAnnotation(RequestParam.class);
                if (requestParamAnnotation != null) {
                    queryParams.add(new RestQueryParam.Single(new MethodParameterModel(requestParamAnnotation.value(), param.getParameterizedType())));
                    foundType(result, param.getParameterizedType(), controllerClass, method.getName());
                }
            }

            // entity parameter
            final MethodParameterModel entityParameter = getEntityParameter(method);
            if (entityParameter != null) {
                foundType(result, entityParameter.getType(), controllerClass, method.getName());
            }

            // return Type
            final Class<?> returnType = method.getReturnType();
            final Type genericReturnType = method.getGenericReturnType();
            final Type modelReturnType;
            if (genericReturnType instanceof ParameterizedType && returnType == ResponseEntity.class) {
                final ParameterizedType parameterizedReturnType = (ParameterizedType) genericReturnType;
                modelReturnType = parameterizedReturnType.getActualTypeArguments()[0];
                foundType(result, modelReturnType, controllerClass, method.getName());
            } else {
                modelReturnType = genericReturnType;
                foundType(result, modelReturnType, controllerClass, method.getName());
            }

            model.getMethods().add(new RestMethodModel(controllerClass, method.getName(), modelReturnType,
                    controllerClass, httpMethod.name(), context.path, pathParams, queryParams, entityParameter, null));
        }
    }
893212
def api_declaration(
            cls, request,
            api_path: (Ptypes.path,
                       String('The path for the info on the resource.'))) -> [
            (200, 'Ok', ApiDeclarationModel),
            (404, 'Not a valid resource.')]:
        '''
        '''
        if api_path in cls.__cache:
            Respond(200, cls.__cache[api_path])
        # Select the resources belonging to this API
        resources = tuple(filter(lambda ep: ep.api.path == api_path, Resource))
        if not resources:
            Respond(404)
        apis = [r.get_swagger_fragment() for r in resources if not r.private]
        cls.__cache[api_path] = {
            'apiVersion': cls.api.version,
            'swaggerVersion': cls.api.swagger_version,
            'basePath': request.url_root[:-1],  # Remove trailing slash
            'resourcePath': '/{}'.format(api_path),
            'apis': apis,
            'models': cls._extract_models(apis),
            'consumes': ['application/json'],
            'produces': ['application/json']
        }
        Respond(200, cls.__cache[api_path])
150164
function (method, result) {

      // result should not be undefined
      if (result === undefined) {
        console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)')
        result = ''
      }

      var rpcMessage = {
        jsonrpc: '2.0',
        result: result,
        id: id
      }

      callback(rpcMessage)
      responseHasBeenSent = true

    }