Search in sources :

Example 6 with HttpPath

use of com.palantir.conjure.spec.HttpPath in project conjure-python by palantir.

the class PythonEndpointDefinition method emit.

@SuppressWarnings({ "CyclomaticComplexity", "MethodLength" })
@Override
default void emit(PythonPoetWriter poetWriter) {
    poetWriter.maintainingIndent(() -> {
        // if auth type is header, insert it as a fake param
        boolean isHeaderType = auth().isPresent() && auth().get().accept(AuthTypeVisitor.IS_HEADER);
        List<PythonEndpointParam> paramsWithHeader = isHeaderType ? ImmutableList.<PythonEndpointParam>builder().add(PythonEndpointParam.builder().paramName("authHeader").pythonParamName("auth_header").myPyType("str").isOptional(false).paramType(ParameterType.header(HeaderParameterType.of(ParameterId.of("Authorization")))).build()).addAll(params()).build() : params();
        poetWriter.writeIndentedLine("def %s(self, %s) -> %s:", pythonMethodName(), Joiner.on(", ").join(paramsWithHeader.stream().sorted(new PythonEndpointParamComparator()).map(param -> {
            String typedParam = String.format("%s: %s", param.pythonParamName(), param.myPyType());
            if (param.isOptional()) {
                return String.format("%s = None", typedParam);
            }
            return typedParam;
        }).collect(Collectors.toList())), myPyReturnType().orElse("None"));
        poetWriter.increaseIndent();
        docs().ifPresent(docs -> {
            poetWriter.writeIndentedLine("\"\"\"");
            poetWriter.writeIndentedLine(docs.get().trim());
            poetWriter.writeIndentedLine("\"\"\"");
        });
        // header
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_headers: Dict[str, Any] = {");
        poetWriter.increaseIndent();
        poetWriter.writeIndentedLine("'Accept': '%s',", isResponseBinary() ? MediaType.APPLICATION_OCTET_STREAM : MediaType.APPLICATION_JSON);
        // body
        Optional<PythonEndpointParam> bodyParam = paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_BODY)).findAny();
        if (bodyParam.isPresent()) {
            poetWriter.writeIndentedLine("'Content-Type': '%s',", isRequestBinary() ? MediaType.APPLICATION_OCTET_STREAM : MediaType.APPLICATION_JSON);
        }
        paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_HEADER)).forEach(param -> {
            poetWriter.writeIndentedLine("'%s': %s,", param.paramType().accept(ParameterTypeVisitor.HEADER).getParamId().get(), param.pythonParamName());
        });
        poetWriter.decreaseIndent();
        poetWriter.writeIndentedLine("}");
        // params
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_params: Dict[str, Any] = {");
        poetWriter.increaseIndent();
        paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_QUERY)).forEach(param -> {
            poetWriter.writeIndentedLine("'%s': %s,", param.paramType().accept(ParameterTypeVisitor.QUERY).getParamId().get(), param.pythonParamName());
        });
        poetWriter.decreaseIndent();
        poetWriter.writeIndentedLine("}");
        // path params
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_path_params: Dict[str, Any] = {");
        poetWriter.increaseIndent();
        // TODO(qchen): no need for param name twice?
        paramsWithHeader.stream().filter(param -> param.paramType().accept(ParameterTypeVisitor.IS_PATH)).forEach(param -> {
            poetWriter.writeIndentedLine("'%s': %s,", param.paramName(), param.pythonParamName());
        });
        poetWriter.decreaseIndent();
        poetWriter.writeIndentedLine("}");
        if (bodyParam.isPresent()) {
            if (!isRequestBinary()) {
                poetWriter.writeLine();
                poetWriter.writeIndentedLine("_json: Any = ConjureEncoder().default(%s)", bodyParam.get().pythonParamName());
            } else {
                poetWriter.writeLine();
                poetWriter.writeIndentedLine("_data: Any = %s", bodyParam.get().pythonParamName());
            }
        } else {
            poetWriter.writeLine();
            poetWriter.writeIndentedLine("_json: Any = None");
        }
        // fix the path, add path params
        poetWriter.writeLine();
        HttpPath fullPath = httpPath();
        String fixedPath = fullPath.toString().replaceAll("\\{(.*):[^}]*}", "{$1}");
        poetWriter.writeIndentedLine("_path = '%s'", fixedPath);
        poetWriter.writeIndentedLine("_path = _path.format(**_path_params)");
        poetWriter.writeLine();
        poetWriter.writeIndentedLine("_response: Response = self._request(");
        poetWriter.increaseIndent();
        poetWriter.writeIndentedLine("'%s',", httpMethod());
        poetWriter.writeIndentedLine("self._uri + _path,");
        poetWriter.writeIndentedLine("params=_params,");
        poetWriter.writeIndentedLine("headers=_headers,");
        if (isResponseBinary()) {
            poetWriter.writeIndentedLine("stream=True,");
        }
        if (!isRequestBinary()) {
            poetWriter.writeIndentedLine("json=_json)");
        } else {
            poetWriter.writeIndentedLine("data=_data)");
        }
        poetWriter.decreaseIndent();
        poetWriter.writeLine();
        if (isResponseBinary()) {
            poetWriter.writeIndentedLine("_raw = _response.raw");
            poetWriter.writeIndentedLine("_raw.decode_content = True");
            poetWriter.writeIndentedLine("return _raw");
        } else if (pythonReturnType().isPresent()) {
            poetWriter.writeIndentedLine("_decoder = ConjureDecoder()");
            if (isOptionalReturnType()) {
                poetWriter.writeIndentedLine("return None if _response.status_code == 204 else _decoder.decode(_response.json(), %s)", pythonReturnType().get());
            } else {
                poetWriter.writeIndentedLine("return _decoder.decode(_response.json(), %s)", pythonReturnType().get());
            }
        } else {
            poetWriter.writeIndentedLine("return");
        }
        poetWriter.decreaseIndent();
    });
}
Also used : HttpMethod(com.palantir.conjure.spec.HttpMethod) AuthType(com.palantir.conjure.spec.AuthType) AuthTypeVisitor(com.palantir.conjure.visitor.AuthTypeVisitor) HttpPath(com.palantir.conjure.spec.HttpPath) Collectors(java.util.stream.Collectors) ParameterTypeVisitor(com.palantir.conjure.visitor.ParameterTypeVisitor) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ParameterType(com.palantir.conjure.spec.ParameterType) List(java.util.List) MediaType(javax.ws.rs.core.MediaType) ImmutableList(com.google.common.collect.ImmutableList) Value(org.immutables.value.Value) Documentation(com.palantir.conjure.spec.Documentation) Optional(java.util.Optional) Comparator(java.util.Comparator) HeaderParameterType(com.palantir.conjure.spec.HeaderParameterType) Joiner(com.google.common.base.Joiner) ParameterId(com.palantir.conjure.spec.ParameterId) HttpPath(com.palantir.conjure.spec.HttpPath)

Aggregations

HttpPath (com.palantir.conjure.spec.HttpPath)6 ImmutableList (com.google.common.collect.ImmutableList)2 ArgumentName (com.palantir.conjure.spec.ArgumentName)2 AuthType (com.palantir.conjure.spec.AuthType)2 Documentation (com.palantir.conjure.spec.Documentation)2 HeaderParameterType (com.palantir.conjure.spec.HeaderParameterType)2 HttpMethod (com.palantir.conjure.spec.HttpMethod)2 ParameterId (com.palantir.conjure.spec.ParameterId)2 ParameterType (com.palantir.conjure.spec.ParameterType)2 Path (com.palantir.util.syntacticpath.Path)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Optional (java.util.Optional)2 Pattern (java.util.regex.Pattern)2 Collectors (java.util.stream.Collectors)2 Joiner (com.google.common.base.Joiner)1 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 ReferenceTypeResolver (com.palantir.conjure.defs.ConjureTypeParserVisitor.ReferenceTypeResolver)1 ConjureDefinitionValidator (com.palantir.conjure.defs.validator.ConjureDefinitionValidator)1