Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

[unused] adds parameter modules, response packages, and response header modules #47

Merged
merged 23 commits into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2bd20f8
Adds parameter template and code to write it
spacether Oct 18, 2022
49ae219
Writes module for each parameter
spacether Oct 18, 2022
157c5c9
Removes prependFormOrBodyParameters
spacether Oct 18, 2022
e84a2ca
Sample regenrated
spacether Oct 18, 2022
aee4b2a
Samples regenerated
spacether Oct 18, 2022
dd53016
Fixes readme example
spacether Oct 18, 2022
7773832
simplifies setting items and additional_properties var names
spacether Oct 19, 2022
421b420
Regenerates sample with fixed schema names
spacether Oct 19, 2022
16c9499
Samples regenerated
spacether Oct 19, 2022
861ab18
Fixes java docstirng typo
spacether Oct 19, 2022
37afbc6
Fixes JavaModelTest tests
spacether Oct 19, 2022
5a11857
Fixes tests in JavaModelEnumTest
spacether Oct 19, 2022
43afdfa
FIxes tests in JavaClientCodegenTest
spacether Oct 19, 2022
f29edc1
FIxes tests in DefaultGeneratorTest
spacether Oct 19, 2022
2e6e8e5
FIxes tests in DefaultCodegenTest
spacether Oct 19, 2022
a677d8e
Adds HeaderParameterWithoutName to api_client
spacether Oct 19, 2022
a7e5301
Sample regenerated, responses are now modules
spacether Oct 19, 2022
19fcbd8
Moves request body schemas to the root indentation level of the respo…
spacether Oct 19, 2022
ee7dc54
Adds code to generate response header modules
spacether Oct 19, 2022
8ad360b
Updates fromParameter
spacether Oct 19, 2022
9cafb58
Sample updated, fixed bug where form param was not seen as body
spacether Oct 19, 2022
30d08ce
Samples regenerated
spacether Oct 20, 2022
efde0db
Fixes java tests
spacether Oct 20, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,6 @@ apiTemplateFiles are for API outputs only (controllers/handlers).
protected Map<String, String> specialCharReplacements = new LinkedHashMap<>();
// When a model is an alias for a simple type
protected Map<String, String> typeAliases = null;
protected Boolean prependFormOrBodyParameters = false;
// The extension of the generated documentation files (defaults to markdown .md)
protected String docExtension;
protected String ignoreFilePathOverride;
Expand Down Expand Up @@ -338,11 +337,6 @@ public void processOpts() {
.get(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG).toString()));
}

if (additionalProperties.containsKey(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS)) {
this.setPrependFormOrBodyParameters(Boolean.valueOf(additionalProperties
.get(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS).toString()));
}

if (additionalProperties.containsKey(CodegenConstants.ENSURE_UNIQUE_PARAMS)) {
this.setEnsureUniqueParams(Boolean.valueOf(additionalProperties
.get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString()));
Expand Down Expand Up @@ -1339,15 +1333,6 @@ public Boolean getSortModelPropertiesByRequiredFlag() {
public void setSortModelPropertiesByRequiredFlag(Boolean sortModelPropertiesByRequiredFlag) {
this.sortModelPropertiesByRequiredFlag = sortModelPropertiesByRequiredFlag;
}

public Boolean getPrependFormOrBodyParameters() {
return prependFormOrBodyParameters;
}

public void setPrependFormOrBodyParameters(Boolean prependFormOrBodyParameters) {
this.prependFormOrBodyParameters = prependFormOrBodyParameters;
}

public Boolean getEnsureUniqueParams() {
return ensureUniqueParams;
}
Expand Down Expand Up @@ -2934,7 +2919,7 @@ public CodegenModel fromModel(String name, Schema schema) {
m.setFormat(schema.getFormat());
m.setComposedSchemas(getComposedSchemas(schema));
if (ModelUtils.isArraySchema(schema)) {
CodegenProperty arrayProperty = fromProperty(name, schema, false);
CodegenProperty arrayProperty = fromProperty("items", schema, false);
m.setItems(arrayProperty.items);
m.arrayModelType = arrayProperty.complexType;
addParentContainer(m, name, schema);
Expand Down Expand Up @@ -3849,17 +3834,9 @@ public CodegenProperty fromProperty(String name, Schema p, boolean required, boo
property.xmlName = p.getXml().getName();
}

// handle inner property
String itemName = null;
if (p.getExtensions() != null && p.getExtensions().get("x-item-name") != null) {
itemName = p.getExtensions().get("x-item-name").toString();
}
if (itemName == null) {
itemName = property.name;
}
ArraySchema arraySchema = (ArraySchema) p;
Schema innerSchema = unaliasSchema(getSchemaItems(arraySchema));
CodegenProperty cp = fromProperty(itemName, innerSchema, false);
CodegenProperty cp = fromProperty("items", innerSchema, false);
updatePropertyForArray(property, cp);
} else if (ModelUtils.isTypeObjectSchema(p)) {
updatePropertyForObject(property, p);
Expand Down Expand Up @@ -4265,7 +4242,7 @@ public CodegenOperation fromOperation(String path,
for (Entry<String, Header> entry : headers.entrySet()) {
String headerName = entry.getKey();
Header header = ModelUtils.getReferencedHeader(this.openAPI, entry.getValue());
CodegenParameter responseHeader = headerToCodegenParameter(header, headerName, r.imports, String.format(Locale.ROOT, "%sResponseParameter", r.code));
CodegenParameter responseHeader = headerToCodegenParameter(header, headerName, r.imports, "");
responseHeaders.add(responseHeader);
}
r.setResponseHeaders(responseHeaders);
Expand Down Expand Up @@ -4354,11 +4331,8 @@ public CodegenOperation fromOperation(String path,
setParameterEncodingValues(cp, requestBody.getContent().get(contentType));
postProcessParameter(cp);
}
// add form parameters to the beginning of all parameter list
if (prependFormOrBodyParameters) {
for (CodegenParameter cp : formParams) {
allParams.add(cp.copy());
}
if (formParams.size() == 1) {
bodyParam = formParams.get(0);
}
} else {
// process body parameter
Expand All @@ -4374,10 +4348,6 @@ public CodegenOperation fromOperation(String path,

bodyParams.add(bodyParam);

if (prependFormOrBodyParameters) {
allParams.add(bodyParam);
}

// add example
if (schemas != null && !isSkipOperationExample()) {
op.requestBodyExamples = new ExampleGenerator(schemas, this.openAPI).generate(null, new ArrayList<>(getConsumesInfo(this.openAPI, operation)), bodyParam.baseType);
Expand All @@ -4386,20 +4356,14 @@ public CodegenOperation fromOperation(String path,
}

if (parameters != null) {
Integer i = 0;
for (Parameter param : parameters) {
param = ModelUtils.getReferencedParameter(this.openAPI, param);

CodegenParameter p = fromParameter(param, imports);
p.setContent(getContent(param.getContent(), imports, param.getName()));

// ensure unique params
if (ensureUniqueParams) {
while (!isParameterNameUnique(p, allParams)) {
p.paramName = generateNextName(p.paramName);
}
}

CodegenParameter p = fromParameter(param, imports, i.toString());
p.setContent(getContent(param.getContent(), imports, "schema"));
allParams.add(p);
i++;

if (param instanceof QueryParameter || "query".equalsIgnoreCase(param.getIn())) {
queryParams.add(p.copy());
Expand All @@ -4416,27 +4380,6 @@ public CodegenOperation fromOperation(String path,
}
}

// add form/body parameter (if any) to the end of all parameter list
if (!prependFormOrBodyParameters) {
for (CodegenParameter cp : formParams) {
if (ensureUniqueParams) {
while (!isParameterNameUnique(cp, allParams)) {
cp.paramName = generateNextName(cp.paramName);
}
}
allParams.add(cp.copy());
}

for (CodegenParameter cp : bodyParams) {
if (ensureUniqueParams) {
while (!isParameterNameUnique(cp, allParams)) {
cp.paramName = generateNextName(cp.paramName);
}
}
allParams.add(cp.copy());
}
}

// create optional, required parameters
for (CodegenParameter cp : allParams) {
if (cp.required) { //required parameters
Expand All @@ -4446,6 +4389,14 @@ public CodegenOperation fromOperation(String path,
op.hasOptionalParams = true;
}
}
if (bodyParam != null) {
if (bodyParam.required) {
requiredParams.add(bodyParam.copy());
} else {
optionalParams.add(bodyParam.copy());
op.hasOptionalParams = true;
}
}

// add imports to operation import tag
for (String i : imports) {
Expand Down Expand Up @@ -4817,7 +4768,7 @@ protected void updateParameterForString(CodegenParameter codegenParameter, Schem
* @param imports set of imports for library/package/module
* @return Codegen Parameter object
*/
public CodegenParameter fromParameter(Parameter parameter, Set<String> imports) {
public CodegenParameter fromParameter(Parameter parameter, Set<String> imports, String priorJsonPathFragment) {
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);

codegenParameter.baseName = parameter.getName();
Expand Down Expand Up @@ -4851,9 +4802,9 @@ public CodegenParameter fromParameter(Parameter parameter, Set<String> imports)
parameterModelName = getParameterDataType(parameter, parameterSchema);
CodegenProperty prop;
if (getUseInlineModelResolver()) {
prop = fromProperty(parameter.getName(), getReferencedSchemaWhenNotEnum(parameterSchema), false);
prop = fromProperty("schema", getReferencedSchemaWhenNotEnum(parameterSchema), false);
} else {
prop = fromProperty(parameter.getName(), parameterSchema, false);
prop = fromProperty("schema", parameterSchema, false);
}
codegenParameter.setSchema(prop);
if (addSchemaImportsFromV3SpecLocations) {
Expand Down Expand Up @@ -5042,7 +4993,7 @@ public CodegenParameter fromParameter(Parameter parameter, Set<String> imports)
if ("multi".equals(collectionFormat)) {
codegenParameter.isCollectionFormatMulti = true;
}
codegenParameter.paramName = toParamName(parameter.getName());
codegenParameter.paramName = toParamName(priorJsonPathFragment);
if (!addSchemaImportsFromV3SpecLocations) {
// import
if (codegenProperty.complexType != null) {
Expand Down Expand Up @@ -7111,7 +7062,7 @@ private CodegenParameter headerToCodegenParameter(Header header, String headerNa
headerParam.setExample(header.getExample());
headerParam.setContent(header.getContent());
headerParam.setExtensions(header.getExtensions());
CodegenParameter param = fromParameter(headerParam, imports);
CodegenParameter param = fromParameter(headerParam, imports, headerName);
param.setContent(getContent(headerParam.getContent(), imports, mediaTypeSchemaSuffix));
return param;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@

import static org.openapitools.codegen.utils.OnceLogger.once;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.escape;
import static org.openapitools.codegen.utils.StringUtils.underscore;

public class PythonClientCodegen extends AbstractPythonCodegen {
Expand Down Expand Up @@ -113,7 +114,10 @@ public PythonClientCodegen() {
importBaseType = false;
addSchemaImportsFromV3SpecLocations = true;
sortModelPropertiesByRequiredFlag = Boolean.TRUE;
sortParamsByRequiredFlag = Boolean.TRUE;
// this must be false for parameter numbers to stay the same as the ones in the spec
// if another schema $refs a schema in a parameter, the json path
// and generated module must have the same parameter index as the spec
sortParamsByRequiredFlag = Boolean.FALSE;
addSuffixToDuplicateOperationNicknames = false;

modifyFeatureSet(features -> features
Expand Down Expand Up @@ -588,9 +592,23 @@ protected void generateEndpoints(OperationsMap objs) {
outputFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod, "request_body.py"));
pathsFiles.add(Arrays.asList(paramMap, "endpoint_request_body.handlebars", outputFilename));
}
// paths.some_path.post.parameter_0.py
Integer i = 0;
for (CodegenParameter cp: co.allParams) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("parameter", cp);
// TODO consolidate imports into body param only
paramMap.put("imports", co.imports);
paramMap.put("packageName", packageName);
outputFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod, toParamName(i.toString())+".py"));
pathsFiles.add(Arrays.asList(paramMap, "endpoint_parameter.handlebars", outputFilename));
i++;
}

for (CodegenResponse response: co.responses) {
// paths.some_path.post.response_for_200.py (file per response)
// paths.some_path.post.response_for_200.__init__.py (file per response)
// response is a package because responses have Headers which can be refed
// so each inline header should be a module in the response package
Map<String, Object> responseMap = new HashMap<>();
responseMap.put("response", response);
responseMap.put("packageName", packageName);
Expand All @@ -600,8 +618,17 @@ protected void generateEndpoints(OperationsMap objs) {
} else {
responseModuleName += response.code;
}
String responseFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod, responseModuleName+ ".py"));
String responseFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod, responseModuleName, "__init__.py"));
pathsFiles.add(Arrays.asList(responseMap, "endpoint_response.handlebars", responseFilename));
for (CodegenParameter header: response.getResponseHeaders()) {
Map<String, Object> headerMap = new HashMap<>();
headerMap.put("parameter", header);
// TODO consolidate imports into header param only
headerMap.put("imports", co.imports);
headerMap.put("packageName", packageName);
String headerFilename = packageFilename(Arrays.asList("paths", pathModuleName, co.httpMethod, responseModuleName, toParamName(header.baseName) + ".py"));
pathsFiles.add(Arrays.asList(headerMap, "endpoint_response_header.handlebars", headerFilename));
}
}
/*
This stub file exists to allow pycharm to read and use typing.overload decorators for it to see that
Expand Down Expand Up @@ -938,8 +965,8 @@ public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs)
return objs;
}

public CodegenParameter fromParameter(Parameter parameter, Set<String> imports) {
CodegenParameter cp = super.fromParameter(parameter, imports);
public CodegenParameter fromParameter(Parameter parameter, Set<String> imports, String priorJsonPathFragment) {
CodegenParameter cp = super.fromParameter(parameter, imports, priorJsonPathFragment);
if (parameter.getStyle() != null) {
switch(parameter.getStyle()) {
case MATRIX:
Expand Down Expand Up @@ -1020,19 +1047,9 @@ public CodegenProperty fromProperty(String name, Schema p, boolean required, boo
if (cp.isPrimitiveType && unaliasedSchema.get$ref() != null) {
cp.complexType = cp.dataType;
}
setAdditionalPropsAndItemsVarNames(cp);
return cp;
}

private void setAdditionalPropsAndItemsVarNames(IJsonSchemaValidationProperties item) {
if (item.getAdditionalProperties() != null) {
item.getAdditionalProperties().setBaseName("additional_properties");
}
if (item.getItems() != null) {
item.getItems().setBaseName("items");
}
}

/**
* checks if the data should be classified as "string" in enum
* e.g. double in C# needs to be double-quoted (e.g. "2.8") by treating it as a string
Expand Down Expand Up @@ -1456,7 +1473,6 @@ public CodegenModel fromModel(String name, Schema sc) {
cm.setHasMultipleTypes(true);
}
Boolean isNotPythonModelSimpleModel = (ModelUtils.isComposedSchema(sc) || ModelUtils.isObjectSchema(sc) || ModelUtils.isMapSchema(sc));
setAdditionalPropsAndItemsVarNames(cm);
if (isNotPythonModelSimpleModel) {
return cm;
}
Expand Down Expand Up @@ -2218,7 +2234,7 @@ protected void setAddProps(Schema schema, IJsonSchemaValidationProperties proper
if (addPropsSchema == null) {
return;
}
CodegenProperty addPropProp = fromProperty("", addPropsSchema, false, false);
CodegenProperty addPropProp = fromProperty("additional_properties", addPropsSchema, false, false);
property.setAdditionalProperties(addPropProp);
}

Expand Down Expand Up @@ -2736,6 +2752,18 @@ public Map<String, Object> postProcessSupportingFileData(Map<String, Object> obj
return objs;
}

@Override
public String toParamName(String name) {
try {
Integer.parseInt(name);
// for parameters in path, or an endpoint
return "parameter_" + name;
} catch (NumberFormatException nfe) {
// for header parameters in responses
return "parameter_" + toModelFilename(name);
}
}

@Override
public void postProcess() {
System.out.println("################################################################################");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,16 @@
```python
{{#with apiInfo}}{{#each apis}}{{#unless hasMore}}{{#if hasHttpSignatureMethods}}import datetime{{/if}}{{/unless}}{{/each}}{{/with}}
import time
import {{{packageName}}}
from pprint import pprint
{{#with apiInfo}}
{{#each apis}}
{{#if @first}}
from {{packageName}}.{{apiPackage}}.tags import {{classFilename}}
{{#each imports}}
{{{import}}}
{{/each}}
{{#with operations}}
{{#each operation}}
{{#if @first}}
{{> doc_auth_partial}}

# Enter a context with an instance of the API client
with {{{packageName}}}.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = {{classFilename}}.{{{classname}}}(api_client)
{{#each allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{#unless required}} (optional){{/unless}}{{#if defaultValue}} (default to {{{.}}}){{/if}}
{{/each}}

try:
{{#if summary}} # {{{summary}}}
{{/if}} {{#if returnType}}api_response = {{/if}}api_instance.{{{operationId}}}({{#each allParams}}{{#if required}}{{paramName}}{{/if}}{{#unless required}}{{paramName}}={{paramName}}{{/unless}}{{#if hasMore}}, {{/if}}{{/each}}){{#if returnType}}
pprint(api_response){{/if}}
except {{{packageName}}}.ApiException as e:
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
{{> api_doc_example }}
{{/if}}
{{/each}}
{{/with}}
{{/if}}
{{/each}}
{{/with}}
```

## Documentation for API Endpoints

Expand Down
Loading