Example #1
0
def generate_curl_example(
    endpoint: str,
    method: str,
    api_url: str,
    auth_email: str = DEFAULT_AUTH_EMAIL,
    auth_api_key: str = DEFAULT_AUTH_API_KEY,
    exclude: Optional[List[str]] = None,
    include: Optional[List[str]] = None,
) -> List[str]:

    lines = ["```curl"]
    operation = endpoint + ":" + method.lower()
    operation_entry = openapi_spec.openapi()["paths"][endpoint][method.lower()]
    global_security = openapi_spec.openapi()["security"]

    operation_params = operation_entry.get("parameters", [])
    operation_request_body = operation_entry.get("requestBody", None)
    operation_security = operation_entry.get("security", None)

    if settings.RUNNING_OPENAPI_CURL_TEST:  # nocoverage
        from zerver.openapi.curl_param_value_generators import patch_openapi_example_values

        operation_params, operation_request_body = patch_openapi_example_values(
            operation, operation_params, operation_request_body)

    format_dict = {}
    for param in operation_params:
        if param["in"] != "path":
            continue
        example_value = get_openapi_param_example_value_as_string(
            endpoint, method, param)
        format_dict[param["name"]] = example_value
    example_endpoint = endpoint.format_map(format_dict)

    curl_first_line_parts = [
        "curl", *curl_method_arguments(example_endpoint, method, api_url)
    ]
    lines.append(" ".join(map(shlex.quote, curl_first_line_parts)))

    insecure_operations = ["/dev_fetch_api_key:post", "/fetch_api_key:post"]
    if operation_security is None:
        if global_security == [{"basicAuth": []}]:
            authentication_required = True
        else:
            raise AssertionError(
                "Unhandled global securityScheme." +
                " Please update the code to handle this scheme.")
    elif operation_security == []:
        if operation in insecure_operations:
            authentication_required = False
        else:
            raise AssertionError(
                "Unknown operation without a securityScheme. " +
                "Please update insecure_operations.")
    else:
        raise AssertionError(
            "Unhandled securityScheme. Please update the code to handle this scheme."
        )

    if authentication_required:
        lines.append("    -u " + shlex.quote(f"{auth_email}:{auth_api_key}"))

    for param in operation_params:
        if param["in"] == "path":
            continue
        param_name = param["name"]

        if include is not None and param_name not in include:
            continue

        if exclude is not None and param_name in exclude:
            continue

        example_value = get_openapi_param_example_value_as_string(
            endpoint, method, param, curl_argument=True)
        lines.append(example_value)

    if "requestBody" in operation_entry:
        properties = operation_entry["requestBody"]["content"][
            "multipart/form-data"]["schema"]["properties"]
        for key, property in properties.items():
            lines.append(
                "    -F " +
                shlex.quote("{}=@{}".format(key, property["example"])))

    for i in range(1, len(lines) - 1):
        lines[i] = lines[i] + " \\"

    lines.append("```")

    return lines
Example #2
0
def generate_curl_example(endpoint: str,
                          method: str,
                          api_url: str,
                          auth_email: str = DEFAULT_AUTH_EMAIL,
                          auth_api_key: str = DEFAULT_AUTH_API_KEY,
                          exclude: Optional[List[str]] = None,
                          include: Optional[List[str]] = None) -> List[str]:
    if exclude is not None and include is not None:
        raise AssertionError(
            "exclude and include cannot be set at the same time.")

    lines = ["```curl"]
    openapi_entry = openapi_spec.spec()['paths'][endpoint][method.lower()]
    openapi_params = openapi_entry.get("parameters", [])
    openapi_request_body = openapi_entry.get("requestBody", None)

    if settings.RUNNING_OPENAPI_CURL_TEST:  # nocoverage
        from zerver.openapi.curl_param_value_generators import patch_openapi_example_values
        openapi_params, openapi_request_body = patch_openapi_example_values(
            endpoint + ":" + method.lower(), openapi_params,
            openapi_request_body)

    format_dict = {}
    for param in openapi_params:
        if param["in"] != "path":
            continue
        example_value = get_openapi_param_example_value_as_string(
            endpoint, method, param)
        format_dict[param["name"]] = example_value
    example_endpoint = endpoint.format_map(format_dict)

    curl_first_line_parts = ["curl"] + curl_method_arguments(
        example_endpoint, method, api_url)
    lines.append(" ".join(curl_first_line_parts))

    authentication_required = openapi_entry.get("security", False)
    if authentication_required:
        lines.append("    -u %s:%s" % (auth_email, auth_api_key))

    for param in openapi_params:
        if param["in"] == "path":
            continue
        param_name = param["name"]

        if include is not None and param_name not in include:
            continue

        if exclude is not None and param_name in exclude:
            continue

        example_value = get_openapi_param_example_value_as_string(
            endpoint, method, param, curl_argument=True)
        lines.append(example_value)

    if "requestBody" in openapi_entry:
        properties = openapi_entry["requestBody"]["content"][
            "multipart/form-data"]["schema"]["properties"]
        for key, property in properties.items():
            lines.append('    -F "{}=@{}"'.format(key, property["example"]))

    for i in range(1, len(lines) - 1):
        lines[i] = lines[i] + " \\"

    lines.append("```")

    return lines