[dart][dart-dio] Next-gen dart-dio generator (#8869)

* [dart-dio] Remove old Dart 1.x templates

* [dart-dio] Initial version of a next-gen Dart Dio generator

* Fix a couple readme links and examples

* Fix import in testcase

* Add integration tests to master POM

* Run initial dart format and improve some base formatting

* Generate docs

* Use integer matchers in test for content-length

* Separate more built_value specific files

* Fix mustache partial path

* Update pubspec template

* Fix tests after mock lib updates

* Generate with new built_value pre-release

This solves the problem of not being able to serialize null.

* Update built_value dependency

* Regenerate after merge

* Regenerate tests

* Fix missing byte response cast

* Update dio to 4.0.0-prev1

* Run format

* Ignore unused imports in inheritance classes

* Update mock test library

* Update docs

* Make a couple variables final

* Update and freeze dio dependency

* Update generator doc

* Add a new option to post processes all dart output at once

This is much faster than individual files. The committed samples should be formatted since Dart is very opinionated and it makes diffs in PRs much easier to read.
Due to this, we also need to format in CI, otherwise there is a git diff.

* Test some CI stuff
This commit is contained in:
Peter Leibiger 2021-03-20 05:26:56 +01:00 committed by GitHub
parent 88fa5d70d7
commit 3d038b74fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
280 changed files with 15378 additions and 1155 deletions

View File

@ -82,6 +82,7 @@ jobs:
- ~/.bundle
- ~/.go_workspace
- ~/.gradle
- ~/.pub-cache
- ~/.cache/bower
- ".git"
- ~/.stack

View File

@ -14,6 +14,18 @@ function cleanup {
trap cleanup EXIT
function installDart {
# install dart2
sudo apt-get update
sudo apt-get install apt-transport-https
sudo sh -c 'wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'
sudo sh -c 'wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list'
sudo apt-get update
sudo apt-get install dart
export PATH="$PATH:/usr/lib/dart/bin"
export DART_POST_PROCESS="dart format"
}
if [ "$NODE_INDEX" = "1" ]; then
echo "Running node $NODE_INDEX to test 'samples.circleci' defined in pom.xml ..."
java -version
@ -24,6 +36,8 @@ if [ "$NODE_INDEX" = "1" ]; then
ls -l /home/circleci/.ivy2/cache
elif [ "$NODE_INDEX" = "2" ]; then
installDart
# run ensure-up-to-date sample script on SNAPSHOT version only
project_version=`mvn org.apache.maven.plugins:maven-help-plugin:3.1.0:evaluate -Dexpression=project.version -q -DforceStdout`
if [[ $project_version == *"-SNAPSHOT" ]]; then
@ -67,14 +81,7 @@ else
export PATH="/usr/local/go1.14/go/bin:$PATH"
go version
# install dart2
sudo apt-get update
sudo apt-get install apt-transport-https
sudo sh -c 'wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -'
sudo sh -c 'wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list'
sudo apt-get update
sudo apt-get install dart
export PATH="$PATH:/usr/lib/dart/bin"
installDart
mvn --no-snapshot-updates --quiet verify -Psamples.circleci.others -Dorg.slf4j.simpleLogger.defaultLogLevel=error
mvn --no-snapshot-updates --quiet javadoc:javadoc -Psamples.circleci -Dorg.slf4j.simpleLogger.defaultLogLevel=error

View File

@ -0,0 +1,7 @@
generatorName: dart-dio-next
outputDir: samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
templateDir: modules/openapi-generator/src/main/resources/dart/libraries/dio
enablePostProcessFile: "true"
additionalProperties:
hideGenerationTimestamp: "true"

View File

@ -22,6 +22,7 @@ The following environment variables are supported by their respective generators
* `CPP_POST_PROCESS_FILE`
* `CSHARP_POST_PROCESS_FILE`
* `C_POST_PROCESS_FILE`
* `DART_POST_PROCESS`
* `DART_POST_PROCESS_FILE`
* `FSHARP_POST_PROCESS_FILE`
* `GO_POST_PROCESS_FILE`

View File

@ -22,6 +22,7 @@ The following generators are available:
* [csharp-netcore](generators/csharp-netcore.md)
* [dart](generators/dart.md)
* [dart-dio](generators/dart-dio.md)
* [dart-dio-next (experimental)](generators/dart-dio-next.md)
* [dart-jaguar](generators/dart-jaguar.md)
* [eiffel](generators/eiffel.md)
* [elixir](generators/elixir.md)

View File

@ -0,0 +1,233 @@
---
title: Config Options for dart-dio-next
sidebar_label: dart-dio-next
---
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|dateLibrary|Specify Date library|<dl><dt>**core**</dt><dd>[DEFAULT] Dart core library (DateTime)</dd><dt>**timemachine**</dt><dd>Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.</dd></dl>|core|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|pubAuthor|Author name in generated pubspec| |null|
|pubAuthorEmail|Email address of the author in generated pubspec| |null|
|pubDescription|Description in generated pubspec| |null|
|pubHomepage|Homepage in generated pubspec| |null|
|pubLibrary|Library name in generated code| |null|
|pubName|Name in generated pubspec| |null|
|pubVersion|Version in generated pubspec| |null|
|serializationLibrary|Specify serialization library|<dl><dt>**built_value**</dt><dd>[DEFAULT] built_value</dd></dl>|built_value|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|Source folder for generated code| |null|
|useEnumExtension|Allow the 'x-enum-values' extension for enums| |null|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>String</li>
<li>bool</li>
<li>double</li>
<li>dynamic</li>
<li>int</li>
<li>num</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>abstract</li>
<li>as</li>
<li>assert</li>
<li>async</li>
<li>await</li>
<li>break</li>
<li>case</li>
<li>catch</li>
<li>class</li>
<li>const</li>
<li>continue</li>
<li>covariant</li>
<li>default</li>
<li>deferred</li>
<li>do</li>
<li>dynamic</li>
<li>else</li>
<li>enum</li>
<li>export</li>
<li>extends</li>
<li>extension</li>
<li>external</li>
<li>factory</li>
<li>false</li>
<li>final</li>
<li>finally</li>
<li>for</li>
<li>function</li>
<li>get</li>
<li>hide</li>
<li>if</li>
<li>implements</li>
<li>import</li>
<li>in</li>
<li>inout</li>
<li>interface</li>
<li>is</li>
<li>late</li>
<li>library</li>
<li>mixin</li>
<li>native</li>
<li>new</li>
<li>null</li>
<li>of</li>
<li>on</li>
<li>operator</li>
<li>out</li>
<li>part</li>
<li>patch</li>
<li>required</li>
<li>rethrow</li>
<li>return</li>
<li>set</li>
<li>show</li>
<li>source</li>
<li>static</li>
<li>super</li>
<li>switch</li>
<li>sync</li>
<li>this</li>
<li>throw</li>
<li>true</li>
<li>try</li>
<li>typedef</li>
<li>var</li>
<li>void</li>
<li>while</li>
<li>with</li>
<li>yield</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✗|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✗|OAS2,OAS3
|Int64|✗|OAS2,OAS3
|Float|✗|OAS2,OAS3
|Double|✗|OAS2,OAS3
|Decimal|✗|ToolingExtension
|String|✗|OAS2,OAS3
|Byte|✗|OAS2,OAS3
|Binary|✗|OAS2,OAS3
|Boolean|✗|OAS2,OAS3
|Date|✗|OAS2,OAS3
|DateTime|✗|OAS2,OAS3
|Password|✗|OAS2,OAS3
|File|✗|OAS2
|Array|✗|OAS2,OAS3
|Maps|✗|ToolingExtension
|CollectionFormat|✗|OAS2
|CollectionFormatMulti|✗|OAS2
|Enum|✗|OAS2,OAS3
|ArrayOfEnum|✗|ToolingExtension
|ArrayOfModel|✗|ToolingExtension
|ArrayOfCollectionOfPrimitives|✗|ToolingExtension
|ArrayOfCollectionOfModel|✗|ToolingExtension
|ArrayOfCollectionOfEnum|✗|ToolingExtension
|MapOfEnum|✗|ToolingExtension
|MapOfModel|✗|ToolingExtension
|MapOfCollectionOfPrimitives|✗|ToolingExtension
|MapOfCollectionOfModel|✗|ToolingExtension
|MapOfCollectionOfEnum|✗|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✗|ToolingExtension
|Model|✗|ToolingExtension
|Api|✗|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✗|OAS2,OAS3
|BasePath|✗|OAS2,OAS3
|Info|✗|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✗|OAS2,OAS3
|Consumes|✗|OAS2
|Produces|✗|OAS2
|ExternalDocumentation|✗|OAS2,OAS3
|Examples|✗|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✗|OAS2,OAS3
|Query|✗|OAS2,OAS3
|Header|✗|OAS2,OAS3
|Body|✗|OAS2
|FormUnencoded|✗|OAS2
|FormMultipart|✗|OAS2
|Cookie|✗|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✗|OAS2,OAS3
|Composite|✗|OAS2,OAS3
|Polymorphism|✗|OAS2,OAS3
|Union|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✗|OAS2,OAS3
|ApiKey|✗|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✗|OAS3
|OAuth2_Implicit|✗|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✗|OAS2,OAS3
|XML|✗|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@ -114,6 +114,15 @@ public class CodegenOperation {
return nonempty(formParams);
}
/**
* Check if there's at least one body parameter or at least one form parameter
*
* @return true if body or form parameter exists, false otherwise
*/
public boolean getHasBodyOrFormParams() {
return getHasBodyParam() || getHasFormParams();
}
/**
* Check if there's at least one form parameter
*

View File

@ -12,17 +12,16 @@ import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.openapitools.codegen.utils.StringUtils.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public abstract class AbstractDartCodegen extends DefaultCodegen {
@ -663,6 +662,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
@Override
public void postProcessFile(File file, String fileType) {
super.postProcessFile(file, fileType);
if (file == null) {
return;
}
@ -674,7 +674,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
// process all files with dart extension
if ("dart".equals(FilenameUtils.getExtension(file.toString()))) {
// currently only support "dartfmt -w yourcode.dart"
// currently supported is "dartfmt -w" and "dart format"
String command = dartPostProcessFile + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
@ -689,4 +689,31 @@ public abstract class AbstractDartCodegen extends DefaultCodegen {
}
}
}
@Override
public void postProcess() {
if (isEnablePostProcessFile()) {
// Using the condition here to have way to still disable this
// for older Dart generators in CI by default.
// Post processing the whole dart output is much faster then individual files.
// Setting this variable to "dart format" is the suggested way of doing this.
final String dartPostProcess = System.getenv("DART_POST_PROCESS");
if (!StringUtils.isEmpty(dartPostProcess)) {
final String command = dartPostProcess + " " + getOutputDir();
try {
Process p = Runtime.getRuntime().exec(command);
int exitValue = p.waitFor();
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: {}", command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
super.postProcess();
}
}

View File

@ -51,10 +51,9 @@ public class DartClientCodegen extends AbstractDartCodegen {
)
);
final CliOption serializationLibrary = new CliOption(CodegenConstants.SERIALIZATION_LIBRARY,
final CliOption serializationLibrary = CliOption.newString(CodegenConstants.SERIALIZATION_LIBRARY,
"Specify serialization library");
serializationLibrary.setDefault(SERIALIZATION_LIBRARY_NATIVE);
serializationLibrary.setType("String");
final Map<String, String> serializationOptions = new HashMap<>();
serializationOptions.put(SERIALIZATION_LIBRARY_NATIVE, "Use native serializer, backwards compatible");

View File

@ -0,0 +1,402 @@
/*
* Copyright 2021 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.ClientModificationFeature;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class DartDioNextClientCodegen extends AbstractDartCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(DartDioNextClientCodegen.class);
public static final String DATE_LIBRARY = "dateLibrary";
public static final String DATE_LIBRARY_CORE = "core";
public static final String DATE_LIBRARY_TIME_MACHINE = "timemachine";
public static final String DATE_LIBRARY_DEFAULT = DATE_LIBRARY_CORE;
public static final String SERIALIZATION_LIBRARY_BUILT_VALUE = "built_value";
public static final String SERIALIZATION_LIBRARY_DEFAULT = SERIALIZATION_LIBRARY_BUILT_VALUE;
private static final String CLIENT_NAME = "clientName";
private String dateLibrary;
private String clientName;
public DartDioNextClientCodegen() {
super();
modifyFeatureSet(features -> features
.includeClientModificationFeatures(
ClientModificationFeature.Authorizations,
ClientModificationFeature.UserAgent
)
);
generatorMetadata = GeneratorMetadata.newBuilder()
.stability(Stability.EXPERIMENTAL)
.build();
outputFolder = "generated-code/dart-dio-next";
embeddedTemplateDir = "dart/libraries/dio";
this.setTemplateDir(embeddedTemplateDir);
apiPackage = "lib.src.api";
modelPackage = "lib.src.model";
supportedLibraries.put(SERIALIZATION_LIBRARY_BUILT_VALUE, "[DEFAULT] built_value");
final CliOption serializationLibrary = CliOption.newString(CodegenConstants.SERIALIZATION_LIBRARY, "Specify serialization library");
serializationLibrary.setEnum(supportedLibraries);
serializationLibrary.setDefault(SERIALIZATION_LIBRARY_DEFAULT);
cliOptions.add(serializationLibrary);
final CliOption dateOption = CliOption.newString(DATE_LIBRARY, "Specify Date library");
dateOption.setDefault(DATE_LIBRARY_DEFAULT);
final Map<String, String> dateOptions = new HashMap<>();
dateOptions.put(DATE_LIBRARY_CORE, "[DEFAULT] Dart core library (DateTime)");
dateOptions.put(DATE_LIBRARY_TIME_MACHINE, "Time Machine is date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.");
dateOption.setEnum(dateOptions);
cliOptions.add(dateOption);
}
public String getDateLibrary() {
return dateLibrary;
}
public void setDateLibrary(String library) {
this.dateLibrary = library;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
@Override
public String getName() {
return "dart-dio-next";
}
@Override
public String getHelp() {
return "Generates a Dart Dio client library with null-safety.";
}
@Override
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("DART_POST_PROCESS_FILE"))) {
LOGGER.info("Environment variable DART_POST_PROCESS_FILE not defined so the Dart code may not be properly formatted. To define it, try `export DART_POST_PROCESS_FILE=\"/usr/local/bin/dartfmt -w\"` (Linux/Mac)");
LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
}
if (!additionalProperties.containsKey(CodegenConstants.SERIALIZATION_LIBRARY)) {
additionalProperties.put(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_DEFAULT);
LOGGER.debug("Serialization library not set, using default {}", SERIALIZATION_LIBRARY_DEFAULT);
}
setLibrary(additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY).toString());
if (!additionalProperties.containsKey(DATE_LIBRARY)) {
additionalProperties.put(DATE_LIBRARY, DATE_LIBRARY_DEFAULT);
LOGGER.debug("Date library not set, using default {}", DATE_LIBRARY_DEFAULT);
}
setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString());
if (!additionalProperties.containsKey(CLIENT_NAME)) {
final String name = org.openapitools.codegen.utils.StringUtils.camelize(pubName);
additionalProperties.put(CLIENT_NAME, name);
LOGGER.debug("Client name not set, using default {}", DATE_LIBRARY_DEFAULT);
}
setClientName(additionalProperties.get(CLIENT_NAME).toString());
supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml"));
supportingFiles.add(new SupportingFile("analysis_options.mustache", "", "analysis_options.yaml"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
final String libFolder = sourceFolder + File.separator + "lib";
supportingFiles.add(new SupportingFile("lib.mustache", libFolder, pubName + ".dart"));
final String srcFolder = libFolder + File.separator + "src";
supportingFiles.add(new SupportingFile("api_client.mustache", srcFolder, "api.dart"));
supportingFiles.add(new SupportingFile("api_util.mustache", srcFolder, "api_util.dart"));
final String authFolder = srcFolder + File.separator + "auth";
supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart"));
supportingFiles.add(new SupportingFile("auth/basic_auth.mustache", authFolder, "basic_auth.dart"));
supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart"));
supportingFiles.add(new SupportingFile("auth/auth.mustache", authFolder, "auth.dart"));
configureSerializationLibrary(srcFolder);
configureDateLibrary(srcFolder);
}
private void configureSerializationLibrary(String srcFolder) {
switch (library) {
default:
case SERIALIZATION_LIBRARY_BUILT_VALUE:
additionalProperties.put("useBuiltValue", "true");
configureSerializationLibraryBuiltValue(srcFolder);
break;
}
}
private void configureSerializationLibraryBuiltValue(String srcFolder) {
supportingFiles.add(new SupportingFile("serialization/built_value/serializers.mustache", srcFolder, "serializers.dart"));
typeMapping.put("Array", "BuiltList");
typeMapping.put("array", "BuiltList");
typeMapping.put("List", "BuiltList");
typeMapping.put("set", "BuiltSet");
typeMapping.put("map", "BuiltMap");
typeMapping.put("file", "Uint8List");
typeMapping.put("binary", "Uint8List");
typeMapping.put("object", "JsonObject");
typeMapping.put("AnyType", "JsonObject");
additionalReservedWords.addAll(Sets.newHashSet(
"EnumClass",
// The following are reserved dataTypes but can not be added to defaultIncludes
// as this would prevent them from being added to the imports.
"BuiltList",
"BuiltSet",
"BuiltMap",
"Uint8List",
"JsonObject"
));
importMapping.put("BuiltList", "package:built_collection/built_collection.dart");
importMapping.put("BuiltSet", "package:built_collection/built_collection.dart");
importMapping.put("BuiltMap", "package:built_collection/built_collection.dart");
importMapping.put("JsonObject", "package:built_value/json_object.dart");
importMapping.put("Uint8List", "dart:typed_data");
}
private void configureDateLibrary(String srcFolder) {
switch (dateLibrary) {
case DATE_LIBRARY_TIME_MACHINE:
additionalProperties.put("useDateLibTimeMachine", "true");
typeMapping.put("date", "OffsetDate");
typeMapping.put("Date", "OffsetDate");
typeMapping.put("DateTime", "OffsetDateTime");
typeMapping.put("datetime", "OffsetDateTime");
additionalReservedWords.addAll(Sets.newHashSet("OffsetDate", "OffsetDateTime"));
importMapping.put("OffsetDate", "package:time_machine/time_machine.dart");
importMapping.put("OffsetDateTime", "package:time_machine/time_machine.dart");
if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) {
supportingFiles.add(new SupportingFile("serialization/built_value/local_date_serializer.mustache", srcFolder, "local_date_serializer.dart"));
}
break;
default:
case DATE_LIBRARY_CORE:
// this option uses the dart core classes
additionalProperties.put("useDateLibCore", "true");
break;
}
}
@Override
public String toDefaultValue(Schema schema) {
if (schema.getDefault() != null) {
if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) {
if (ModelUtils.isArraySchema(schema)) {
if (ModelUtils.isSet(schema)) {
return "SetBuilder()";
}
return "ListBuilder()";
}
if (ModelUtils.isMapSchema(schema)) {
return "MapBuilder()";
}
}
if (ModelUtils.isDateSchema(schema) || ModelUtils.isDateTimeSchema(schema)) {
// this is currently not supported and would create compile errors
return null;
}
if (ModelUtils.isStringSchema(schema)) {
return "'" + schema.getDefault().toString().replaceAll("'", "\\'") + "'";
}
return schema.getDefault().toString();
}
return null;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
objs = super.postProcessModels(objs);
List<Object> models = (List<Object>) objs.get("models");
ProcessUtils.addIndexToProperties(models, 1);
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
Set<String> modelImports = new HashSet<>();
CodegenModel cm = (CodegenModel) mo.get("model");
for (String modelImport : cm.imports) {
if (needToImport(modelImport)) {
if (importMapping().containsKey(modelImport)) {
modelImports.add(importMapping().get(modelImport));
} else {
modelImports.add("package:" + pubName + "/src/model/" + underscore(modelImport) + ".dart");
}
}
}
cm.imports = modelImports;
boolean hasVars = cm.vars.size() > 0;
cm.vendorExtensions.put("x-has-vars", hasVars);
}
return objs;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) {
if (property.isEnum) {
// enums are generated with built_value and make use of BuiltSet
model.imports.add("BuiltSet");
}
property.getVendorExtensions().put("x-built-value-serializer-type", createBuiltValueSerializerType(property));
}
}
private String createBuiltValueSerializerType(CodegenProperty property) {
final StringBuilder sb = new StringBuilder("const FullType(");
if (property.isContainer) {
appendBuiltValueCollection(sb, property);
} else {
sb.append(property.datatypeWithEnum);
}
sb.append(")");
return sb.toString();
}
private void appendBuiltValueCollection(StringBuilder sb, CodegenProperty property) {
sb.append(property.baseType);
sb.append(", [FullType(");
if (property.isMap) {
// a map always has string keys
sb.append("String), FullType(");
}
if (property.items.isContainer) {
appendBuiltValueCollection(sb, property.items);
} else {
sb.append(property.items.datatypeWithEnum);
}
sb.append(")]");
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
objs = super.postProcessOperationsWithModels(objs, allModels);
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
Set<Map<String, Object>> serializers = new HashSet<>();
Set<String> modelImports = new HashSet<>();
Set<String> fullImports = new HashSet<>();
for (CodegenOperation op : operationList) {
op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT);
boolean isJson = true; //default to JSON
boolean isForm = false;
boolean isMultipart = false;
if (op.consumes != null) {
for (Map<String, String> consume : op.consumes) {
if (consume.containsKey("mediaType")) {
String type = consume.get("mediaType");
isJson = type.equalsIgnoreCase("application/json");
isForm = type.equalsIgnoreCase("application/x-www-form-urlencoded");
isMultipart = type.equalsIgnoreCase("multipart/form-data");
break;
}
}
}
for (CodegenParameter param : op.bodyParams) {
if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && isMultipart) {
param.baseType = "MultipartFile";
param.dataType = "MultipartFile";
}
if (param.isContainer) {
final Map<String, Object> serializer = new HashMap<>();
serializer.put("isArray", param.isArray);
serializer.put("uniqueItems", param.uniqueItems);
serializer.put("isMap", param.isMap);
serializer.put("baseType", param.baseType);
serializers.add(serializer);
}
}
op.vendorExtensions.put("x-is-json", isJson);
op.vendorExtensions.put("x-is-form", isForm);
op.vendorExtensions.put("x-is-multipart", isMultipart);
if (op.getHasFormParams()) {
fullImports.add("package:" + pubName + "/src/api_util.dart");
}
Set<String> imports = new HashSet<>();
for (String item : op.imports) {
if (needToImport(item)) {
if (importMapping().containsKey(item)) {
fullImports.add(importMapping().get(item));
} else {
imports.add(underscore(item));
}
}
}
modelImports.addAll(imports);
op.imports = imports;
if (op.returnContainer != null) {
final Map<String, Object> serializer = new HashMap<>();
serializer.put("isArray", Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer));
serializer.put("uniqueItems", op.uniqueItems);
serializer.put("isMap", Objects.equals("map", op.returnContainer));
serializer.put("baseType", op.returnBaseType);
serializers.add(serializer);
}
}
objs.put("modelImports", modelImports);
objs.put("fullImports", fullImports);
objs.put("serializers", serializers);
return objs;
}
}

View File

@ -24,6 +24,7 @@ org.openapitools.codegen.languages.CSharpDotNet2ClientCodegen
org.openapitools.codegen.languages.CSharpNancyFXServerCodegen
org.openapitools.codegen.languages.DartClientCodegen
org.openapitools.codegen.languages.DartDioClientCodegen
org.openapitools.codegen.languages.DartDioNextClientCodegen
org.openapitools.codegen.languages.DartJaguarClientCodegen
org.openapitools.codegen.languages.EiffelClientCodegen
org.openapitools.codegen.languages.ElixirClientCodegen

View File

@ -51,15 +51,15 @@ Please follow the [installation procedure](#installation--usage) and then run th
import 'package:{{pubName}}/api.dart';
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
var api_instance = new {{classname}}();
final api = {{classname}}();
{{#allParams}}
var {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}new {{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}}
final {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}}
{{/allParams}}
try {
{{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#returnType}}final response = await {{/returnType}}api.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#returnType}}
print(result);
print(response);
{{/returnType}}
} catch (e) {
print("Exception when calling {{classname}}->{{operationId}}: $e\n");
@ -73,12 +73,12 @@ All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}/{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}/{{{classname}}}.md)
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
## Documentation For Authorization

View File

@ -10,7 +10,7 @@ All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}

View File

@ -1,2 +0,0 @@
analyzer:
strong-mode: true

View File

@ -1,117 +0,0 @@
part of {{pubName}}.api;
{{#operations}}
class {{classname}} {
final ApiClient apiClient;
{{classname}}([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient;
{{#operation}}
/// {{summary}}
///
/// {{notes}}
{{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
// verify required params are set
{{#allParams}}
{{#required}}
if({{paramName}} == null) {
throw new ApiException(400, "Missing required param: {{paramName}}");
}
{{/required}}
{{/allParams}}
// create path and map variables
String path = "{{{path}}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{baseName}}" + "}", {{{paramName}}}.toString()){{/pathParams}};
// query params
List<QueryParam> queryParams = [];
Map<String, String> headerParams = {};
Map<String, String> formParams = {};
{{#queryParams}}
{{^required}}
if({{paramName}} != null) {
{{/required}}
queryParams.addAll(_convertParametersForCollectionFormat("{{collectionFormat}}", "{{baseName}}", {{paramName}}));
{{^required}}
}
{{/required}}
{{/queryParams}}
{{#headerParams}}
headerParams["{{baseName}}"] = {{paramName}};
{{/headerParams}}
List<String> contentTypes = [{{#consumes}}"{{{mediaType}}}"{{^-last}},{{/-last}}{{/consumes}}];
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
List<String> authNames = [{{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}}];
if(contentType.startsWith("multipart/form-data")) {
bool hasFields = false;
MultipartRequest mp = new MultipartRequest(null, null);
{{#formParams}}
{{^isFile}}
if ({{paramName}} != null) {
hasFields = true;
mp.fields['{{baseName}}'] = parameterToString({{paramName}});
}
{{/isFile}}
{{#isFile}}
if ({{paramName}} != null) {
hasFields = true;
mp.fields['{{baseName}}'] = {{paramName}}.field;
mp.files.add({{paramName}});
}
{{/isFile}}
{{/formParams}}
if(hasFields)
postBody = mp;
}
else {
{{#formParams}}
{{^isFile}}
if ({{paramName}} != null)
formParams['{{baseName}}'] = parameterToString({{paramName}});
{{/isFile}}
{{/formParams}}
}
var response = await apiClient.invokeAPI(path,
'{{httpMethod}}',
queryParams,
postBody,
headerParams,
formParams,
contentType,
authNames);
if(response.statusCode >= 400) {
throw new ApiException(response.statusCode, _decodeBodyBytes(response));
} else if(response.body != null) {
{{#isArray}}
{{#returnType}}
return (apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as List).map((item) => item as {{returnBaseType}}).toList();
{{/returnType}}
{{/isArray}}
{{^isArray}}
{{#isMap}}
{{#returnType}}
return new {{{returnType}}}.from(apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}'));
{{/returnType}};
{{/isMap}}
{{^isMap}}
{{#returnType}}
return apiClient.deserialize(_decodeBodyBytes(response), '{{{returnType}}}') as {{{returnType}}};
{{/returnType}}
{{/isMap}}
{{/isArray}}
} else {
return{{#returnType}} null{{/returnType}};
}
}
{{/operation}}
}
{{/operations}}

View File

@ -1,170 +0,0 @@
part of {{pubName}}.api;
class QueryParam {
String name;
String value;
QueryParam(this.name, this.value);
}
class ApiClient {
String basePath;
var client = new Client();
Map<String, String> _defaultHeaderMap = {};
Map<String, Authentication> _authentications = {};
final _RegList = new RegExp(r'^List<(.*)>$');
final _RegMap = new RegExp(r'^Map<String,(.*)>$');
ApiClient({this.basePath: "{{{basePath}}}"}) {
// Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}
_authentications['{{name}}'] = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}}
_authentications['{{name}}'] = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}}
_authentications['{{name}}'] = new OAuth();{{/isOAuth}}{{/authMethods}}
{{#httpUserAgent}}addDefaultHeader('User-Agent', '{{{.}}}');{{/httpUserAgent}}
}
void addDefaultHeader(String key, String value) {
_defaultHeaderMap[key] = value;
}
dynamic _deserialize(dynamic value, String targetType) {
try {
switch (targetType) {
case 'String':
return '$value';
case 'int':
return value is int ? value : int.parse('$value');
case 'bool':
return value is bool ? value : '$value'.toLowerCase() == 'true';
case 'double':
return value is double ? value : double.parse('$value');
{{#models}}
{{#model}}
case '{{classname}}':
{{#isEnum}}
// Enclose the value in a list so that Dartson can use a transformer
// to decode it.
final listValue = [value];
final List<dynamic> listResult = dson.map(listValue, []);
return listResult[0];
{{/isEnum}}
{{^isEnum}}
return new {{classname}}.fromJson(value);
{{/isEnum}}
{{/model}}
{{/models}}
default:
{
Match match;
if (value is List &&
(match = _RegList.firstMatch(targetType)) != null) {
var newTargetType = match[1];
return value.map((v) => _deserialize(v, newTargetType)).toList();
} else if (value is Map &&
(match = _RegMap.firstMatch(targetType)) != null) {
var newTargetType = match[1];
return new Map.fromIterables(value.keys,
value.values.map((v) => _deserialize(v, newTargetType)));
}
}
}
} catch (e, stack) {
throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack);
}
throw new ApiException(500, 'Could not find a suitable class for deserialization');
}
dynamic deserialize(String json, String targetType) {
// Remove all spaces. Necessary for reg expressions as well.
targetType = targetType.replaceAll(' ', '');
if (targetType == 'String') return json;
var decodedJson = JSON.decode(json);
return _deserialize(decodedJson, targetType);
}
String serialize(Object obj) {
String serialized = '';
if (obj == null) {
serialized = '';
} else {
serialized = JSON.encode(obj);
}
return serialized;
}
// We don't use a Map<String, String> for queryParams.
// If collectionFormat is 'multi' a key might appear multiple times.
Future<Response> invokeAPI(String path,
String method,
Iterable<QueryParam> queryParams,
Object body,
Map<String, String> headerParams,
Map<String, String> formParams,
String contentType,
List<String> authNames) async {
_updateParamsForAuth(authNames, queryParams, headerParams);
var ps = queryParams
.where((p) => p.value != null)
.map((p) => '${p.name}=${Uri.encodeQueryComponent(p.value)}');
String queryString = ps.isNotEmpty ?
'?' + ps.join('&') :
'';
String url = basePath + path + queryString;
headerParams.addAll(_defaultHeaderMap);
headerParams['Content-Type'] = contentType;
if(body is MultipartRequest) {
var request = new MultipartRequest(method, Uri.parse(url));
request.fields.addAll(body.fields);
request.files.addAll(body.files);
request.headers.addAll(body.headers);
request.headers.addAll(headerParams);
var response = await client.send(request);
return Response.fromStream(response);
} else {
var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body);
switch(method) {
case "POST":
return client.post(url, headers: headerParams, body: msgBody);
case "PUT":
return client.put(url, headers: headerParams, body: msgBody);
case "DELETE":
return client.delete(url, headers: headerParams);
case "PATCH":
return client.patch(url, headers: headerParams, body: msgBody);
case "HEAD":
return client.head(url, headers: headerParams);
default:
return client.get(url, headers: headerParams);
}
}
}
/// Update query and header parameters based on authentication settings.
/// @param authNames The authentications to apply
void _updateParamsForAuth(List<String> authNames, List<QueryParam> queryParams, Map<String, String> headerParams) {
authNames.forEach((authName) {
Authentication auth = _authentications[authName];
if (auth == null) throw new ArgumentError("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
});
}
void setAccessToken(String accessToken) {
_authentications.forEach((key, auth) {
if (auth is OAuth) {
auth.setAccessToken(accessToken);
}
});
}
}

View File

@ -1,23 +0,0 @@
part of {{pubName}}.api;
class ApiException implements Exception {
int code = 0;
String message = null;
Exception innerException = null;
StackTrace stackTrace = null;
ApiException(this.code, this.message);
ApiException.withInner(this.code, this.message, this.innerException, this.stackTrace);
String toString() {
if (message == null) return "ApiException";
if (innerException == null) {
return "ApiException $code: $message";
}
return "ApiException $code: $message (Inner exception: ${innerException})\n\n" +
stackTrace.toString();
}
}

View File

@ -1,64 +0,0 @@
part of {{pubName}}.api;
const _delimiters = const {'csv': ',', 'ssv': ' ', 'tsv': '\t', 'pipes': '|'};
// port from Java version
Iterable<QueryParam> _convertParametersForCollectionFormat(
String collectionFormat, String name, dynamic value) {
var params = <QueryParam>[];
// preconditions
if (name == null || name.isEmpty || value == null) return params;
if (value is! List) {
params.add(new QueryParam(name, parameterToString(value)));
return params;
}
List values = value as List;
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty)
? "csv"
: collectionFormat; // default: csv
if (collectionFormat == "multi") {
return values.map((v) => new QueryParam(name, parameterToString(v)));
}
String delimiter = _delimiters[collectionFormat] ?? ",";
params.add(new QueryParam(name, values.map((v) => parameterToString(v)).join(delimiter)));
return params;
}
/// Format the given parameter object into string.
String parameterToString(dynamic value) {
if (value == null) {
return '';
} else if (value is DateTime) {
return value.toUtc().toIso8601String();
{{#models}}
{{#model}}
{{#isEnum}}
} else if (value is {{classname}}) {
return new {{classname}}TypeTransformer().encode(value).toString();
{{/isEnum}}
{{/model}}
{{/models}}
} else {
return value.toString();
}
}
/// Returns the decoded body by utf-8 if application/json with the given headers.
/// Else, returns the decoded body by default algorithm of dart:http.
/// Because avoid to text garbling when header only contains "application/json" without "; charset=utf-8".
String _decodeBodyBytes(Response response) {
var contentType = response.headers['content-type'];
if (contentType != null && contentType.contains("application/json")) {
return utf8.decode(response.bodyBytes);
} else {
return response.body;
}
}

View File

@ -1,28 +0,0 @@
import 'package:{{pubName}}/api.dart';
import 'package:test/test.dart';
{{#operations}}
/// tests for {{classname}}
void main() {
var instance = new {{classname}}();
group('tests for {{classname}}', () {
{{#operation}}
{{#summary}}
// {{{.}}}
//
{{/summary}}
{{#notes}}
// {{{.}}}
//
{{/notes}}
//{{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{operationId}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async
test('test {{operationId}}', () async {
// TODO
});
{{/operation}}
});
}
{{/operations}}

View File

@ -1,20 +0,0 @@
library {{pubName}}.api;
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
part 'api_client.dart';
part 'api_helper.dart';
part 'api_exception.dart';
part 'auth/authentication.dart';
part 'auth/api_key_auth.dart';
part 'auth/oauth.dart';
part 'auth/http_basic_auth.dart';
{{#apiInfo}}{{#apis}}part 'api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}}
{{#models}}{{#model}}part 'model/{{classFilename}}.dart';
{{/model}}{{/models}}
ApiClient defaultApiClient = new ApiClient();

View File

@ -1,27 +0,0 @@
part of {{pubName}}.api;
class ApiKeyAuth implements Authentication {
final String location;
final String paramName;
String apiKey;
String apiKeyPrefix;
ApiKeyAuth(this.location, this.paramName);
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
String value;
if (apiKeyPrefix != null) {
value = '$apiKeyPrefix $apiKey';
} else {
value = apiKey;
}
if (location == 'query' && value != null) {
queryParams.add(new QueryParam(paramName, value));
} else if (location == 'header' && value != null) {
headerParams[paramName] = value;
}
}
}

View File

@ -1,7 +0,0 @@
part of {{pubName}}.api;
abstract class Authentication {
/// Apply authentication settings to header and query params.
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams);
}

View File

@ -1,14 +0,0 @@
part of {{pubName}}.api;
class HttpBasicAuth implements Authentication {
String username;
String password;
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams["Authorization"] = "Basic " + BASE64.encode(UTF8.encode(str));
}
}

View File

@ -1,19 +0,0 @@
part of {{pubName}}.api;
class OAuth implements Authentication {
String accessToken;
OAuth({this.accessToken}) {
}
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
if (accessToken != null) {
headerParams["Authorization"] = "Bearer " + accessToken;
}
}
void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}

View File

@ -1,96 +0,0 @@
class {{classname}} {
{{#vars}}
{{#description}}/* {{{description}}} */{{/description}}
{{^defaultValue}}{{{dataType}}} {{name}} = null;{{/defaultValue}}{{#defaultValue}}{{{dataType}}} {{name}} = {{defaultValue}};{{/defaultValue}}
{{#allowableValues}}
{{#min}} // range from {{min}} to {{max}}{{/min}}//{{^min}}enum {{name}}Enum { {{#values}} {{.}}, {{/values}} };{{/min}}{
{{/allowableValues}}
{{/vars}}
{{classname}}();
@override
String toString() {
return '{{classname}}[{{#vars}}{{name}}=${{name}}, {{/vars}}]';
}
{{classname}}.fromJson(Map<String, dynamic> json) {
if (json == null) return;
{{#vars}}
if (json['{{baseName}}'] == null) {
{{name}} = null;
} else {
{{#isDateTime}}
{{name}} = DateTime.parse(json['{{baseName}}']);
{{/isDateTime}}
{{#isDate}}
{{name}} = DateTime.parse(json['{{baseName}}']);
{{/isDate}}
{{^isDateTime}}
{{^isDate}}
{{#complexType}}
{{#isArray}}
{{name}} = {{complexType}}.listFromJson(json['{{baseName}}']);
{{/isArray}}
{{^isArray}}
{{#isMap}}
{{name}} = {{complexType}}.mapFromJson(json['{{baseName}}']);
{{/isMap}}
{{^isMap}}
{{name}} = new {{complexType}}.fromJson(json['{{baseName}}']);
{{/isMap}}
{{/isArray}}
{{/complexType}}
{{^complexType}}
{{#isArray}}
{{name}} = (json['{{baseName}}'] as List).map((item) => item as {{items.datatype}}).toList();
{{/isArray}}
{{^isArray}}
{{name}} = json['{{baseName}}'];
{{/isArray}}
{{/complexType}}
{{/isDate}}
{{/isDateTime}}
}
{{/vars}}
}
Map<String, dynamic> toJson() {
return {
{{#vars}}
{{#isDateTime}}
'{{baseName}}': {{name}} == null ? '' : {{name}}.toUtc().toIso8601String(){{^-last}},{{/-last}}
{{/isDateTime}}
{{#isDate}}
'{{baseName}}': {{name}} == null ? '' : {{name}}.toUtc().toIso8601String(){{^-last}},{{/-last}}
{{/isDate}}
{{^isDateTime}}
{{^isDate}}
{{#complexType}}
{{#isArray}}
'{{baseName}}': {{name}} == null ? null : {{name}}.map((item) => item.toJson()).toList(){{^-last}},{{/-last}}
{{/isArray}}
{{^isArray}}
'{{baseName}}': {{name}} == null ? null : {{name}}.toJson(){{^-last}},{{/-last}}
{{/isArray}}
{{/complexType}}
{{^complexType}}
'{{baseName}}': {{name}}{{^-last}},{{/-last}}
{{/complexType}}
{{/isDate}}
{{/isDateTime}}
{{/vars}}
};
}
static List<{{classname}}> listFromJson(List<dynamic> json) {
return json == null ? new List<{{classname}}>() : json.map((value) => new {{classname}}.fromJson(value)).toList();
}
static Map<String, {{classname}}> mapFromJson(Map<String, Map<String, dynamic>> json) {
var map = new Map<String, {{classname}}>();
if (json != null && json.length > 0) {
json.forEach((String key, Map<String, dynamic> value) => map[key] = new {{classname}}.fromJson(value));
}
return map;
}
}

View File

@ -1,36 +0,0 @@
@Entity()
class {{classname}} {
/// The underlying value of this enum member.
final {{dataType}} value;
const {{classname}}._internal(this.value);
{{#allowableValues}}
{{#enumVars}}
{{#description}}
/// {{description}}
{{/description}}
static const {{classname}} {{{name}}} = const {{classname}}._internal({{{value}}});
{{/enumVars}}
{{/allowableValues}}
}
class {{classname}}TypeTransformer extends TypeTransformer<{{classname}}> {
@override
dynamic encode({{classname}} data) {
return data.value;
}
@override
{{classname}} decode(dynamic data) {
switch (data) {
{{#allowableValues}}
{{#enumVars}}
case {{{value}}}: return {{classname}}.{{{name}}};
{{/enumVars}}
{{/allowableValues}}
default: throw('Unknown enum value to decode: $data');
}
}
}

View File

@ -1,58 +0,0 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="{{{gitHost}}}"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -1,4 +1,4 @@
# {{pubName}}
# {{pubName}} (EXPERIMENTAL)
{{#appDescriptionWithNewLines}}
{{{appDescriptionWithNewLines}}}
{{/appDescriptionWithNewLines}}
@ -19,7 +19,9 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
## Requirements
Dart 1.20.0 or later OR Flutter 0.0.20 or later
* Dart 2.12.0 or later OR Flutter 1.26.0 or later
* Dio 4.0.0+
* timemachine option currently **DOES NOT** support sound null-safety and may not work
## Installation & Usage
@ -31,7 +33,7 @@ version: {{pubVersion}}
description: {{pubDescription}}
dependencies:
{{pubName}}:
git: https://{{gitHost}}/{{gitUserId}}/{{gitRepoId}}.git
git: https://github.com/{{gitUserId}}/{{gitRepoId}}.git
version: 'any'
```
@ -43,48 +45,25 @@ dependencies:
path: /path/to/{{pubName}}
```
## Tests
TODO
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```dart
import 'package:{{pubName}}/api.dart';
import 'package:{{pubName}}/{{pubName}}.dart';
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
{{#hasAuthMethods}}
{{#authMethods}}
{{#isBasic}}
// TODO Configure HTTP basic authorization: {{{name}}}
//{{pubName}}.api.Configuration.username = 'YOUR_USERNAME';
//{{pubName}}.api.Configuration.password = 'YOUR_PASSWORD';
{{/isBasic}}
{{#isApiKey}}
// TODO Configure API key authorization: {{{name}}}
//{{pubName}}.api.Configuration.apiKey{'{{{keyParamName}}}'} = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//{{pubName}}.api.Configuration.apiKeyPrefix{'{{{keyParamName}}}'} = "Bearer";
{{/isApiKey}}
{{#isOAuth}}
// TODO Configure OAuth2 access token for authorization: {{{name}}}
//{{pubName}}.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
var api_instance = new {{classname}}();
final api = {{classname}}();
{{#allParams}}
var {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}new {{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}}
final {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}}
{{/allParams}}
try {
{{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#returnType}}final response = await {{/returnType}}api.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{#returnType}}
print(result);
print(response);
{{/returnType}}
} catch (e) {
} catch on DioError (e) {
print("Exception when calling {{classname}}->{{operationId}}: $e\n");
}
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
@ -96,12 +75,12 @@ All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}/{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}/{{{classname}}}.md)
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
## Documentation For Authorization

View File

@ -0,0 +1,9 @@
analyzer:
language:
strict-inference: true
strict-raw-types: true
strong-mode:
implicit-dynamic: false
implicit-casts: false
exclude:
- test/*.dart

View File

@ -0,0 +1,136 @@
{{>header}}
import 'dart:async';
{{#useBuiltValue}}import 'package:built_value/serializer.dart';{{/useBuiltValue}}
import 'package:dio/dio.dart';
{{#operations}}
{{#modelImports}}import 'package:{{pubName}}/src/model/{{.}}.dart';
{{/modelImports}}
{{#fullImports}}import '{{.}}';
{{/fullImports}}
class {{classname}} {
final Dio _dio;
{{#useBuiltValue}}
final Serializers _serializers;
{{/useBuiltValue}}
const {{classname}}(this._dio{{#useBuiltValue}}, this._serializers{{/useBuiltValue}});
{{#operation}}
/// {{{summary}}}
///
/// {{{notes}}}
Future<Response<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> {{nickname}}({ {{#allParams}}{{#isPathParam}}
required {{{dataType}}} {{paramName}},{{/isPathParam}}{{#isQueryParam}}
{{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isQueryParam}}{{#isHeaderParam}}
{{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isHeaderParam}}{{#isBodyParam}}
{{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isBodyParam}}{{#isFormParam}}
{{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isFormParam}}{{/allParams}}
CancelToken? cancelToken,
Map<String, dynamic>? headers,
Map<String, dynamic>? extra,
ValidateStatus? validateStatus,
ProgressCallback? onSendProgress,
ProgressCallback? onReceiveProgress,
}) async {
final _path = r'{{{path}}}'{{#pathParams}}.replaceAll('{' r'{{{baseName}}}' '}', {{{paramName}}}.toString()){{/pathParams}};
final _options = Options(
method: r'{{#lambda.uppercase}}{{httpMethod}}{{/lambda.uppercase}}',
{{#isResponseFile}}
responseType: ResponseType.bytes,
{{/isResponseFile}}
headers: <String, dynamic>{
{{#httpUserAgent}}
r'User-Agent': r'{{{.}}}',
{{/httpUserAgent}}
{{#headerParams}}
{{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{baseName}}': {{paramName}},
{{/headerParams}}
...?headers,
},
extra: <String, dynamic>{
'secure': <Map<String, String>>[{{^hasAuthMethods}}],{{/hasAuthMethods}}{{#hasAuthMethods}}
{{#authMethods}}{
'type': '{{type}}',
'name': '{{name}}',{{#isApiKey}}
'keyName': '{{keyParamName}}',
'where': '{{#isKeyInQuery}}query{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}',{{/isApiKey}}
},{{/authMethods}}
],{{/hasAuthMethods}}
...?extra,
},
contentType: [{{^hasConsumes}}
'application/json',{{/hasConsumes}}{{#hasConsumes}}{{#consumes}}
'{{{mediaType}}}',{{/consumes}}{{/hasConsumes}}
].first,
validateStatus: validateStatus,
);
final _queryParameters = <String, dynamic>{
{{#queryParams}}
{{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{baseName}}': {{paramName}},
{{/queryParams}}
};
{{#hasBodyOrFormParams}}
dynamic _bodyData;
try {
{{#useBuiltValue}}{{>serialization/built_value/serialize}}{{/useBuiltValue}}
} catch(error) {
throw DioError(
requestOptions: _options.compose(
_dio.options,
_path,
queryParameters: _queryParameters,
),
type: DioErrorType.other,
error: error,
);
}
{{/hasBodyOrFormParams}}
final _response = await _dio.request<Object>(
_path,{{#hasBodyOrFormParams}}
data: _bodyData,{{/hasBodyOrFormParams}}
options: _options,
queryParameters: _queryParameters,
cancelToken: cancelToken,
onSendProgress: onSendProgress,
onReceiveProgress: onReceiveProgress,
);
{{#returnType}}
{{{returnType}}} _responseData;
try {
{{#useBuiltValue}}{{>serialization/built_value/deserialize}}{{/useBuiltValue}}
} catch (error) {
throw DioError(
requestOptions: _response.requestOptions,
response: _response,
type: DioErrorType.other,
error: error,
);
}
return Response<{{{returnType}}}>(
data: _responseData,
headers: _response.headers,
isRedirect: _response.isRedirect,
requestOptions: _response.requestOptions,
redirects: _response.redirects,
statusCode: _response.statusCode,
statusMessage: _response.statusMessage,
extra: _response.extra,
);{{/returnType}}{{^returnType}}
return _response;{{/returnType}}
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,64 @@
{{>header}}
import 'package:dio/dio.dart';{{#useBuiltValue}}
import 'package:built_value/serializer.dart';
import 'package:{{pubName}}/src/serializers.dart';{{/useBuiltValue}}
import 'package:{{pubName}}/src/auth/api_key_auth.dart';
import 'package:{{pubName}}/src/auth/basic_auth.dart';
import 'package:{{pubName}}/src/auth/oauth.dart';
{{#apiInfo}}{{#apis}}import 'package:{{pubName}}/src/api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}}
class {{clientName}} {
static const String basePath = r'{{{basePath}}}';
final Dio dio;
{{#useBuiltValue}}
final Serializers serializers;
{{/useBuiltValue}}
{{clientName}}({
Dio? dio,{{#useBuiltValue}}
Serializers? serializers,{{/useBuiltValue}}
String? basePathOverride,
List<Interceptor>? interceptors,
}) : {{#useBuiltValue}}this.serializers = serializers ?? standardSerializers,{{/useBuiltValue}}
this.dio = dio ??
Dio(BaseOptions(
baseUrl: basePathOverride ?? basePath,
connectTimeout: 5000,
receiveTimeout: 3000,
)) {
if (interceptors == null) {
this.dio.interceptors.addAll([
OAuthInterceptor(),
BasicAuthInterceptor(),
ApiKeyAuthInterceptor(),
]);
} else {
this.dio.interceptors.addAll(interceptors);
}
}
void setOAuthToken(String name, String token) {
if (this.dio.interceptors.any((i) => i is OAuthInterceptor)) {
(this.dio.interceptors.firstWhere((i) => i is OAuthInterceptor) as OAuthInterceptor).tokens[name] = token;
}
}
void setBasicAuth(String name, String username, String password) {
if (this.dio.interceptors.any((i) => i is BasicAuthInterceptor)) {
(this.dio.interceptors.firstWhere((i) => i is BasicAuthInterceptor) as BasicAuthInterceptor).authInfo[name] = BasicAuthInfo(username, password);
}
}
void setApiKey(String name, String apiKey) {
if (this.dio.interceptors.any((i) => i is ApiKeyAuthInterceptor)) {
(this.dio.interceptors.firstWhere((element) => element is ApiKeyAuthInterceptor) as ApiKeyAuthInterceptor).apiKeys[name] = apiKey;
}
}{{#apiInfo}}{{#apis}}
/// Get {{classname}} instance, base route and serializer can be overridden by a given but be careful,
/// by doing that all interceptors will not be executed
{{classname}} get{{classname}}() {
return {{classname}}(dio{{#useBuiltValue}}, serializers{{/useBuiltValue}});
}{{/apis}}{{/apiInfo}}
}

View File

@ -10,7 +10,7 @@ All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
@ -29,25 +29,25 @@ import 'package:{{pubName}}/api.dart';
{{#authMethods}}
{{#isBasic}}
// TODO Configure HTTP basic authorization: {{{name}}}
//{{pubName}}.api.Configuration.username = 'YOUR_USERNAME';
//{{pubName}}.api.Configuration.password = 'YOUR_PASSWORD';
//defaultApiClient.getAuthentication<HttpBasicAuth>('{{{name}}}').username = 'YOUR_USERNAME'
//defaultApiClient.getAuthentication<HttpBasicAuth>('{{{name}}}').password = 'YOUR_PASSWORD';
{{/isBasic}}
{{#isApiKey}}
// TODO Configure API key authorization: {{{name}}}
//{{pubName}}.api.Configuration.apiKey{'{{{keyParamName}}}'} = 'YOUR_API_KEY';
//defaultApiClient.getAuthentication<ApiKeyAuth>('{{{name}}}').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//{{pubName}}.api.Configuration.apiKeyPrefix{'{{{keyParamName}}}'} = "Bearer";
//defaultApiClient.getAuthentication<ApiKeyAuth>('{{{name}}}').apiKeyPrefix = 'Bearer';
{{/isApiKey}}
{{#isOAuth}}
// TODO Configure OAuth2 access token for authorization: {{{name}}}
//{{pubName}}.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN';
//defaultApiClient.getAuthentication<OAuth>('{{{name}}}').accessToken = 'YOUR_ACCESS_TOKEN';
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
var api_instance = new {{classname}}();
{{#allParams}}
var {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}new {{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}}
var {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}new {{{dataType}}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}}
{{/allParams}}
try {
@ -56,7 +56,7 @@ try {
print(result);
{{/returnType}}
} catch (e) {
print("Exception when calling {{classname}}->{{operationId}}: $e\n");
print('Exception when calling {{classname}}->{{operationId}}: $e\n');
}
```
@ -64,7 +64,7 @@ try {
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{baseType}}.md){{/isPrimitiveType}}| {{{description}}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}}
{{/allParams}}
### Return type

View File

@ -0,0 +1,28 @@
import 'package:test/test.dart';
import 'package:{{pubName}}/{{pubName}}.dart';
{{#operations}}
/// tests for {{{classname}}}
void main() {
final instance = {{{clientName}}}().get{{{classname}}}();
group({{{classname}}}, () {
{{#operation}}
{{#summary}}
// {{{.}}}
//
{{/summary}}
{{#notes}}
// {{{.}}}
//
{{/notes}}
//{{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{dataType}}} {{{paramName}}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{{paramName}}}{{^-last}}, {{/-last}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async
test('test {{{operationId}}}', () async {
// TODO
});
{{/operation}}
});
}
{{/operations}}

View File

@ -0,0 +1,28 @@
{{>header}}
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
/// Format the given form parameter object into something that Dio can handle.
/// Returns primitive or String.
/// Returns List/Map if the value is BuildList/BuiltMap.
dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType type) {
if (value == null) {
return '';
}
if (value is String || value is num || value is bool) {
return value;
}
final serialized = serializers.serialize(
value as Object,
specifiedType: type,
);
if (serialized is String) {
return serialized;
}
if (value is BuiltList || value is BuiltMap) {
return serialized;
}
return json.encode(serialized);
}

View File

@ -0,0 +1,27 @@
{{>header}}
import 'package:dio/dio.dart';
import 'package:{{pubName}}/src/auth/auth.dart';
class ApiKeyAuthInterceptor extends AuthInterceptor {
final Map<String, String> apiKeys = {};
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
final authInfo = getAuthInfo(options, 'apiKey');
for (final info in authInfo) {
final authName = info['name'] as String;
final authKeyName = info['keyName'] as String;
final authWhere = info['where'] as String;
final apiKey = apiKeys[authName];
if (apiKey != null) {
if (authWhere == 'query') {
options.queryParameters[authKeyName] = apiKey;
} else {
options.headers[authKeyName] = apiKey;
}
}
}
super.onRequest(options, handler);
}
}

View File

@ -0,0 +1,21 @@
{{>header}}
import 'package:dio/dio.dart';
abstract class AuthInterceptor extends Interceptor {
/// Get auth information on given route for the given type.
/// Can return an empty list if type is not present on auth data or
/// if route doesn't need authentication.
List<Map<String, dynamic>> getAuthInfo(RequestOptions route, String type) {
if (route.extra.containsKey('secure')) {
final auth = route.extra['secure'] as List<Map<String, String>>;
final results = <Map<String, dynamic>>[];
for (final info in auth) {
if (info['type'] == type) {
results.add(info);
}
}
return results;
}
return [];
}
}

View File

@ -0,0 +1,34 @@
{{>header}}
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:{{pubName}}/src/auth/auth.dart';
class BasicAuthInfo {
final String username;
final String password;
const BasicAuthInfo(this.username, this.password);
}
class BasicAuthInterceptor extends AuthInterceptor {
final Map<String, BasicAuthInfo> authInfo = {};
@override
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
final metadataAuthInfo = getAuthInfo(options, 'basic');
for (final info in metadataAuthInfo) {
final authName = info['name'] as String;
final basicAuthInfo = authInfo[authName];
if (basicAuthInfo != null) {
final basicAuth = 'Basic ${base64Encode(utf8.encode('${basicAuthInfo.username}:${basicAuthInfo.password}'))}';
options.headers['Authorization'] = basicAuth;
break;
}
}
super.onRequest(options, handler);
}
}

View File

@ -0,0 +1,23 @@
{{>header}}
import 'package:dio/dio.dart';
import 'package:{{pubName}}/src/auth/auth.dart';
class OAuthInterceptor extends AuthInterceptor {
final Map<String, String> tokens = {};
@override
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) {
final authInfo = getAuthInfo(options, 'oauth');
for (final info in authInfo) {
final token = tokens[info['name']];
if (token != null) {
options.headers['Authorization'] = 'Bearer ${token}';
break;
}
}
super.onRequest(options, handler);
}
}

View File

@ -0,0 +1 @@
{{#useBuiltValue}}{{>serialization/built_value/class}}{{/useBuiltValue}}

View File

@ -0,0 +1 @@
{{#useBuiltValue}}{{>serialization/built_value/enum}}{{/useBuiltValue}}

View File

@ -1,6 +1,7 @@
# See https://www.dartlang.org/tools/private-files.html
# See https://dart.dev/guides/libraries/private-files
# Files and directories created by pub
.dart_tool/
.buildlog
.packages
.project
@ -25,3 +26,12 @@ doc/api/
# Don't commit pubspec lock file
# (Library packages only! Remove pattern if developing an application package)
pubspec.lock
# Dont commit files and directories created by other development environments.
# For example, if your development environment creates any of the following files,
# consider putting them in a global ignore file:
*.iml // IntelliJ
*.ipr // IntelliJ
*.iws // IntelliJ
.idea/ // IntelliJ
.DS_Store // Mac

View File

@ -0,0 +1,3 @@
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//

View File

@ -0,0 +1,11 @@
{{>header}}
export 'package:{{pubName}}/src/api.dart';
export 'package:{{pubName}}/src/auth/api_key_auth.dart';
export 'package:{{pubName}}/src/auth/basic_auth.dart';
export 'package:{{pubName}}/src/auth/oauth.dart';
{{#useBuiltValue}}export 'package:{{pubName}}/src/serializers.dart';{{/useBuiltValue}}
{{#apiInfo}}{{#apis}}export 'package:{{pubName}}/src/api/{{classFilename}}.dart';
{{/apis}}{{/apiInfo}}
{{#models}}{{#model}}export 'package:{{pubName}}/src/model/{{classFilename}}.dart';
{{/model}}{{/models}}

View File

@ -0,0 +1,9 @@
{{>header}}
{{#models}}
{{#model}}
{{#imports}}
import '{{.}}';
{{/imports}}
{{#isEnum}}{{>enum}}{{/isEnum}}{{^isEnum}}{{>class}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,28 @@
{{#models}}
{{#model}}
import 'package:test/test.dart';
import 'package:{{pubName}}/{{pubName}}.dart';
// tests for {{{classname}}}
void main() {
{{^isEnum}}
{{! Due to required vars without default value we can not create a full instance here }}
final instance = {{{classname}}}Builder();
// TODO add properties to the builder and call build()
{{/isEnum}}
group({{{classname}}}, () {
{{#vars}}
{{#description}}
// {{{description}}}
{{/description}}
// {{{dataType}}} {{{name}}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}}
test('to test the property `{{{name}}}`', () async {
// TODO
});
{{/vars}}
});
}
{{/model}}
{{/models}}

View File

@ -8,7 +8,7 @@ import 'package:{{pubName}}/api.dart';
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}}
{{/vars}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,23 @@
name: {{pubName}}
version: {{pubVersion}}
description: {{pubDescription}}
environment:
sdk: '>=2.12.0 <3.0.0'
dependencies:
dio: '4.0.0-prev2'
{{#useBuiltValue}}
built_value: '>=8.0.3 <9.0.0'
built_collection: '>=5.0.0 <6.0.0'
{{/useBuiltValue}}
{{#useDateLibTimeMachine}}
time_machine: ^0.9.16
{{/useDateLibTimeMachine}}
dev_dependencies:
{{#useBuiltValue}}
built_value_generator: '>=8.0.3 <9.0.0'
build_runner: any
{{/useBuiltValue}}
test: '>=1.16.0 <1.17.0'

View File

@ -0,0 +1,127 @@
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part '{{classFilename}}.g.dart';
{{!
Classes with polymorphism or composition may generate unused imports,
these need to be ignored for said classes so that there are no lint errors.
}}
{{#parentModel}}// ignore_for_file: unused_import{{/parentModel}}
abstract class {{classname}} implements Built<{{classname}}, {{classname}}Builder> {
{{#vars}}
{{#description}}
/// {{{description}}}
{{/description}}
@BuiltValueField(wireName: r'{{baseName}}')
{{{datatypeWithEnum}}}{{#isNullable}}?{{/isNullable}}{{^isNullable}}{{^required}}?{{/required}}{{/isNullable}} get {{name}};
{{#allowableValues}}
// {{#min}}range from {{{min}}} to {{{max}}}{{/min}}{{^min}}enum {{name}}Enum { {{#values}} {{{.}}}, {{/values}} };{{/min}}
{{/allowableValues}}
{{/vars}}
{{classname}}._();
static void _initializeBuilder({{{classname}}}Builder b) => b{{#vars}}{{#defaultValue}}
..{{{name}}} = {{#isEnum}}{{^isContainer}}const {{{enumName}}}._({{/isContainer}}{{/isEnum}}{{{defaultValue}}}{{#isEnum}}{{^isContainer}}){{/isContainer}}{{/isEnum}}{{/defaultValue}}{{/vars}};
factory {{classname}}([void updates({{classname}}Builder b)]) = _${{classname}};
@BuiltValueSerializer(custom: true)
static Serializer<{{classname}}> get serializer => _${{classname}}Serializer();
}
{{!
Generate a custom serializer in order to support combinations of required and nullable.
By default built_value does not serialize null fields.
}}
class _${{classname}}Serializer implements StructuredSerializer<{{classname}}> {
@override
final Iterable<Type> types = const [{{classname}}, _${{classname}}];
@override
final String wireName = r'{{classname}}';
@override
Iterable<Object?> serialize(Serializers serializers, {{{classname}}} object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[];
{{#vars}}
{{#required}}
{{!
A required property need to always be part of the serialized output.
When it is nullable, null is serialized, otherwise it is an error if it is null.
}}
result
..add(r'{{baseName}}')
..add({{#isNullable}}object.{{{name}}} == null ? null : {{/isNullable}}serializers.serialize(object.{{{name}}},
specifiedType: {{{vendorExtensions.x-built-value-serializer-type}}}));
{{/required}}
{{^required}}
if (object.{{{name}}} != null) {
{{! Non-required properties are only serialized if not null. }}
result
..add(r'{{baseName}}')
..add(serializers.serialize(object.{{{name}}},
specifiedType: {{{vendorExtensions.x-built-value-serializer-type}}}));
}
{{/required}}
{{/vars}}
return result;
}
@override
{{classname}} deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = {{classname}}Builder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
{{#vars}}
case r'{{baseName}}':
{{#isContainer}}
result.{{{name}}}.replace(serializers.deserialize(value,
specifiedType: {{{vendorExtensions.x-built-value-serializer-type}}}) as {{{datatypeWithEnum}}});
{{/isContainer}}
{{#isModel}}
result.{{{name}}}.replace(serializers.deserialize(value,
specifiedType: {{{vendorExtensions.x-built-value-serializer-type}}}) as {{{datatypeWithEnum}}});
{{/isModel}}
{{^isContainer}}
{{^isModel}}
result.{{{name}}} = serializers.deserialize(value,
specifiedType: {{{vendorExtensions.x-built-value-serializer-type}}}) as {{{datatypeWithEnum}}};
{{/isModel}}
{{/isContainer}}
break;
{{/vars}}
}
}
return result.build();
}
}
{{!
Generate an enum for any variables that are declared as inline enums
isEnum is only true for inline variables that are enums.
If an enum is declared as a definition, isEnum is false and the enum is generated from the
enum.mustache template.
}}
{{#vars}}
{{#isEnum}}
{{^isContainer}}
{{>serialization/built_value/enum_inline}}
{{/isContainer}}
{{#isContainer}}
{{#mostInnerItems}}
{{>serialization/built_value/enum_inline}}
{{/mostInnerItems}}
{{/isContainer}}
{{/isEnum}}
{{/vars}}

View File

@ -0,0 +1,24 @@
{{#isResponseFile}}
_responseData = _response.data as {{{returnType}}};
{{/isResponseFile}}
{{^isResponseFile}}
{{#returnSimpleType}}
{{#returnTypeIsPrimitive}}
_responseData = _response.data as {{{returnType}}};
{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}
const _responseType = FullType({{{returnType}}});
_responseData = _serializers.deserialize(
_response.data!,
specifiedType: _responseType,
) as {{{returnType}}};
{{/returnTypeIsPrimitive}}
{{/returnSimpleType}}
{{^returnSimpleType}}
const _responseType = FullType(Built{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}{{#isMap}}Map{{/isMap}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{returnBaseType}}})]);
_responseData = _serializers.deserialize(
_response.data!,
specifiedType: _responseType,
) as {{{returnType}}};
{{/returnSimpleType}}
{{/isResponseFile}}

View File

@ -0,0 +1,33 @@
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part '{{classFilename}}.g.dart';
class {{classname}} extends EnumClass {
{{#allowableValues}}
{{#enumVars}}
{{#description}}
/// {{{description}}}
{{/description}}
@BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{^isInteger}}wireName: r{{{value}}}{{/isInteger}})
static const {{classname}} {{name}} = _${{name}};
{{/enumVars}}
{{/allowableValues}}
static Serializer<{{classname}}> get serializer => _${{#lambda.camelcase}}{{{classname}}}{{/lambda.camelcase}}Serializer;
const {{classname}}._(String name): super(name);
static BuiltSet<{{classname}}> get values => _$values;
static {{classname}} valueOf(String name) => _$valueOf(name);
}
/// Optionally, enum_class can generate a mixin to go with your enum for use
/// with Angular. It exposes your enum constants as getters. So, if you mix it
/// in to your Dart component class, the values become available to the
/// corresponding Angular template.
///
/// Trigger mixin generation by writing a line like this one next to your enum.
abstract class {{classname}}Mixin = Object with _${{classname}}Mixin;

View File

@ -0,0 +1,19 @@
class {{{enumName}}} extends EnumClass {
{{#allowableValues}}
{{#enumVars}}
{{#description}}
/// {{{description}}}
{{/description}}
@BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{^isInteger}}wireName: r{{{value}}}{{/isInteger}})
static const {{{enumName}}} {{name}} = _${{#lambda.camelcase}}{{{enumName}}}{{/lambda.camelcase}}_{{name}};
{{/enumVars}}
{{/allowableValues}}
static Serializer<{{{enumName}}}> get serializer => _${{#lambda.camelcase}}{{{enumName}}}{{/lambda.camelcase}}Serializer;
const {{{enumName}}}._(String name): super(name);
static BuiltSet<{{{enumName}}}> get values => _${{#lambda.camelcase}}{{{enumName}}}{{/lambda.camelcase}}Values;
static {{{enumName}}} valueOf(String name) => _${{#lambda.camelcase}}{{{enumName}}}{{/lambda.camelcase}}ValueOf(name);
}

View File

@ -0,0 +1,52 @@
{{>header}}
import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:time_machine/time_machine.dart';
class OffsetDateSerializer implements PrimitiveSerializer<OffsetDate> {
const OffsetDateSerializer();
@override
Iterable<Type> get types => BuiltList<Type>([OffsetDate]);
@override
String get wireName => 'OffsetDate';
@override
OffsetDate deserialize(Serializers serializers, Object serialized,
{FullType specifiedType = FullType.unspecified}) {
final local = LocalDate.dateTime(DateTime.parse(serialized as String));
return OffsetDate(local, Offset(0));
}
@override
Object serialize(Serializers serializers, OffsetDate offsetDate,
{FullType specifiedType = FullType.unspecified}) {
return offsetDate.toString('yyyy-MM-dd');
}
}
class OffsetDateTimeSerializer implements PrimitiveSerializer<OffsetDateTime> {
const OffsetDateTimeSerializer();
@override
Iterable<Type> get types => BuiltList<Type>([OffsetDateTime]);
@override
String get wireName => 'OffsetDateTime';
@override
OffsetDateTime deserialize(Serializers serializers, Object serialized,
{FullType specifiedType = FullType.unspecified}) {
final local = LocalDateTime.dateTime(DateTime.parse(serialized as String));
return OffsetDateTime(local, Offset(0));
}
@override
Object serialize(Serializers serializers, OffsetDateTime offsetDateTime,
{FullType specifiedType = FullType.unspecified}) {
return offsetDateTime.toString();
}
}

View File

@ -0,0 +1,21 @@
{{#hasFormParams}}
_bodyData = {{#isMultipart}}FormData.fromMap({{/isMultipart}}<String, dynamic>{
{{#formParams}}
{{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}MultipartFile.fromBytes({{{paramName}}}, filename: r'{{{baseName}}}'){{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}},
{{/formParams}}
}{{#isMultipart}}){{/isMultipart}};
{{/hasFormParams}}
{{#bodyParam}}
{{#isPrimitiveType}}
_bodyData = {{paramName}};
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isContainer}}
const _type = FullType(Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]);
{{/isContainer}}
{{^isContainer}}
const _type = FullType({{{baseType}}});
{{/isContainer}}
_bodyData = {{^required}}{{paramName}} == null ? null : {{/required}}_serializers.serialize({{paramName}}, specifiedType: _type);
{{/isPrimitiveType}}
{{/bodyParam}}

View File

@ -0,0 +1,33 @@
{{>header}}
import 'package:built_collection/built_collection.dart';
import 'package:built_value/json_object.dart';
import 'package:built_value/serializer.dart';
import 'package:built_value/standard_json_plugin.dart';
{{#useDateLibCore}}import 'package:built_value/iso_8601_date_time_serializer.dart';{{/useDateLibCore}}
{{#useDateLibTimeMachine}}import 'package:time_machine/time_machine.dart';
import 'package:{{pubName}}/src/local_date_serializer.dart';{{/useDateLibTimeMachine}}
{{#models}}{{#model}}import 'package:{{pubName}}/src/model/{{classFilename}}.dart';
{{/model}}{{/models}}
part 'serializers.g.dart';
@SerializersFor([{{#models}}{{#model}}
{{classname}},{{/model}}{{/models}}
])
Serializers serializers = (_$serializers.toBuilder(){{#apiInfo}}{{#apis}}{{#serializers}}
..addBuilderFactory(
{{#isArray}}
const FullType(Built{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType({{baseType}})]),
() => {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}Builder<{{baseType}}>(),
{{/isArray}}
{{#isMap}}
const FullType(BuiltMap, [FullType(String), FullType({{baseType}})]),
() => MapBuilder<String, {{baseType}}>(),
{{/isMap}}
){{/serializers}}{{/apis}}{{/apiInfo}}{{#useDateLibTimeMachine}}
..add(const OffsetDateSerializer())
..add(const OffsetDateTimeSerializer()){{/useDateLibTimeMachine}}
..add(Iso8601DateTimeSerializer()))
.build();
Serializers standardSerializers =
(serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

View File

@ -1,12 +0,0 @@
part of {{pubName}}.api;
{{#models}}
{{#model}}
{{#isEnum}}
{{>enum}}
{{/isEnum}}
{{^isEnum}}
{{>class}}
{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -1,26 +0,0 @@
{{#models}}
{{#model}}
import 'package:{{pubName}}/api.dart';
import 'package:test/test.dart';
// tests for {{classname}}
void main() {
var instance = new {{classname}}();
group('test {{classname}}', () {
{{#vars}}
{{#description}}
// {{{description}}}
{{/description}}
// {{{dataType}}} {{name}}{{#defaultValue}} (default value: {{{.}}}){{/defaultValue}}
test('to test the property `{{name}}`', () async {
// TODO
});
{{/vars}}
});
}
{{/model}}
{{/models}}

View File

@ -1,7 +0,0 @@
name: {{pubName}}
version: {{pubVersion}}
description: {{pubDescription}}
dependencies:
http: '>=0.11.1 <0.13.0'
dev_dependencies:
test: ^1.3.0

View File

@ -1,11 +0,0 @@
# https://docs.travis-ci.com/user/languages/dart/
#
language: dart
dart:
# Install a specific stable release
- "1.24.3"
install:
- pub get
script:
- pub run test

View File

@ -10,7 +10,7 @@ All URIs are relative to *{{{basePath}}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationId}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}}
{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationIdLowerCase}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}

View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.openapitools.codegen.dartdio;
package org.openapitools.codegen.dart.dio;
import java.io.BufferedReader;
import java.io.FileInputStream;

View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.openapitools.codegen.dartdio;
package org.openapitools.codegen.dart.dio;
import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;

View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.openapitools.codegen.dartdio;
package org.openapitools.codegen.dart.dio;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;

View File

@ -0,0 +1,86 @@
/*
* Copyright 2021 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.dart.dio;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.languages.DartDioClientCodegen;
import org.openapitools.codegen.languages.DartDioNextClientCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DartDioNextClientCodegenTest {
@Test
public void testInitialConfigValues() throws Exception {
final DartDioNextClientCodegen codegen = new DartDioNextClientCodegen();
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE);
Assert.assertEquals(codegen.isHideGenerationTimestamp(), true);
}
@Test
public void testSettersForConfigValues() throws Exception {
final DartDioClientCodegen codegen = new DartDioClientCodegen();
codegen.setHideGenerationTimestamp(false);
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE);
Assert.assertEquals(codegen.isHideGenerationTimestamp(), false);
}
@Test
public void testAdditionalPropertiesPutForConfigValues() throws Exception {
final DartDioClientCodegen codegen = new DartDioClientCodegen();
codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, false);
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE);
Assert.assertEquals(codegen.isHideGenerationTimestamp(), false);
}
@Test
public void testKeywords() throws Exception {
final DartDioClientCodegen codegen = new DartDioClientCodegen();
List<String> reservedWordsList = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/main/resources/dart/dart-keywords.txt"), Charset.forName("UTF-8")));
while(reader.ready()) { reservedWordsList.add(reader.readLine()); }
reader.close();
} catch (Exception e) {
String errorString = String.format(Locale.ROOT, "Error reading dart keywords: %s", e);
Assert.fail(errorString, e);
}
Assert.assertEquals(reservedWordsList.size() > 20, true);
Assert.assertEquals(codegen.reservedWords().size() == reservedWordsList.size(), true);
for(String keyword : reservedWordsList) {
// reserved words are stored in lowercase
Assert.assertEquals(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), true, String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString()));
}
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright 2021 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.dart.dio;
import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.DartDioNextClientCodegen;
import org.openapitools.codegen.options.DartDioNextClientOptionsProvider;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DartDioNextClientOptionsTest extends AbstractOptionsTest {
private DartDioNextClientCodegen clientCodegen = mock(DartDioNextClientCodegen.class, mockSettings);
public DartDioNextClientOptionsTest() {
super(new DartDioNextClientOptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void verifyOptions() {
verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(DartDioNextClientOptionsProvider.SORT_PARAMS_VALUE));
verify(clientCodegen).setPubLibrary(DartDioNextClientOptionsProvider.PUB_LIBRARY_VALUE);
verify(clientCodegen).setPubName(DartDioNextClientOptionsProvider.PUB_NAME_VALUE);
verify(clientCodegen).setPubVersion(DartDioNextClientOptionsProvider.PUB_VERSION_VALUE);
verify(clientCodegen).setPubDescription(DartDioNextClientOptionsProvider.PUB_DESCRIPTION_VALUE);
verify(clientCodegen).setPubAuthor(DartDioNextClientOptionsProvider.PUB_AUTHOR_VALUE);
verify(clientCodegen).setPubAuthorEmail(DartDioNextClientOptionsProvider.PUB_AUTHOR_EMAIL_VALUE);
verify(clientCodegen).setPubHomepage(DartDioNextClientOptionsProvider.PUB_HOMEPAGE_VALUE);
verify(clientCodegen).setSourceFolder(DartDioNextClientOptionsProvider.SOURCE_FOLDER_VALUE);
verify(clientCodegen).setUseEnumExtension(Boolean.parseBoolean(DartDioNextClientOptionsProvider.USE_ENUM_EXTENSION));
verify(clientCodegen).setDateLibrary(DartDioNextClientCodegen.DATE_LIBRARY_DEFAULT);
verify(clientCodegen).setLibrary(DartDioNextClientCodegen.SERIALIZATION_LIBRARY_DEFAULT);
}
}

View File

@ -0,0 +1,494 @@
/*
* Copyright 2021 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.dart.dio;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.DartDioNextClientCodegen;
import org.openapitools.codegen.languages.DartDioNextClientCodegen;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class DartDioNextModelTest {
@Test(description = "convert a simple model")
public void simpleModelTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema())
.addProperties("name", new StringSchema())
.addProperties("createdAt", new DateTimeSchema())
.addRequiredItem("id")
.addRequiredItem("name");
final DefaultCodegen codegen = new DartDioNextClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 3);
// {{imports}} is not used in template
//Assert.assertEquals(cm.imports.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.dataType, "String");
Assert.assertEquals(property2.name, "name");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "String");
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertFalse(property2.isContainer);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.complexType, "DateTime");
Assert.assertEquals(property3.dataType, "DateTime");
Assert.assertEquals(property3.name, "createdAt");
Assert.assertNull(property3.defaultValue);
Assert.assertEquals(property3.baseType, "DateTime");
Assert.assertFalse(property3.required);
Assert.assertFalse(property3.isContainer);
}
@Test(description = "convert a simple dart-dit model with datelibrary")
public void simpleModelWithTimeMachineTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema())
.addProperties("name", new StringSchema())
.addProperties("createdAt", new DateTimeSchema())
.addProperties("birthDate", new DateSchema())
.addRequiredItem("id")
.addRequiredItem("name");
final DartDioNextClientCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(DartDioNextClientCodegen.DATE_LIBRARY, DartDioNextClientCodegen.DATE_LIBRARY_TIME_MACHINE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 4);
// {{imports}} is not used in template
//Assert.assertEquals(cm.imports.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.dataType, "String");
Assert.assertEquals(property2.name, "name");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "String");
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertFalse(property2.isContainer);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.complexType, "OffsetDateTime");
Assert.assertEquals(property3.dataType, "OffsetDateTime");
Assert.assertEquals(property3.name, "createdAt");
Assert.assertNull(property3.defaultValue);
Assert.assertEquals(property3.baseType, "OffsetDateTime");
Assert.assertFalse(property3.required);
Assert.assertFalse(property3.isContainer);
final CodegenProperty property4 = cm.vars.get(3);
Assert.assertEquals(property4.baseName, "birthDate");
Assert.assertEquals(property4.complexType, "OffsetDate");
Assert.assertEquals(property4.dataType, "OffsetDate");
Assert.assertEquals(property4.name, "birthDate");
Assert.assertNull(property4.defaultValue);
Assert.assertEquals(property4.baseType, "OffsetDate");
Assert.assertFalse(property4.required);
Assert.assertFalse(property4.isContainer);
}
@Test(description = "convert a model with list property")
public void listPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema())
.addProperties("urls", new ArraySchema()
.items(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 2);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.dataType, "BuiltList<String>");
Assert.assertEquals(property2.name, "urls");
Assert.assertEquals(property2.baseType, "BuiltList");
Assert.assertEquals(property2.containerType, "array");
Assert.assertFalse(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with set property")
public void setPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema())
.addProperties("urls", new ArraySchema().items(new StringSchema()).uniqueItems(true))
.addRequiredItem("id");
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 2);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.dataType, "BuiltSet<String>");
Assert.assertEquals(property2.name, "urls");
Assert.assertEquals(property2.baseType, "BuiltSet");
Assert.assertEquals(property2.containerType, "set");
Assert.assertFalse(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("translations", new MapSchema()
.additionalProperties(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "translations");
Assert.assertEquals(property1.dataType, "BuiltMap<String, String>");
Assert.assertEquals(property1.name, "translations");
Assert.assertEquals(property1.baseType, "BuiltMap");
Assert.assertEquals(property1.containerType, "map");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
Assert.assertTrue(property1.isPrimitiveType);
}
@Test(description = "convert a model with complex property")
public void complexPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.dataType, "Children");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "Children");
Assert.assertFalse(property1.required);
Assert.assertFalse(property1.isContainer);
}
@Test(description = "convert a model with complex list property")
public void complexListProperty() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new ArraySchema()
.items(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.dataType, "BuiltList<Children>");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "BuiltList");
Assert.assertEquals(property1.containerType, "array");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert a model with complex map property")
public void complexMapSchema() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new MapSchema()
.additionalProperties(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.dataType, "BuiltMap<String, Children>");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "BuiltMap");
Assert.assertEquals(property1.containerType, "map");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert an array model")
public void arrayModelTest() {
final Schema model = new ArraySchema()
.items(new Schema().$ref("#/definitions/Children"))
.description("an array model");
final DefaultCodegen codegen = new DartDioNextClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(model.getDescription(), "an array model");
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertTrue(cm.isArray);
Assert.assertEquals(cm.description, "an array model");
Assert.assertEquals(cm.vars.size(), 0);
}
@Test(description = "convert a map model")
public void mapModelTest() {
final Schema model = new Schema()
.description("a map model")
.additionalProperties(new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new DartDioNextClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a map model");
Assert.assertEquals(cm.vars.size(), 0);
}
@DataProvider(name = "modelNames")
public static Object[][] modelNames() {
return new Object[][] {
{"EnumClass", "ModelEnumClass"},
{"JsonObject", "ModelJsonObject"},
// OffsetDate is valid without timemachine date library
{"OffsetDate", "OffsetDate"},
};
}
@Test(dataProvider = "modelNames", description = "correctly prefix reserved model names")
public void modelNameTest(String name, String expectedName) {
OpenAPI openAPI = TestUtils.createOpenAPI();
final Schema model = new Schema();
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.processOpts();
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel(name, model);
Assert.assertEquals(cm.name, name);
Assert.assertEquals(cm.classname, expectedName);
}
@DataProvider(name = "modelNamesTimemachine")
public static Object[][] modelNamesTimemachine() {
return new Object[][] {
{"EnumClass", "ModelEnumClass"},
{"JsonObject", "ModelJsonObject"},
// OffsetDate is not valid with timemachine date library
{"OffsetDate", "ModelOffsetDate"},
};
}
@Test(dataProvider = "modelNamesTimemachine", description = "correctly prefix reserved model names")
public void modelNameTestTimemachine(String name, String expectedName) {
OpenAPI openAPI = TestUtils.createOpenAPI();
final Schema model = new Schema();
final DartDioNextClientCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(DartDioNextClientCodegen.DATE_LIBRARY, DartDioNextClientCodegen.DATE_LIBRARY_TIME_MACHINE);
codegen.processOpts();
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel(name, model);
Assert.assertEquals(cm.name, name);
Assert.assertEquals(cm.classname, expectedName);
}
@Test(description = "correctly generate collection default values")
public void collectionDefaultValues() {
final ArraySchema array = new ArraySchema();
array.setDefault("[]");
final Schema model = new Schema()
.description("a sample model")
.addProperties("arrayNoDefault", new ArraySchema())
.addProperties("arrayEmptyDefault", array)
.addProperties("mapNoDefault", new MapSchema());
final DefaultCodegen codegen = new DartDioNextClientCodegen();
codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_BUILT_VALUE);
codegen.setOpenAPI(TestUtils.createOpenAPIWithOneSchema("sample", model));
codegen.processOpts();
final CodegenModel cm = codegen.fromModel("sample", model);
final CodegenProperty arrayNoDefault = cm.vars.get(0);
Assert.assertEquals(arrayNoDefault.name, "arrayNoDefault");
Assert.assertNull(arrayNoDefault.defaultValue);
final CodegenProperty arrayEmptyDefault = cm.vars.get(1);
Assert.assertEquals(arrayEmptyDefault.name, "arrayEmptyDefault");
Assert.assertEquals(arrayEmptyDefault.defaultValue, "ListBuilder()");
final CodegenProperty mapNoDefault = cm.vars.get(2);
Assert.assertEquals(mapNoDefault.name, "mapNoDefault");
Assert.assertNull(mapNoDefault.defaultValue);
}
@Test(description = "correctly generate date/datetime default values, currently null")
public void dateDefaultValues() {
final DateSchema date = new DateSchema();
date.setDefault("2021-01-01");
final DateTimeSchema dateTime = new DateTimeSchema();
dateTime.setDefault("2021-01-01T14:00:00Z");
final Schema model = new Schema()
.description("a sample model")
.addProperties("date", date)
.addProperties("dateTime", dateTime)
.addProperties("mapNoDefault", new MapSchema());
final DefaultCodegen codegen = new DartDioNextClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
final CodegenProperty dateDefault = cm.vars.get(0);
Assert.assertEquals(dateDefault.name, "date");
Assert.assertNull(dateDefault.defaultValue);
final CodegenProperty dateTimeDefault = cm.vars.get(1);
Assert.assertEquals(dateTimeDefault.name, "dateTime");
Assert.assertNull(dateTimeDefault.defaultValue);
}
}

View File

@ -31,7 +31,7 @@ public class DartDioClientOptionsProvider implements OptionsProvider {
public static final String PUB_LIBRARY_VALUE = "openapi.api";
public static final String PUB_NAME_VALUE = "openapi";
public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String PUB_DESCRIPTION_VALUE = "OpenAPI API client dart";
public static final String PUB_DESCRIPTION_VALUE = "OpenAPI API client dart-dio";
public static final String SOURCE_FOLDER_VALUE = "src";
public static final String USE_ENUM_EXTENSION = "true";
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";

View File

@ -0,0 +1,74 @@
/*
* Copyright 2021 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.options;
import com.google.common.collect.ImmutableMap;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.languages.DartDioNextClientCodegen;
import java.util.Map;
public class DartDioNextClientOptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "true";
public static final String SORT_MODEL_PROPERTIES_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String PUB_LIBRARY_VALUE = "openapi.api";
public static final String PUB_NAME_VALUE = "openapi";
public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String PUB_DESCRIPTION_VALUE = "OpenAPI API client dart-dio";
public static final String SOURCE_FOLDER_VALUE = "src";
public static final String USE_ENUM_EXTENSION = "true";
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
public static final String PUB_AUTHOR_VALUE = "Author";
public static final String PUB_AUTHOR_EMAIL_VALUE = "author@homepage";
public static final String PUB_HOMEPAGE_VALUE = "Homepage";
@Override
public String getLanguage() {
return "dart-dio-next";
}
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(DartDioNextClientCodegen.PUB_LIBRARY, PUB_LIBRARY_VALUE)
.put(DartDioNextClientCodegen.PUB_NAME, PUB_NAME_VALUE)
.put(DartDioNextClientCodegen.PUB_VERSION, PUB_VERSION_VALUE)
.put(DartDioNextClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE)
.put(DartDioNextClientCodegen.PUB_AUTHOR, PUB_AUTHOR_VALUE)
.put(DartDioNextClientCodegen.PUB_AUTHOR_EMAIL, PUB_AUTHOR_EMAIL_VALUE)
.put(DartDioNextClientCodegen.PUB_HOMEPAGE, PUB_HOMEPAGE_VALUE)
.put(CodegenConstants.SERIALIZATION_LIBRARY, DartDioNextClientCodegen.SERIALIZATION_LIBRARY_DEFAULT)
.put(DartDioNextClientCodegen.DATE_LIBRARY, DartDioNextClientCodegen.DATE_LIBRARY_DEFAULT)
.put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE)
.put(DartDioNextClientCodegen.USE_ENUM_EXTENSION, USE_ENUM_EXTENSION)
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
.put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true")
.put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true")
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@ -1360,6 +1360,7 @@
<module>samples/client/petstore/dart-dio/petstore_client_lib</module>
<module>samples/openapi3/client/petstore/dart-dio/petstore_client_lib</module>
<module>samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake</module>
<module>samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake</module>
<module>samples/client/petstore/dart-jaguar/openapi</module>
<module>samples/client/petstore/dart-jaguar/flutter_petstore/openapi</module>
</modules>

View File

@ -40,11 +40,11 @@ Please follow the [installation procedure](#installation--usage) and then run th
import 'package:openapi/api.dart';
var api_instance = new PetApi();
var body = new Pet(); // Pet | Pet object that needs to be added to the store
final api = PetApi();
final body = Pet(); // Pet | Pet object that needs to be added to the store
try {
api_instance.addPet(body);
api.addPet(body);
} catch (e) {
print("Exception when calling PetApi->addPet: $e\n");
}
@ -57,36 +57,36 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**addPet**](doc//PetApi.md#addpet) | **post** /pet | Add a new pet to the store
*PetApi* | [**deletePet**](doc//PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet
*PetApi* | [**findPetsByStatus**](doc//PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status
*PetApi* | [**findPetsByTags**](doc//PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags
*PetApi* | [**getPetById**](doc//PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID
*PetApi* | [**updatePet**](doc//PetApi.md#updatepet) | **put** /pet | Update an existing pet
*PetApi* | [**updatePetWithForm**](doc//PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**uploadFile**](doc//PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**deleteOrder**](doc//StoreApi.md#deleteorder) | **delete** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**getInventory**](doc//StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status
*StoreApi* | [**getOrderById**](doc//StoreApi.md#getorderbyid) | **get** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**placeOrder**](doc//StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet
*UserApi* | [**createUser**](doc//UserApi.md#createuser) | **post** /user | Create user
*UserApi* | [**createUsersWithArrayInput**](doc//UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**createUsersWithListInput**](doc//UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array
*UserApi* | [**deleteUser**](doc//UserApi.md#deleteuser) | **delete** /user/{username} | Delete user
*UserApi* | [**getUserByName**](doc//UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name
*UserApi* | [**loginUser**](doc//UserApi.md#loginuser) | **get** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](doc//UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](doc//UserApi.md#updateuser) | **put** /user/{username} | Updated user
*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store
*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet
*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status
*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags
*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID
*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet
*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status
*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet
*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user
*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array
*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user
*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name
*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user
## Documentation For Models
- [ApiResponse](doc//ApiResponse.md)
- [Category](doc//Category.md)
- [Order](doc//Order.md)
- [Pet](doc//Pet.md)
- [Tag](doc//Tag.md)
- [User](doc//User.md)
- [ApiResponse](doc/ApiResponse.md)
- [Category](doc/Category.md)
- [Order](doc/Order.md)
- [Pet](doc/Pet.md)
- [Tag](doc/Tag.md)
- [User](doc/User.md)
## Documentation For Authorization

View File

@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**addPet**](PetApi.md#addPet) | **post** /pet | Add a new pet to the store
[**deletePet**](PetApi.md#deletePet) | **delete** /pet/{petId} | Deletes a pet
[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **get** /pet/findByStatus | Finds Pets by status
[**findPetsByTags**](PetApi.md#findPetsByTags) | **get** /pet/findByTags | Finds Pets by tags
[**getPetById**](PetApi.md#getPetById) | **get** /pet/{petId} | Find pet by ID
[**updatePet**](PetApi.md#updatePet) | **put** /pet | Update an existing pet
[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **post** /pet/{petId} | Updates a pet in the store with form data
[**uploadFile**](PetApi.md#uploadFile) | **post** /pet/{petId}/uploadImage | uploads an image
[**addPet**](PetApi.md#addpet) | **post** /pet | Add a new pet to the store
[**deletePet**](PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet
[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status
[**findPetsByTags**](PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags
[**getPetById**](PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID
[**updatePet**](PetApi.md#updatepet) | **put** /pet | Update an existing pet
[**updatePetWithForm**](PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data
[**uploadFile**](PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image
# **addPet**

View File

@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**deleteOrder**](StoreApi.md#deleteOrder) | **delete** /store/order/{orderId} | Delete purchase order by ID
[**getInventory**](StoreApi.md#getInventory) | **get** /store/inventory | Returns pet inventories by status
[**getOrderById**](StoreApi.md#getOrderById) | **get** /store/order/{orderId} | Find purchase order by ID
[**placeOrder**](StoreApi.md#placeOrder) | **post** /store/order | Place an order for a pet
[**deleteOrder**](StoreApi.md#deleteorder) | **delete** /store/order/{orderId} | Delete purchase order by ID
[**getInventory**](StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status
[**getOrderById**](StoreApi.md#getorderbyid) | **get** /store/order/{orderId} | Find purchase order by ID
[**placeOrder**](StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet
# **deleteOrder**

View File

@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**createUser**](UserApi.md#createUser) | **post** /user | Create user
[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **post** /user/createWithArray | Creates list of users with given input array
[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **post** /user/createWithList | Creates list of users with given input array
[**deleteUser**](UserApi.md#deleteUser) | **delete** /user/{username} | Delete user
[**getUserByName**](UserApi.md#getUserByName) | **get** /user/{username} | Get user by user name
[**loginUser**](UserApi.md#loginUser) | **get** /user/login | Logs user into the system
[**logoutUser**](UserApi.md#logoutUser) | **get** /user/logout | Logs out current logged in user session
[**updateUser**](UserApi.md#updateUser) | **put** /user/{username} | Updated user
[**createUser**](UserApi.md#createuser) | **post** /user | Create user
[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array
[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array
[**deleteUser**](UserApi.md#deleteuser) | **delete** /user/{username} | Delete user
[**getUserByName**](UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name
[**loginUser**](UserApi.md#loginuser) | **get** /user/login | Logs user into the system
[**logoutUser**](UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session
[**updateUser**](UserApi.md#updateuser) | **put** /user/{username} | Updated user
# **createUser**

View File

@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store
[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet
[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID
[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet
[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
[**addPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store
[**deletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet
[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status
[**findPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags
[**getPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID
[**updatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet
[**updatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data
[**uploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image
# **addPet**

View File

@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status
[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID
[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet
[**deleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
[**getInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status
[**getOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID
[**placeOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet
# **deleteOrder**

View File

@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**createUser**](UserApi.md#createUser) | **POST** /user | Create user
[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array
[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array
[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user
[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name
[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system
[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session
[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user
[**createUser**](UserApi.md#createuser) | **POST** /user | Create user
[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array
[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array
[**deleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user
[**getUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name
[**loginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system
[**logoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session
[**updateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user
# **createUser**

View File

@ -0,0 +1,37 @@
# See https://dart.dev/guides/libraries/private-files
# Files and directories created by pub
.dart_tool/
.buildlog
.packages
.project
.pub/
build/
**/packages/
# Files created by dart2js
# (Most Dart developers will use pub build to compile Dart, use/modify these
# rules if you intend to use dart2js directly
# Convention is to use extension '.dart.js' for Dart compiled to Javascript to
# differentiate from explicit Javascript files)
*.dart.js
*.part.js
*.js.deps
*.js.map
*.info.json
# Directory created by dartdoc
doc/api/
# Don't commit pubspec lock file
# (Library packages only! Remove pattern if developing an application package)
pubspec.lock
# Dont commit files and directories created by other development environments.
# For example, if your development environment creates any of the following files,
# consider putting them in a global ignore file:
*.iml // IntelliJ
*.ipr // IntelliJ
*.iws // IntelliJ
.idea/ // IntelliJ
.DS_Store // Mac

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,114 @@
.gitignore
README.md
analysis_options.yaml
doc/AdditionalPropertiesClass.md
doc/Animal.md
doc/AnotherFakeApi.md
doc/ApiResponse.md
doc/ArrayOfArrayOfNumberOnly.md
doc/ArrayOfNumberOnly.md
doc/ArrayTest.md
doc/Capitalization.md
doc/Cat.md
doc/CatAllOf.md
doc/Category.md
doc/ClassModel.md
doc/DefaultApi.md
doc/Dog.md
doc/DogAllOf.md
doc/EnumArrays.md
doc/EnumTest.md
doc/FakeApi.md
doc/FakeClassnameTags123Api.md
doc/FileSchemaTestClass.md
doc/Foo.md
doc/FormatTest.md
doc/HasOnlyReadOnly.md
doc/HealthCheckResult.md
doc/InlineResponseDefault.md
doc/MapTest.md
doc/MixedPropertiesAndAdditionalPropertiesClass.md
doc/Model200Response.md
doc/ModelClient.md
doc/ModelEnumClass.md
doc/ModelFile.md
doc/ModelList.md
doc/ModelReturn.md
doc/Name.md
doc/NullableClass.md
doc/NumberOnly.md
doc/Order.md
doc/OuterComposite.md
doc/OuterEnum.md
doc/OuterEnumDefaultValue.md
doc/OuterEnumInteger.md
doc/OuterEnumIntegerDefaultValue.md
doc/OuterObjectWithEnumProperty.md
doc/Pet.md
doc/PetApi.md
doc/ReadOnlyFirst.md
doc/SpecialModelName.md
doc/StoreApi.md
doc/Tag.md
doc/User.md
doc/UserApi.md
lib/openapi.dart
lib/src/api.dart
lib/src/api/another_fake_api.dart
lib/src/api/default_api.dart
lib/src/api/fake_api.dart
lib/src/api/fake_classname_tags123_api.dart
lib/src/api/pet_api.dart
lib/src/api/store_api.dart
lib/src/api/user_api.dart
lib/src/api_util.dart
lib/src/auth/api_key_auth.dart
lib/src/auth/auth.dart
lib/src/auth/basic_auth.dart
lib/src/auth/oauth.dart
lib/src/model/additional_properties_class.dart
lib/src/model/animal.dart
lib/src/model/api_response.dart
lib/src/model/array_of_array_of_number_only.dart
lib/src/model/array_of_number_only.dart
lib/src/model/array_test.dart
lib/src/model/capitalization.dart
lib/src/model/cat.dart
lib/src/model/cat_all_of.dart
lib/src/model/category.dart
lib/src/model/class_model.dart
lib/src/model/dog.dart
lib/src/model/dog_all_of.dart
lib/src/model/enum_arrays.dart
lib/src/model/enum_test.dart
lib/src/model/file_schema_test_class.dart
lib/src/model/foo.dart
lib/src/model/format_test.dart
lib/src/model/has_only_read_only.dart
lib/src/model/health_check_result.dart
lib/src/model/inline_response_default.dart
lib/src/model/map_test.dart
lib/src/model/mixed_properties_and_additional_properties_class.dart
lib/src/model/model200_response.dart
lib/src/model/model_client.dart
lib/src/model/model_enum_class.dart
lib/src/model/model_file.dart
lib/src/model/model_list.dart
lib/src/model/model_return.dart
lib/src/model/name.dart
lib/src/model/nullable_class.dart
lib/src/model/number_only.dart
lib/src/model/order.dart
lib/src/model/outer_composite.dart
lib/src/model/outer_enum.dart
lib/src/model/outer_enum_default_value.dart
lib/src/model/outer_enum_integer.dart
lib/src/model/outer_enum_integer_default_value.dart
lib/src/model/outer_object_with_enum_property.dart
lib/src/model/pet.dart
lib/src/model/read_only_first.dart
lib/src/model/special_model_name.dart
lib/src/model/tag.dart
lib/src/model/user.dart
lib/src/serializers.dart
pubspec.yaml

View File

@ -0,0 +1,194 @@
# openapi (EXPERIMENTAL)
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
This Dart package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 1.0.0
- Build package: org.openapitools.codegen.languages.DartDioNextClientCodegen
## Requirements
* Dart 2.12.0 or later OR Flutter 1.26.0 or later
* Dio 4.0.0+
* timemachine option currently **DOES NOT** support sound null-safety and may not work
## Installation & Usage
### Github
If this Dart package is published to Github, please include the following in pubspec.yaml
```
name: openapi
version: 1.0.0
description: OpenAPI API client
dependencies:
openapi:
git: https://github.com/GIT_USER_ID/GIT_REPO_ID.git
version: 'any'
```
### Local
To use the package in your local drive, please include the following in pubspec.yaml
```
dependencies:
openapi:
path: /path/to/openapi
```
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```dart
import 'package:openapi/openapi.dart';
final api = AnotherFakeApi();
final modelClient = ModelClient(); // ModelClient | client model
try {
final response = await api.call123testSpecialTags(modelClient);
print(response);
} catch on DioError (e) {
print("Exception when calling AnotherFakeApi->call123testSpecialTags: $e\n");
}
```
## Documentation for API Endpoints
All URIs are relative to *http://petstore.swagger.io:80/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags
*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **get** /foo |
*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint
*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication
*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean |
*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite |
*FakeApi* | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **post** /fake/outer/number |
*FakeApi* | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **post** /fake/outer/string |
*FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **post** /fake/property/enum-int |
*FakeApi* | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema |
*FakeApi* | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params |
*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **patch** /fake | To test \&quot;client\&quot; model
*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters
*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional)
*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties
*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data
*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters |
*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case
*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store
*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet
*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status
*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags
*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID
*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet
*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image
*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required)
*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID
*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status
*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID
*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet
*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user
*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array
*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user
*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name
*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user
## Documentation For Models
- [AdditionalPropertiesClass](doc/AdditionalPropertiesClass.md)
- [Animal](doc/Animal.md)
- [ApiResponse](doc/ApiResponse.md)
- [ArrayOfArrayOfNumberOnly](doc/ArrayOfArrayOfNumberOnly.md)
- [ArrayOfNumberOnly](doc/ArrayOfNumberOnly.md)
- [ArrayTest](doc/ArrayTest.md)
- [Capitalization](doc/Capitalization.md)
- [Cat](doc/Cat.md)
- [CatAllOf](doc/CatAllOf.md)
- [Category](doc/Category.md)
- [ClassModel](doc/ClassModel.md)
- [Dog](doc/Dog.md)
- [DogAllOf](doc/DogAllOf.md)
- [EnumArrays](doc/EnumArrays.md)
- [EnumTest](doc/EnumTest.md)
- [FileSchemaTestClass](doc/FileSchemaTestClass.md)
- [Foo](doc/Foo.md)
- [FormatTest](doc/FormatTest.md)
- [HasOnlyReadOnly](doc/HasOnlyReadOnly.md)
- [HealthCheckResult](doc/HealthCheckResult.md)
- [InlineResponseDefault](doc/InlineResponseDefault.md)
- [MapTest](doc/MapTest.md)
- [MixedPropertiesAndAdditionalPropertiesClass](doc/MixedPropertiesAndAdditionalPropertiesClass.md)
- [Model200Response](doc/Model200Response.md)
- [ModelClient](doc/ModelClient.md)
- [ModelEnumClass](doc/ModelEnumClass.md)
- [ModelFile](doc/ModelFile.md)
- [ModelList](doc/ModelList.md)
- [ModelReturn](doc/ModelReturn.md)
- [Name](doc/Name.md)
- [NullableClass](doc/NullableClass.md)
- [NumberOnly](doc/NumberOnly.md)
- [Order](doc/Order.md)
- [OuterComposite](doc/OuterComposite.md)
- [OuterEnum](doc/OuterEnum.md)
- [OuterEnumDefaultValue](doc/OuterEnumDefaultValue.md)
- [OuterEnumInteger](doc/OuterEnumInteger.md)
- [OuterEnumIntegerDefaultValue](doc/OuterEnumIntegerDefaultValue.md)
- [OuterObjectWithEnumProperty](doc/OuterObjectWithEnumProperty.md)
- [Pet](doc/Pet.md)
- [ReadOnlyFirst](doc/ReadOnlyFirst.md)
- [SpecialModelName](doc/SpecialModelName.md)
- [Tag](doc/Tag.md)
- [User](doc/User.md)
## Documentation For Authorization
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## api_key_query
- **Type**: API key
- **API key parameter name**: api_key_query
- **Location**: URL query string
## bearer_test
- **Type**: HTTP basic authentication
## http_basic_test
- **Type**: HTTP basic authentication
## http_signature_test
- **Type**: HTTP basic authentication
## petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
- **Scopes**:
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
## Author

View File

@ -0,0 +1,9 @@
analyzer:
language:
strict-inference: true
strict-raw-types: true
strong-mode:
implicit-dynamic: false
implicit-casts: false
exclude:
- test/*.dart

View File

@ -0,0 +1,16 @@
# openapi.model.AdditionalPropertiesClass
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**mapProperty** | **BuiltMap<String, String>** | | [optional]
**mapOfMapProperty** | [**BuiltMap<String, BuiltMap<String, String>>**](BuiltMap.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# openapi.model.Animal
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**className** | **String** | |
**color** | **String** | | [optional] [default to 'red']
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,57 @@
# openapi.api.AnotherFakeApi
## Load the API package
```dart
import 'package:openapi/api.dart';
```
All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags
# **call123testSpecialTags**
> ModelClient call123testSpecialTags(modelClient)
To test special tags
To test special tags and operation ID starting with number
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new AnotherFakeApi();
var modelClient = new ModelClient(); // ModelClient | client model
try {
var result = api_instance.call123testSpecialTags(modelClient);
print(result);
} catch (e) {
print('Exception when calling AnotherFakeApi->call123testSpecialTags: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**modelClient** | [**ModelClient**](ModelClient.md)| client model |
### Return type
[**ModelClient**](ModelClient.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -0,0 +1,17 @@
# openapi.model.ApiResponse
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**code** | **int** | | [optional]
**type** | **String** | | [optional]
**message** | **String** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,15 @@
# openapi.model.ArrayOfArrayOfNumberOnly
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**arrayArrayNumber** | [**BuiltList<BuiltList<num>>**](BuiltList.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,15 @@
# openapi.model.ArrayOfNumberOnly
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**arrayNumber** | **BuiltList<num>** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,17 @@
# openapi.model.ArrayTest
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**arrayOfString** | **BuiltList<String>** | | [optional]
**arrayArrayOfInteger** | [**BuiltList<BuiltList<int>>**](BuiltList.md) | | [optional]
**arrayArrayOfModel** | [**BuiltList<BuiltList<ReadOnlyFirst>>**](BuiltList.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,20 @@
# openapi.model.Capitalization
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**smallCamel** | **String** | | [optional]
**capitalCamel** | **String** | | [optional]
**smallSnake** | **String** | | [optional]
**capitalSnake** | **String** | | [optional]
**sCAETHFlowPoints** | **String** | | [optional]
**ATT_NAME** | **String** | Name of the pet | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,17 @@
# openapi.model.Cat
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**className** | **String** | |
**color** | **String** | | [optional] [default to 'red']
**declawed** | **bool** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,15 @@
# openapi.model.CatAllOf
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**declawed** | **bool** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# openapi.model.Category
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **int** | | [optional]
**name** | **String** | | [default to 'default-name']
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,15 @@
# openapi.model.ClassModel
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**class_** | **String** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,51 @@
# openapi.api.DefaultApi
## Load the API package
```dart
import 'package:openapi/api.dart';
```
All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**fooGet**](DefaultApi.md#fooget) | **get** /foo |
# **fooGet**
> InlineResponseDefault fooGet()
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new DefaultApi();
try {
var result = api_instance.fooGet();
print(result);
} catch (e) {
print('Exception when calling DefaultApi->fooGet: $e\n');
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**InlineResponseDefault**](InlineResponseDefault.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -0,0 +1,17 @@
# openapi.model.Dog
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**className** | **String** | |
**color** | **String** | | [optional] [default to 'red']
**breed** | **String** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,15 @@
# openapi.model.DogAllOf
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**breed** | **String** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,16 @@
# openapi.model.EnumArrays
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**justSymbol** | **String** | | [optional]
**arrayEnum** | **BuiltList<String>** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,22 @@
# openapi.model.EnumTest
## Load the model package
```dart
import 'package:openapi/api.dart';
```
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**enumString** | **String** | | [optional]
**enumStringRequired** | **String** | |
**enumInteger** | **int** | | [optional]
**enumNumber** | **double** | | [optional]
**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional]
**outerEnumInteger** | [**OuterEnumInteger**](OuterEnumInteger.md) | | [optional]
**outerEnumDefaultValue** | [**OuterEnumDefaultValue**](OuterEnumDefaultValue.md) | | [optional]
**outerEnumIntegerDefaultValue** | [**OuterEnumIntegerDefaultValue**](OuterEnumIntegerDefaultValue.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,769 @@
# openapi.api.FakeApi
## Load the API package
```dart
import 'package:openapi/api.dart';
```
All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**fakeHealthGet**](FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint
[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication
[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean |
[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite |
[**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **post** /fake/outer/number |
[**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **post** /fake/outer/string |
[**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **post** /fake/property/enum-int |
[**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema |
[**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params |
[**testClientModel**](FakeApi.md#testclientmodel) | **patch** /fake | To test \&quot;client\&quot; model
[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
[**testEnumParameters**](FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters
[**testGroupParameters**](FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional)
[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties
[**testJsonFormData**](FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data
[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters |
# **fakeHealthGet**
> HealthCheckResult fakeHealthGet()
Health check endpoint
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
try {
var result = api_instance.fakeHealthGet();
print(result);
} catch (e) {
print('Exception when calling FakeApi->fakeHealthGet: $e\n');
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**HealthCheckResult**](HealthCheckResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **fakeHttpSignatureTest**
> fakeHttpSignatureTest(pet, query1, header1)
test http signature authentication
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure HTTP basic authorization: http_signature_test
//defaultApiClient.getAuthentication<HttpBasicAuth>('http_signature_test').username = 'YOUR_USERNAME'
//defaultApiClient.getAuthentication<HttpBasicAuth>('http_signature_test').password = 'YOUR_PASSWORD';
var api_instance = new FakeApi();
var pet = new Pet(); // Pet | Pet object that needs to be added to the store
var query1 = query1_example; // String | query parameter
var header1 = header1_example; // String | header parameter
try {
api_instance.fakeHttpSignatureTest(pet, query1, header1);
} catch (e) {
print('Exception when calling FakeApi->fakeHttpSignatureTest: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
**query1** | **String**| query parameter | [optional]
**header1** | **String**| header parameter | [optional]
### Return type
void (empty response body)
### Authorization
[http_signature_test](../README.md#http_signature_test)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **fakeOuterBooleanSerialize**
> bool fakeOuterBooleanSerialize(body)
Test serialization of outer boolean types
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var body = new bool(); // bool | Input boolean as post body
try {
var result = api_instance.fakeOuterBooleanSerialize(body);
print(result);
} catch (e) {
print('Exception when calling FakeApi->fakeOuterBooleanSerialize: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | **bool**| Input boolean as post body | [optional]
### Return type
**bool**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **fakeOuterCompositeSerialize**
> OuterComposite fakeOuterCompositeSerialize(outerComposite)
Test serialization of object with outer number type
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body
try {
var result = api_instance.fakeOuterCompositeSerialize(outerComposite);
print(result);
} catch (e) {
print('Exception when calling FakeApi->fakeOuterCompositeSerialize: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional]
### Return type
[**OuterComposite**](OuterComposite.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **fakeOuterNumberSerialize**
> num fakeOuterNumberSerialize(body)
Test serialization of outer number types
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var body = new num(); // num | Input number as post body
try {
var result = api_instance.fakeOuterNumberSerialize(body);
print(result);
} catch (e) {
print('Exception when calling FakeApi->fakeOuterNumberSerialize: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | **num**| Input number as post body | [optional]
### Return type
**num**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **fakeOuterStringSerialize**
> String fakeOuterStringSerialize(body)
Test serialization of outer string types
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var body = new String(); // String | Input string as post body
try {
var result = api_instance.fakeOuterStringSerialize(body);
print(result);
} catch (e) {
print('Exception when calling FakeApi->fakeOuterStringSerialize: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | **String**| Input string as post body | [optional]
### Return type
**String**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **fakePropertyEnumIntegerSerialize**
> OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty)
Test serialization of enum (int) properties with examples
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var outerObjectWithEnumProperty = new OuterObjectWithEnumProperty(); // OuterObjectWithEnumProperty | Input enum (int) as post body
try {
var result = api_instance.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty);
print(result);
} catch (e) {
print('Exception when calling FakeApi->fakePropertyEnumIntegerSerialize: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**outerObjectWithEnumProperty** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)| Input enum (int) as post body |
### Return type
[**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testBodyWithFileSchema**
> testBodyWithFileSchema(fileSchemaTestClass)
For this test, the body for this request much reference a schema named `File`.
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass |
try {
api_instance.testBodyWithFileSchema(fileSchemaTestClass);
} catch (e) {
print('Exception when calling FakeApi->testBodyWithFileSchema: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testBodyWithQueryParams**
> testBodyWithQueryParams(query, user)
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var query = query_example; // String |
var user = new User(); // User |
try {
api_instance.testBodyWithQueryParams(query, user);
} catch (e) {
print('Exception when calling FakeApi->testBodyWithQueryParams: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**query** | **String**| |
**user** | [**User**](User.md)| |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testClientModel**
> ModelClient testClientModel(modelClient)
To test \"client\" model
To test \"client\" model
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var modelClient = new ModelClient(); // ModelClient | client model
try {
var result = api_instance.testClientModel(modelClient);
print(result);
} catch (e) {
print('Exception when calling FakeApi->testClientModel: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**modelClient** | [**ModelClient**](ModelClient.md)| client model |
### Return type
[**ModelClient**](ModelClient.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testEndpointParameters**
> testEndpointParameters(number, double_, patternWithoutDelimiter, byte, integer, int32, int64, float, string, binary, date, dateTime, password, callback)
Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure HTTP basic authorization: http_basic_test
//defaultApiClient.getAuthentication<HttpBasicAuth>('http_basic_test').username = 'YOUR_USERNAME'
//defaultApiClient.getAuthentication<HttpBasicAuth>('http_basic_test').password = 'YOUR_PASSWORD';
var api_instance = new FakeApi();
var number = 8.14; // num | None
var double_ = 1.2; // double | None
var patternWithoutDelimiter = patternWithoutDelimiter_example; // String | None
var byte = BYTE_ARRAY_DATA_HERE; // String | None
var integer = 56; // int | None
var int32 = 56; // int | None
var int64 = 789; // int | None
var float = 3.4; // double | None
var string = string_example; // String | None
var binary = BINARY_DATA_HERE; // Uint8List | None
var date = 2013-10-20; // DateTime | None
var dateTime = 2013-10-20T19:20:30+01:00; // DateTime | None
var password = password_example; // String | None
var callback = callback_example; // String | None
try {
api_instance.testEndpointParameters(number, double_, patternWithoutDelimiter, byte, integer, int32, int64, float, string, binary, date, dateTime, password, callback);
} catch (e) {
print('Exception when calling FakeApi->testEndpointParameters: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**number** | **num**| None |
**double_** | **double**| None |
**patternWithoutDelimiter** | **String**| None |
**byte** | **String**| None |
**integer** | **int**| None | [optional]
**int32** | **int**| None | [optional]
**int64** | **int**| None | [optional]
**float** | **double**| None | [optional]
**string** | **String**| None | [optional]
**binary** | **Uint8List**| None | [optional]
**date** | **DateTime**| None | [optional]
**dateTime** | **DateTime**| None | [optional]
**password** | **String**| None | [optional]
**callback** | **String**| None | [optional]
### Return type
void (empty response body)
### Authorization
[http_basic_test](../README.md#http_basic_test)
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testEnumParameters**
> testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString)
To test enum parameters
To test enum parameters
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var enumHeaderStringArray = []; // BuiltList<String> | Header parameter enum test (string array)
var enumHeaderString = enumHeaderString_example; // String | Header parameter enum test (string)
var enumQueryStringArray = []; // BuiltList<String> | Query parameter enum test (string array)
var enumQueryString = enumQueryString_example; // String | Query parameter enum test (string)
var enumQueryInteger = 56; // int | Query parameter enum test (double)
var enumQueryDouble = 1.2; // double | Query parameter enum test (double)
var enumFormStringArray = [enumFormStringArray_example]; // BuiltList<String> | Form parameter enum test (string array)
var enumFormString = enumFormString_example; // String | Form parameter enum test (string)
try {
api_instance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString);
} catch (e) {
print('Exception when calling FakeApi->testEnumParameters: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**enumHeaderStringArray** | [**BuiltList<String>**](String.md)| Header parameter enum test (string array) | [optional]
**enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to '-efg']
**enumQueryStringArray** | [**BuiltList<String>**](String.md)| Query parameter enum test (string array) | [optional]
**enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to '-efg']
**enumQueryInteger** | **int**| Query parameter enum test (double) | [optional]
**enumQueryDouble** | **double**| Query parameter enum test (double) | [optional]
**enumFormStringArray** | [**BuiltList<String>**](String.md)| Form parameter enum test (string array) | [optional] [default to '$']
**enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to '-efg']
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testGroupParameters**
> testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group)
Fake endpoint to test group parameters (optional)
Fake endpoint to test group parameters (optional)
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure HTTP basic authorization: bearer_test
//defaultApiClient.getAuthentication<HttpBasicAuth>('bearer_test').username = 'YOUR_USERNAME'
//defaultApiClient.getAuthentication<HttpBasicAuth>('bearer_test').password = 'YOUR_PASSWORD';
var api_instance = new FakeApi();
var requiredStringGroup = 56; // int | Required String in group parameters
var requiredBooleanGroup = true; // bool | Required Boolean in group parameters
var requiredInt64Group = 789; // int | Required Integer in group parameters
var stringGroup = 56; // int | String in group parameters
var booleanGroup = true; // bool | Boolean in group parameters
var int64Group = 789; // int | Integer in group parameters
try {
api_instance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group);
} catch (e) {
print('Exception when calling FakeApi->testGroupParameters: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**requiredStringGroup** | **int**| Required String in group parameters |
**requiredBooleanGroup** | **bool**| Required Boolean in group parameters |
**requiredInt64Group** | **int**| Required Integer in group parameters |
**stringGroup** | **int**| String in group parameters | [optional]
**booleanGroup** | **bool**| Boolean in group parameters | [optional]
**int64Group** | **int**| Integer in group parameters | [optional]
### Return type
void (empty response body)
### Authorization
[bearer_test](../README.md#bearer_test)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testInlineAdditionalProperties**
> testInlineAdditionalProperties(requestBody)
test inline additionalProperties
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var requestBody = new BuiltMap<String, String>(); // BuiltMap<String, String> | request body
try {
api_instance.testInlineAdditionalProperties(requestBody);
} catch (e) {
print('Exception when calling FakeApi->testInlineAdditionalProperties: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**requestBody** | [**BuiltMap<String, String>**](String.md)| request body |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testJsonFormData**
> testJsonFormData(param, param2)
test json serialization of form data
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var param = param_example; // String | field1
var param2 = param2_example; // String | field2
try {
api_instance.testJsonFormData(param, param2);
} catch (e) {
print('Exception when calling FakeApi->testJsonFormData: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**param** | **String**| field1 |
**param2** | **String**| field2 |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **testQueryParameterCollectionFormat**
> testQueryParameterCollectionFormat(pipe, ioutil, http, url, context)
To test the collection format in query parameters
### Example
```dart
import 'package:openapi/api.dart';
var api_instance = new FakeApi();
var pipe = []; // BuiltList<String> |
var ioutil = []; // BuiltList<String> |
var http = []; // BuiltList<String> |
var url = []; // BuiltList<String> |
var context = []; // BuiltList<String> |
try {
api_instance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context);
} catch (e) {
print('Exception when calling FakeApi->testQueryParameterCollectionFormat: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**pipe** | [**BuiltList<String>**](String.md)| |
**ioutil** | [**BuiltList<String>**](String.md)| |
**http** | [**BuiltList<String>**](String.md)| |
**url** | [**BuiltList<String>**](String.md)| |
**context** | [**BuiltList<String>**](String.md)| |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@ -0,0 +1,61 @@
# openapi.api.FakeClassnameTags123Api
## Load the API package
```dart
import 'package:openapi/api.dart';
```
All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case
# **testClassname**
> ModelClient testClassname(modelClient)
To test class name in snake case
To test class name in snake case
### Example
```dart
import 'package:openapi/api.dart';
// TODO Configure API key authorization: api_key_query
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key_query').apiKey = 'YOUR_API_KEY';
// uncomment below to setup prefix (e.g. Bearer) for API key, if needed
//defaultApiClient.getAuthentication<ApiKeyAuth>('api_key_query').apiKeyPrefix = 'Bearer';
var api_instance = new FakeClassnameTags123Api();
var modelClient = new ModelClient(); // ModelClient | client model
try {
var result = api_instance.testClassname(modelClient);
print(result);
} catch (e) {
print('Exception when calling FakeClassnameTags123Api->testClassname: $e\n');
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**modelClient** | [**ModelClient**](ModelClient.md)| client model |
### Return type
[**ModelClient**](ModelClient.md)
### Authorization
[api_key_query](../README.md#api_key_query)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

Some files were not shown because too many files have changed in this diff Show More