diff --git a/.gitignore b/.gitignore index ddb360f16..7c675c18a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .gradle /build/ /native.handler/target +target /native.handler/java-wrapper/build /native.handler/build /asyncapi-cli/build diff --git a/README.md b/README.md index 0b8e2cc7e..b05bf6f57 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,63 @@ -# Asyncapi -This repository is the code base for the ballerina async-api tool +# Ballerina - AsyncAPI Tools +[![Build](https://github.com/ballerina-platform/asyncapi-tools/actions/workflows/build-timestamped-master.yml/badge.svg)](https://github.com/ballerina-platform/asyncapi-tools/actions/workflows/build-timestamped-master.yml) +[![GitHub Last Commit](https://img.shields.io/github/last-commit/ballerina-platform/asyncapi-tools.svg)](https://github.com/ballerina-platform/asyncapi-tools/commits/master) +[![GitHub issues](https://img.shields.io/github/issues/ballerina-platform/ballerina-standard-library/module/asyncpi-tools.svg?label=Open%20Issues)](https://github.com/ballerina-platform/ballerina-library/labels/module%2Fasyncapi-tools) -# Architecture of the repository -![architecture](asyncapi-cli/src/main/resources/architecture.jpg?raw=true) \ No newline at end of file +The AsyncAPI Specification is a specification, which creates an event driven architecture based contract for APIs +detailing all of its resources and channels in both human and machine-readable format for easy development, discovery, +and integration. AsyncAPI tools currently s the following capabilities. + +1. Generate Ballerina client code from a given AsyncAPI contract with `http` and `ws` protocols. +2. Export the AsyncAPI definition of a Ballerina service using the `ws` protocol. +3. The asyncapi command in Ballerina is used for AsyncAPI to Ballerina and Ballerina to AsyncAPI code generations. + +The `asyncapi` command in Ballerina is used for AsyncAPI to Ballerina and Ballerina to AsyncAPI code generations. + +## Building from the Source + +### Setting Up the Prerequisites + +1. OpenJDK 17 ([Adopt OpenJDK](https://adoptopenjdk.net/) or any other OpenJDK distribution) + + >**Info:** You can also use [Oracle JDK](https://www.oracle.com/java/technologies/javase-downloads.html). Set the JAVA_HOME environment variable to the pathname of the directory into which you installed JDK. + +2. Export GitHub Personal access token with read package permissions as follows, + ``` + export packageUser= + export packagePAT= + ``` + +### Building the Source + +Execute the commands below to build from the source. + +1. To build the library: + + ./gradlew clean build + +2. To run the integration tests: + + ./gradlew clean test + +3. To build the module without the tests: + + ./gradlew clean build -x test + +4. To publish to maven local: + + ./gradlew clean build publishToMavenLocal + +## Contributing to Ballerina + +As an open-source project, Ballerina welcomes contributions from the community. + +For more information, go to the [contribution guidelines](https://github.com/ballerina-platform/ballerina-lang/blob/master/CONTRIBUTING.md). + +## Code of Conduct + +All contributors are encouraged to read the [Ballerina Code of Conduct](https://ballerina.io/code-of-conduct). + +## Useful Links + +* Chat live with us via our [Discord server](https://discord.gg/ballerinalang). +* Post all technical questions on Stack Overflow with the [#ballerina](https://stackoverflow.com/questions/tagged/ballerina) tag. \ No newline at end of file diff --git a/asyncapi-cli/build.gradle b/asyncapi-cli/build.gradle index 9df6cea55..834fc24b6 100644 --- a/asyncapi-cli/build.gradle +++ b/asyncapi-cli/build.gradle @@ -21,39 +21,176 @@ apply plugin: "checkstyle" description = "Ballerina - AsyncAPI Tooling - AsyncAPI to Ballerina" +def ballerinaDist = "$project.buildDir/jballerina-tools-${ballerinaLangVersion}" +def runtimePath = "${project.rootDir}/target/ballerina-distribution" + +tasks.register("jBallerinaPack") +tasks.register("unpackStdLibs") +tasks.register("copyStdlibs") + configurations.all { resolutionStrategy.preferProjectModules() } +configurations { + ballerinaStdLibs + balTools +} + dependencies { checkstyle project(':checkstyle') checkstyle "com.puppycrawl.tools:checkstyle:${puppycrawlCheckstyleVersion}" - implementation 'io.apicurio:apicurio-data-models:1.1.15' - implementation 'org.apache.logging.log4j:log4j-core:2.14.1' + implementation "io.apicurio:apicurio-data-models:${apiCurioVersion}" + implementation "org.apache.logging.log4j:log4j-core:${log4jVersion}" + implementation "org.slf4j:slf4j-api:${slf4jVersion}" implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${jacksonDataformatYamlVersion}" - implementation 'commons-io:commons-io:2.11.0' + implementation "commons-io:commons-io:${commonsIoVersion}" implementation "org.ballerinalang:ballerina-lang:${ballerinaLangVersion}" implementation "org.ballerinalang:ballerina-parser:${ballerinaLangVersion}" implementation "org.ballerinalang:ballerina-cli:${ballerinaLangVersion}" implementation "org.ballerinalang:formatter-core:${ballerinaLangVersion}" implementation "org.ballerinalang:ballerina-tools-api:${ballerinaLangVersion}" + implementation "org.ballerinalang:ballerina-runtime:${ballerinaLangVersion}" implementation "io.ballerina.stdlib:http-native:${stdlibHttpVersion}" implementation "org.ballerinalang:language-server-commons:${ballerinaLangVersion}" - implementation "info.picocli:picocli:4.0.1" + implementation "info.picocli:picocli:${picocliVersion}" testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' testImplementation "org.testng:testng:${testngVersion}" + + balTools ("org.ballerinalang:jballerina-tools:${ballerinaLangVersion}") { + transitive = false + } + + /* Standard libraries */ + ballerinaStdLibs "io.ballerina.stdlib:io-ballerina:${stdlibIoVersion}" + ballerinaStdLibs "io.ballerina.stdlib:http-ballerina:${stdlibHttpVersion}" + ballerinaStdLibs "io.ballerina.stdlib:log-ballerina:${stdlibLogVersion}" + ballerinaStdLibs "io.ballerina.stdlib:os-ballerina:${stdlibOsVersion}" + ballerinaStdLibs "io.ballerina.stdlib:mime-ballerina:${stdlibMimeVersion}" + ballerinaStdLibs "io.ballerina.stdlib:regex-ballerina:${stdlibRegexVersion}" + ballerinaStdLibs "io.ballerina.stdlib:crypto-ballerina:${stdlibCryptoVersion}" + ballerinaStdLibs "io.ballerina.stdlib:auth-ballerina:${stdlibAuthVersion}" + ballerinaStdLibs "io.ballerina.stdlib:time-ballerina:${stdlibTimeVersion}" + ballerinaStdLibs "io.ballerina.stdlib:cache-ballerina:${stdlibCacheVersion}" + ballerinaStdLibs "io.ballerina.stdlib:task-ballerina:${stdlibTaskVersion}" + ballerinaStdLibs "io.ballerina.stdlib:file-ballerina:${stdlibFileVersion}" + ballerinaStdLibs "io.ballerina.stdlib:jwt-ballerina:${stdlibJwtVersion}" + ballerinaStdLibs "io.ballerina.stdlib:oauth2-ballerina:${stdlibOAuth2Version}" + ballerinaStdLibs "io.ballerina.stdlib:uuid-ballerina:${stdlibUuidVersion}" + ballerinaStdLibs "io.ballerina.stdlib:url-ballerina:${stdlibUrlVersion}" + ballerinaStdLibs "io.ballerina.stdlib:xmldata-ballerina:${stdlibXmldataVersion}" + ballerinaStdLibs "io.ballerina.stdlib:observe-ballerina:${observeVersion}" + ballerinaStdLibs "io.ballerina:observe-ballerina:${observeInternalVersion}" + ballerinaStdLibs "io.ballerina.stdlib:kafka-ballerina:${stdlibKafkaVersion}" + ballerinaStdLibs "io.ballerina.stdlib:rabbitmq-ballerina:${stdlibRabbitMqVersion}" + ballerinaStdLibs "io.ballerina.stdlib:websocket-ballerina:${stdlibWebsocketVersion}" + ballerinaStdLibs "io.ballerina.stdlib:constraint-ballerina:${stdlibConstraintVersion}" +} + +clean { + delete "$project.projectDir/build" + delete "$project.rootDir/target" +} + +jBallerinaPack { + doLast { + configurations.balTools.resolvedConfiguration.resolvedArtifacts.each { artifact -> + copy { + from project.zipTree(artifact.getFile()) + into new File("${project.buildDir}") + } + copy { + from(project.zipTree(artifact.getFile())) { + eachFile { fcd -> + fcd.relativePath = new RelativePath(!fcd.file.isDirectory(), fcd.relativePath.segments.drop(1)) + } + includeEmptyDirs = false + } + into runtimePath + } + } + } + outputs.dir ballerinaDist +} + +unpackStdLibs() { + dependsOn(jBallerinaPack) + doLast { + configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> + copy { + from project.zipTree(artifact.getFile()) + into new File("${project.buildDir}/extracted-stdlibs/" + artifact.name + "-zip") + } + } + } +} + +copyStdlibs() { + dependsOn(unpackStdLibs) + /* Standard Libraries */ + doLast { + configurations.ballerinaStdLibs.resolvedConfiguration.resolvedArtifacts.each { artifact -> + def artifactExtractedPath = "${project.buildDir}/extracted-stdlibs/" + artifact.name + "-zip" + copy { + into ballerinaDist + into("repo/bala") { + from "${artifactExtractedPath}/bala" + } + into("repo/cache") { + from "${artifactExtractedPath}/cache" + } + } + copy { + into runtimePath + into("repo/bala") { + from "${artifactExtractedPath}/bala" + } + into("repo/cache") { + from "${artifactExtractedPath}/cache" + } + } + } + def asyncapiCliJar = "${project.rootDir}/asyncapi-cli/build/libs/asyncapi-cli-${project.version}.jar" + copy { + into ballerinaDist + into("bre/lib") { + from "${asyncapiCliJar}" + } + } + copy { + into runtimePath + into("bre/lib") { + from "${asyncapiCliJar}" + } + } + } } test { + dependsOn(copyStdlibs) + systemProperty "ballerina.home", ballerinaDist + systemProperty "ballerina.offline.flag", "true" useTestNG() { suites "src/test/resources/testng.xml" } + testLogging.showStandardStreams = true + testLogging { + events "PASSED", "FAILED", "SKIPPED" + afterSuite { desc, result -> + if (!desc.parent) { // will match the outermost suite + def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)" + def startItem = '| ', endItem = ' |' + def repeatLength = startItem.length() + output.length() + endItem.length() + println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength)) + } + } + } } checkstyle { - toolVersion '10.12.0' + toolVersion "${puppycrawlCheckstyleVersion}" configFile rootProject.file("config/checkstyle/build/checkstyle.xml") configProperties = ["suppressionFile" : file("${rootDir}/config/checkstyle/build/suppressions.xml")] } @@ -74,7 +211,7 @@ jar { shadowJar { configurations = [project.configurations.runtimeClasspath] dependencies { - include(dependency('io.apicurio:apicurio-data-models:1.1.15')) + include(dependency("io.apicurio:apicurio-data-models:${apiCurioVersion}")) exclude('META-INF/*.SF') exclude('META-INF/*.DSA') exclude('META-INF/*.RSA') @@ -90,3 +227,4 @@ compileJava { } } +build.dependsOn("copyStdlibs") diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiCmd.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiCmd.java index de88f55f7..b2502e651 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiCmd.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiCmd.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you 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 @@ -17,24 +17,61 @@ */ package io.ballerina.asyncapi.cmd; +import io.ballerina.asyncapi.cmd.websockets.AsyncAPIDiagnostic; +import io.ballerina.asyncapi.cmd.websockets.AsyncApiToBallerinaGenerator; +import io.ballerina.asyncapi.cmd.websockets.BallerinaToAsyncApiGenerator; +import io.ballerina.asyncapi.cmd.websockets.CmdConstants; +import io.ballerina.asyncapi.cmd.websockets.CmdUtils; import io.ballerina.asyncapi.codegenerator.application.Application; import io.ballerina.asyncapi.codegenerator.application.CodeGenerator; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.DiagnosticMessages; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.ExceptionDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.IncompatibleRemoteDiagnostic; import io.ballerina.cli.BLauncherCmd; +import org.ballerinalang.formatter.core.FormatterException; import picocli.CommandLine; import java.io.BufferedReader; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.List; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.EXPERIMENTAL_WARNING; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.INPUT_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.INPUT_FLAG_ALT; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.JSON_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.LICENSE_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.LINE_SEPARATOR; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.OUTPUT_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.OUTPUT_FLAG_ALT; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.PROTOCOL_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.SERVICE_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.TEST_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.VALID_HTTP_NAMES; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.VALID_WS_NAMES; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.CLIENT_GENERATION_FAILED; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.INVALID_OPTION_ERROR_HTTP; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.INVALID_USE_OF_JSON_FLAG_WARNING; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.INVALID_USE_OF_LICENSE_FLAG_WARNING; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.INVALID_USE_OF_SERVICE_FLAG_WARNING; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.INVALID_USE_OF_TEST_FLAG_WARNING; +import static io.ballerina.asyncapi.cmd.AsyncApiMessages.MESSAGE_INVALID_LICENSE_STREAM; + /** - * Main class to implement "asyncapi" command for ballerina. Commands for Listener generation from AsyncAPI spec + * Main class to implement "asyncapi" command for ballerina. Commands for Listener generation from AsyncApi spec + * */ @CommandLine.Command( name = "asyncapi", @@ -45,18 +82,35 @@ public class AsyncApiCmd implements BLauncherCmd { private PrintStream outStream; private boolean exitWhenFinish; private Path executionPath = Paths.get(System.getProperty("user.dir")); + private Path targetOutputPath; @CommandLine.Option(names = {"-h", "--help"}, hidden = true) private boolean helpFlag; - @CommandLine.Option(names = {"-i", "--input"}, description = "File path to the AsyncAPI specification") + @CommandLine.Option(names = {INPUT_FLAG_ALT, INPUT_FLAG}, description = "File path to the AsyncAPI specification") private boolean inputPath; - @CommandLine.Option(names = {"-o", "--output"}, + @CommandLine.Option(names = {OUTPUT_FLAG_ALT, OUTPUT_FLAG}, description = "Directory to store the generated Ballerina service. " + "If this is not provided, the generated files will be stored in the the current execution directory") private String outputPath; + @CommandLine.Option (names = {PROTOCOL_FLAG}, description = "The protocol to be used for the service") + private String protocol = "http"; + + @CommandLine.Option(names = {LICENSE_FLAG}, description = "Location of the file which contains the license header") + private String licenseFilePath; + + @CommandLine.Option(names = {SERVICE_FLAG}, description = "Service name that need to documented as asyncapi " + + "contract") + private String service; + + @CommandLine.Option(names = {TEST_FLAG}, hidden = true, description = "Generate test files") + private boolean includeTestFiles; + + @CommandLine.Option(names = {JSON_FLAG}, description = "Generate json file") + private boolean generatedFileType; + @CommandLine.Parameters private List argList; @@ -91,6 +145,18 @@ public AsyncApiCmd(PrintStream outStream, Path executionDir, boolean exitWhenFin this.exitWhenFinish = exitWhenFinish; } + /** + * Constructor override, which takes output stream and execution dir and exits when finish as inputs. + * + * @param executionDir defines the directory location of execution of ballerina command + * @param exitWhenFinish exit when finish the execution + */ + public AsyncApiCmd(Path executionDir, boolean exitWhenFinish) { + this.outStream = System.err; + this.executionPath = executionDir; + this.exitWhenFinish = exitWhenFinish; + } + @Override public void execute() { if (helpFlag) { @@ -105,11 +171,44 @@ public void execute() { return; } String fileName = argList.get(0); - Application codeGenerator = new CodeGenerator(); - try { - codeGenerator.generate(fileName, (outputPath == null) ? String.valueOf(executionPath) : outputPath); - } catch (BallerinaAsyncApiException e) { - outStream.println(e.getMessage()); + + if (VALID_HTTP_NAMES.contains(protocol.toLowerCase())) { + verifyValidInputsForHttp(); + Application codeGenerator = new CodeGenerator(); + try { + codeGenerator.generate(fileName, (outputPath == null) ? + String.valueOf(executionPath) : outputPath); + } catch (BallerinaAsyncApiException e) { + outStream.println(e.getMessage()); + exitError(this.exitWhenFinish); + } + } else if (VALID_WS_NAMES.contains(protocol.toLowerCase())) { + outStream.println(EXPERIMENTAL_WARNING); + if (fileName.endsWith(Constants.YAML_EXTENSION) || fileName.endsWith(Constants.JSON_EXTENSION) || + fileName.endsWith(Constants.YML_EXTENSION)) { + giveWarningsForInvalidClientGenOptions(); + try { + asyncApiToBallerinaWs(fileName); + } catch (IOException e) { + outStream.println(e.getLocalizedMessage()); + exitError(this.exitWhenFinish); + } + // when -i has bal extension + } else if (fileName.endsWith(CmdConstants.BAL_EXTENSION)) { + giveWarningsForInvalidSpecGenOptions(); + try { + ballerinaToAsyncApiWs(fileName); + } catch (Exception e) { + outStream.println(e.getLocalizedMessage()); + exitError(this.exitWhenFinish); + } + // If -i has no extensions + } else { + outStream.println(AsyncApiMessages.MISSING_CONTRACT_PATH); + exitError(this.exitWhenFinish); + } + } else { + outStream.println(String.format(AsyncApiMessages.MESSAGE_INVALID_PROTOCOL, protocol)); exitError(this.exitWhenFinish); } } else { @@ -124,6 +223,145 @@ public void execute() { } } + private void giveWarningsForInvalidSpecGenOptions() { + if (licenseFilePath != null) { + outStream.println(INVALID_USE_OF_LICENSE_FLAG_WARNING); + } + if (includeTestFiles) { + outStream.println(INVALID_USE_OF_TEST_FLAG_WARNING); + } + } + + private void giveWarningsForInvalidClientGenOptions() { + if (generatedFileType) { + outStream.println(INVALID_USE_OF_JSON_FLAG_WARNING); + } + if (service != null) { + outStream.println(INVALID_USE_OF_SERVICE_FLAG_WARNING); + } + } + + private void verifyValidInputsForHttp() { + if (licenseFilePath != null) { + outStream.println(String.format(INVALID_OPTION_ERROR_HTTP, LICENSE_FLAG)); + exitError(this.exitWhenFinish); + } + if (service != null) { + outStream.println(String.format(INVALID_OPTION_ERROR_HTTP, SERVICE_FLAG)); + exitError(this.exitWhenFinish); + } + if (includeTestFiles) { + outStream.println(String.format(INVALID_OPTION_ERROR_HTTP, TEST_FLAG)); + exitError(this.exitWhenFinish); + } + if (generatedFileType) { + outStream.println(String.format(INVALID_OPTION_ERROR_HTTP, JSON_FLAG)); + exitError(this.exitWhenFinish); + } + } + + private void ballerinaToAsyncApiWs(String fileName) { + List errors = new ArrayList<>(); + final File balFile = new File(fileName); + try { + Path balFilePath = Paths.get(balFile.getCanonicalPath()); + setOutputPathWs(); + // Check service name it is mandatory + List generationErrors = BallerinaToAsyncApiGenerator + .generateAsyncAPIDefinitionsAllService(balFilePath, targetOutputPath, service, generatedFileType, + outStream); + errors.addAll(generationErrors); + } catch (IOException e) { + DiagnosticMessages message = DiagnosticMessages.AAS_CONVERTOR_102; + ExceptionDiagnostic error = new ExceptionDiagnostic(message.getCode(), message.getDescription(), null, + e.getLocalizedMessage()); + errors.add(error); + } + + if (!errors.isEmpty()) { + for (AsyncApiConverterDiagnostic error : errors) { + if (error instanceof ExceptionDiagnostic exceptionDiagnostic) { + AsyncAPIDiagnostic diagnostic = CmdUtils.constructAsyncAPIDiagnostic(exceptionDiagnostic.getCode(), + exceptionDiagnostic.getMessage(), exceptionDiagnostic.getDiagnosticSeverity(), + exceptionDiagnostic.getLocation().orElse(null)); + outStream.println(diagnostic); + exitError(this.exitWhenFinish); + } else if (error instanceof IncompatibleRemoteDiagnostic incompatibleError) { + AsyncAPIDiagnostic diagnostic = CmdUtils.constructAsyncAPIDiagnostic(incompatibleError.getCode(), + incompatibleError.getMessage(), incompatibleError.getDiagnosticSeverity(), + incompatibleError.getLocation().get()); + outStream.println(diagnostic); + } + } + } + } + + private void asyncApiToBallerinaWs(String fileName) throws IOException { + AsyncApiToBallerinaGenerator generator = new AsyncApiToBallerinaGenerator(this.extractLicenseHeaderWs(), + this.includeTestFiles); + final File asyncApiFile = new File(fileName); + setOutputPathWs(); + Path resourcePath = Paths.get(asyncApiFile.getCanonicalPath()); + generatesClientFileWs(generator, resourcePath); + } + + /** + * This util is to set the license header content which is to be added at the beginning of the ballerina files. + */ + private String extractLicenseHeaderWs() { + try { + String licenseHeader; + if (this.licenseFilePath != null && !this.licenseFilePath.isBlank()) { + Path filePath = Paths.get((new File(this.licenseFilePath).getCanonicalPath())); + licenseHeader = Files.readString(Paths.get(filePath.toString())); + if (!licenseHeader.endsWith(LINE_SEPARATOR)) { + licenseHeader = licenseHeader + LINE_SEPARATOR + LINE_SEPARATOR; + } else if (!licenseHeader.endsWith(LINE_SEPARATOR + LINE_SEPARATOR)) { + licenseHeader = licenseHeader + LINE_SEPARATOR; + } + return licenseHeader; + } + } catch (IOException e) { + outStream.println(String.format(MESSAGE_INVALID_LICENSE_STREAM, this.licenseFilePath, e.getMessage())); + exitError(this.exitWhenFinish); + } + return ""; + } + + /** + * This util is to get the output Path. + */ + private void setOutputPathWs() { + targetOutputPath = executionPath; + if (this.outputPath != null) { + if (Paths.get(outputPath).isAbsolute()) { + targetOutputPath = Paths.get(outputPath); + } else { + targetOutputPath = Paths.get(targetOutputPath.toString(), outputPath); + } + } + } + + /** + * A Util to Client generation. + * + * @param generator generator object + * @param resourcePath resource Path + */ + private void generatesClientFileWs(AsyncApiToBallerinaGenerator generator, Path resourcePath) { + try { + generator.generateClient(resourcePath, targetOutputPath); + } catch (IOException | FormatterException | BallerinaAsyncApiExceptionWs e) { + if (e.getLocalizedMessage() != null) { + outStream.println(e.getLocalizedMessage()); + exitError(this.exitWhenFinish); + } else { + outStream.println(CLIENT_GENERATION_FAILED); + exitError(this.exitWhenFinish); + } + } + } + @Override public String getName() { return CMD_NAME; @@ -132,8 +370,8 @@ public String getName() { @Override public void printLongDesc(StringBuilder stringBuilder) { try (InputStream inputStream = ClassLoader.getSystemResourceAsStream("ballerina-asyncapi.help"); - InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); - BufferedReader br = new BufferedReader(inputStreamReader)) { + InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + BufferedReader br = new BufferedReader(inputStreamReader)) { String content; while ((content = br.readLine()) != null) { diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiConstants.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiConstants.java new file mode 100644 index 000000000..665f1ae0e --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiConstants.java @@ -0,0 +1,28 @@ +package io.ballerina.asyncapi.cmd; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Holds constants used in the asyncapi commands. + * + */ +public class AsyncApiConstants { + public static final Set VALID_HTTP_NAMES = new HashSet<>(Arrays.asList("http", "https")); + public static final Set VALID_WS_NAMES = new HashSet<>(Arrays.asList("ws", "wss", "websocket")); + public static final String LICENSE_FLAG = "--license"; + public static final String SERVICE_FLAG = "--service"; + public static final String TEST_FLAG = "--with-tests"; + public static final String JSON_FLAG = "--json"; + public static final String INPUT_FLAG = "--input"; + public static final String OUTPUT_FLAG = "--output"; + public static final String INPUT_FLAG_ALT = "-i"; + public static final String OUTPUT_FLAG_ALT = "-o"; + public static final String PROTOCOL_FLAG = "--protocol"; + public static final String SPEC = "spec"; + public static final String CLIENT = "client"; + public static final String LINE_SEPARATOR = System.lineSeparator(); + public static final String EXPERIMENTAL_WARNING = "WARNING The support for websockets protocol is currently " + + "an experimental feature, and its behavior may be subject to change in future releases." + LINE_SEPARATOR; +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiMessages.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiMessages.java index a87251318..fba4a4de1 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiMessages.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/AsyncApiMessages.java @@ -1,9 +1,50 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.CLIENT; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.JSON_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.LICENSE_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.SERVICE_FLAG; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.SPEC; +import static io.ballerina.asyncapi.cmd.AsyncApiConstants.TEST_FLAG; + /** * This class contains the messages constants required for AsyncApi tool. */ public class AsyncApiMessages { public static final String MESSAGE_FOR_MISSING_INPUT = "An AsyncApi definition file is required to generate the " + "listener. \ne.g: bal asyncapi --input "; + public static final String CLIENT_GENERATION_FAILED = "Error occurred when generating client for AsyncAPI contract"; + public static final String MISSING_CONTRACT_PATH = "Bal service file is required to generate the " + + "asyncapi definition. \ne.g: bal asyncapi --input "; + public static final String MESSAGE_INVALID_PROTOCOL = "ERROR invalid protocol: %s. Supported protocols are" + + " `http` and `ws`."; + public static final String INVALID_OPTION_ERROR_HTTP = "ERROR unsupported %s flag for http protocol"; + public static final String INVALID_OPTION_WARNING = "WARNING the `%s` option is invalid for generating" + + " %s files and will be ignored."; + public static final String INVALID_USE_OF_LICENSE_FLAG_WARNING = String.format(INVALID_OPTION_WARNING, LICENSE_FLAG, + SPEC); + public static final String INVALID_USE_OF_TEST_FLAG_WARNING = String.format(INVALID_OPTION_WARNING, TEST_FLAG, + SPEC); + public static final String INVALID_USE_OF_JSON_FLAG_WARNING = String.format(INVALID_OPTION_WARNING, JSON_FLAG, + CLIENT); + public static final String INVALID_USE_OF_SERVICE_FLAG_WARNING = String.format(INVALID_OPTION_WARNING, SERVICE_FLAG, + CLIENT); + public static final String MESSAGE_INVALID_LICENSE_STREAM = "Invalid license file path : %s. %s."; } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/AsyncAPIDiagnostic.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/AsyncAPIDiagnostic.java new file mode 100644 index 000000000..7b1dc40bf --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/AsyncAPIDiagnostic.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd.websockets; + +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticInfo; +import io.ballerina.tools.diagnostics.DiagnosticProperty; +import io.ballerina.tools.diagnostics.Location; +import io.ballerina.tools.text.LinePosition; +import io.ballerina.tools.text.LineRange; + +import java.text.MessageFormat; +import java.util.Collections; +import java.util.List; + +/** + * Represents a {@code Diagnostic} related to asyncapi command. + * + */ +public class AsyncAPIDiagnostic extends Diagnostic { + private final DiagnosticInfo diagnosticInfo; + private final Location location; + private final String message; + + public AsyncAPIDiagnostic(DiagnosticInfo diagnosticInfo, Location location, Object[] args) { + this.diagnosticInfo = diagnosticInfo; + this.location = location; + this.message = MessageFormat.format(diagnosticInfo.messageFormat(), args); + } + + /** + * Rearrange line range with 1 based, since default line range gives 0 based. + */ + static LineRange getOneBasedLineRange(LineRange lineRange) { + return LineRange.from( + lineRange.filePath(), + LinePosition.from(lineRange.startLine().line() + 1, lineRange.startLine().offset() + 1), + LinePosition.from(lineRange.endLine().line() + 1, lineRange.endLine().offset() + 1)); + } + + public Location location() { + return this.location; + } + + public DiagnosticInfo diagnosticInfo() { + return this.diagnosticInfo; + } + + public String message() { + return this.message; + } + + public List> properties() { + return Collections.emptyList(); + } + + @Override + public String toString() { + LineRange lineRange = getOneBasedLineRange(this.location().lineRange()); + String var10000 = this.diagnosticInfo().severity().toString(); + return var10000 + " [" + lineRange.filePath() + ":" + lineRange + "] " + this.message(); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/AsyncApiToBallerinaGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/AsyncApiToBallerinaGenerator.java new file mode 100644 index 000000000..749cb26a4 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/AsyncApiToBallerinaGenerator.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd.websockets; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.CodegenUtils; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.TestGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.websocketscore.model.GenSrcFile; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import org.ballerinalang.formatter.core.Formatter; +import org.ballerinalang.formatter.core.FormatterException; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +import static io.ballerina.asyncapi.cmd.websockets.CmdConstants.CLIENT_FILE_NAME; +import static io.ballerina.asyncapi.cmd.websockets.CmdConstants.CONFIG_FILE_NAME; +import static io.ballerina.asyncapi.cmd.websockets.CmdConstants.TEST_DIR; +import static io.ballerina.asyncapi.cmd.websockets.CmdConstants.TEST_FILE_NAME; +import static io.ballerina.asyncapi.cmd.websockets.CmdConstants.TYPE_FILE_NAME; +import static io.ballerina.asyncapi.cmd.websockets.CmdUtils.setGeneratedFileName; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ASYNCAPI_PATH_SEPARATOR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.GenType.GEN_CLIENT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.UTIL_FILE_NAME; + +/** + * This class generates Ballerina Websocket client for a provided AsyncAPI definition. + * + */ +public class AsyncApiToBallerinaGenerator { + private static final PrintStream outStream = System.err; + private final String licenseHeader; + private final boolean includeTestFiles; + + public AsyncApiToBallerinaGenerator(String licenseHeader, boolean includeTestFiles) { + this.licenseHeader = licenseHeader; + this.includeTestFiles = includeTestFiles; + } + + /** + * Generates ballerina websocket client for provided Async API Definition in {@code definitionPath}. + * Generated source will be written to a ballerina module at {@code outPath} + * Method can be use for generating Ballerina websocket clients. + * + * @param definitionPath Input Async Api Definition file path + * @param outPath Destination file path to save generated client files including types.bal, utils.bal + * If not provided {@code definitionPath} will be used as the default destination path + * @throws IOException when file operations fail + * @throws BallerinaAsyncApiExceptionWs when code generator fails + */ + public void generateClient(Path definitionPath, Path outPath) throws IOException, BallerinaAsyncApiExceptionWs, + FormatterException { + writeGeneratedSources(generateClientFiles(definitionPath), outPath, GEN_CLIENT); + } + + /** + * + * @param sources Generated all sources as a list + * @param srcPath Output path provided + * @throws IOException + */ + private void writeGeneratedSources(List sources, Path srcPath, GeneratorConstants.GenType type) + throws IOException { + // Remove old generated file with same name + List listFiles = new ArrayList<>(); + if (Files.notExists(srcPath)) { + Files.createDirectories(srcPath); + } + if (Files.exists(srcPath)) { + File[] files = new File(String.valueOf(srcPath)).listFiles(); + if (files != null) { + listFiles.addAll(Arrays.asList(files)); + for (File file : files) { + if (file.isDirectory() && file.getName().equals("tests")) { + File[] innerFiles = new File(srcPath + "/tests").listFiles(); + if (innerFiles != null) { + listFiles.addAll(Arrays.asList(innerFiles)); + } + } + } + } + } + + for (File file : listFiles) { + for (GenSrcFile gFile : sources) { + if (file.getName().equals(gFile.getFileName())) { + if (System.console() != null) { + String userInput = System.console().readLine("There is already a/an " + file.getName() + + " in the location. Do you want to override the file? [y/N] "); + if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), "y")) { + int duplicateCount = 0; + setGeneratedFileName(listFiles, gFile, duplicateCount); + } + } + } + } + } + + for (GenSrcFile file : sources) { + Path filePath; + // We only overwrite files of overwritable type. + // So non overwritable files will be written to disk only once. + if (!file.getType().isOverwritable()) { + filePath = srcPath.resolve(file.getFileName()); + if (Files.notExists(filePath)) { + String fileContent = file.getFileName().endsWith(".bal") ? + (licenseHeader + file.getContent()) : file.getContent(); + CodegenUtils.writeFile(filePath, fileContent); + } + } else { + boolean isDuplicatedFileInTests = file.getFileName().matches("test.+[0-9]+.bal") || + file.getFileName().matches("Config.+[0-9]+.toml"); + if (file.getFileName().equals(TEST_FILE_NAME) || file.getFileName().equals(CONFIG_FILE_NAME) || + isDuplicatedFileInTests) { + // Create test directory if not exists in the path. If exists do not throw an error + Files.createDirectories(Paths.get(srcPath + ASYNCAPI_PATH_SEPARATOR + TEST_DIR)); + filePath = Paths.get(srcPath.resolve(TEST_DIR + ASYNCAPI_PATH_SEPARATOR + + file.getFileName()).toFile().getCanonicalPath()); + } else { + filePath = Paths.get(srcPath.resolve(file.getFileName()).toFile().getCanonicalPath()); + } + String fileContent = file.getFileName().endsWith(".bal") ? + (licenseHeader + file.getContent()) : file.getContent(); + CodegenUtils.writeFile(filePath, fileContent); + } + } + + outStream.println("Client generated successfully."); + outStream.println("Following files were created."); + Iterator iterator = sources.iterator(); + while (iterator.hasNext()) { + outStream.println("-- " + iterator.next().getFileName()); + } + } + + /** + * Generate code for ballerina client. + * @param asyncApi path to the AsyncAPI definition + * @return generated source files as a list of {@link GenSrcFile} + * @throws IOException when code generation with specified templates fails + */ + private List generateClientFiles(Path asyncApi) + throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + List sourceFiles = new ArrayList<>(); + // Normalize AsyncAPI definition + AsyncApi25DocumentImpl asyncApiDef = GeneratorUtils.normalizeAsyncAPI(asyncApi); + // Generate ballerina client. + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig asyncApiClientConfig = clientMetaDataBuilder.withAsyncApi(asyncApiDef) + .withLicense(licenseHeader).build(); + //Generate client intermediate code + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(asyncApiClientConfig); + String mainContent = Formatter.format(intermediateClientGenerator.generateSyntaxTree()).toString(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, CLIENT_FILE_NAME, mainContent)); + + //Generate util functions for client intermediate code + String utilContent = Formatter.format( + intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree()).toString(); + if (!utilContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.UTIL_SRC, UTIL_FILE_NAME, utilContent)); + } + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + //Generate ballerina records to represent schemas in client intermediate code + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncApiDef, + preGeneratedTypeDefNodes); + // Generate schema generator syntax tree + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + String schemaContent = Formatter.format(schemaSyntaxTree).toString(); + + if (!schemaContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.MODEL_SRC, TYPE_FILE_NAME, schemaContent)); + } + + // Generate test boilerplate code for test cases + if (this.includeTestFiles) { + TestGenerator testGenerator = new TestGenerator(intermediateClientGenerator); + String testContent = Formatter.format(testGenerator.generateSyntaxTree()).toString(); + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, TEST_FILE_NAME, testContent)); + String configContent = testGenerator.getConfigTomlFile(); + if (!configContent.isBlank()) { + sourceFiles.add(new GenSrcFile(GenSrcFile.GenFileType.GEN_SRC, CONFIG_FILE_NAME, configContent)); + } + } + return sourceFiles; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/BallerinaToAsyncApiGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/BallerinaToAsyncApiGenerator.java new file mode 100644 index 000000000..e5f46202d --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/BallerinaToAsyncApiGenerator.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd.websockets; + +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.DiagnosticMessages; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.ExceptionDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.AsyncApiResult; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.CodegenUtils; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ServiceToAsyncApiConverterUtils; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.projects.Document; +import io.ballerina.projects.DocumentId; +import io.ballerina.projects.Module; +import io.ballerina.projects.ModuleId; +import io.ballerina.projects.Package; +import io.ballerina.projects.PackageCompilation; +import io.ballerina.projects.Project; +import io.ballerina.projects.ProjectKind; +import io.ballerina.projects.directory.ProjectLoader; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.CodegenUtils.resolveContractFileName; + +/** + * AsyncApi related utility classes. + * + */ +public class BallerinaToAsyncApiGenerator { + + public static List generateAsyncAPIDefinitionsAllService(Path servicePath, + Path outPath, + String serviceName, + Boolean needJson, + PrintStream outStream) { + SyntaxTree syntaxTree; + SemanticModel semanticModel; + Project project; + final List errors = new ArrayList<>(); + + // Load project instance for single ballerina file + project = ProjectLoader.loadProject(servicePath); + Package packageName = project.currentPackage(); + DocumentId docId; + Document doc; + if (project.kind().equals(ProjectKind.BUILD_PROJECT)) { + docId = project.documentId(servicePath); + ModuleId moduleId = docId.moduleId(); + doc = project.currentPackage().module(moduleId).document(docId); + } else { + // Take module instance for traversing the syntax tree + Module currentModule = packageName.getDefaultModule(); + Iterator documentIterator = currentModule.documentIds().iterator(); + docId = documentIterator.next(); + doc = currentModule.document(docId); + } + Optional path = project.documentPath(docId); + Path inputPath = path.orElse(null); + syntaxTree = doc.syntaxTree(); + PackageCompilation compilation = project.currentPackage().getCompilation(); + boolean hasErrors = compilation.diagnosticResult().diagnostics().stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + + if (hasErrors) { + // if there are any compilation errors, do not proceed + outStream.println("COMPILATION ERRORS:"); + for (Diagnostic e :compilation.diagnosticResult().diagnostics()) { + if (e.diagnosticInfo().severity().equals(DiagnosticSeverity.ERROR)) { + outStream.println(e.message()); + } + } + } else { + semanticModel = compilation.getSemanticModel(docId.moduleId()); + List asyncAPIDefinitions = ServiceToAsyncApiConverterUtils. + generateAsyncAPISpecDefinition(syntaxTree, semanticModel, serviceName, needJson, inputPath); + + if (!asyncAPIDefinitions.isEmpty()) { + List fileNames = new ArrayList<>(); + for (AsyncApiResult definition : asyncAPIDefinitions) { + if (Files.notExists(outPath)) { + try { + Files.createDirectories(outPath); + } catch (IOException e) { + DiagnosticMessages message = DiagnosticMessages.AAS_CONVERTOR_102; + ExceptionDiagnostic error = new ExceptionDiagnostic(message.getCode(), + message.getDescription() + e.getLocalizedMessage(), null); + errors.add(error); + } + } + try { + errors.addAll(definition.getDiagnostics()); + if (definition.getAsyncAPI().isPresent()) { + Optional content; + if (needJson) { + content = definition.getJson(); + } else { + content = definition.getYaml(); + } + String fileName = resolveContractFileName(outPath, definition.getServiceName(), needJson); + CodegenUtils.writeFile(outPath.resolve(fileName), content.get()); + fileNames.add(fileName); + } + } catch (IOException e) { + DiagnosticMessages message = DiagnosticMessages.AAS_CONVERTOR_102; + ExceptionDiagnostic error = new ExceptionDiagnostic(message.getCode(), + message.getDescription() + e.getLocalizedMessage(), null); + errors.add(error); + } + } + outStream.println("AsyncAPI definition(s) generated successfully and copied to :"); + for (String fileName : fileNames) { + outStream.println("-- " + fileName); + } + } + } + return errors; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/CmdConstants.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/CmdConstants.java new file mode 100644 index 000000000..c8eb11458 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/CmdConstants.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd.websockets; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Constants for asyncapi commands. + * + */ +public class CmdConstants { + public static final String BAL_EXTENSION = ".bal"; + public static final Map TYPE_MAP; + + /** + * Enum to select the code generation mode. + * Ballerina service, mock and client generation is available + */ + public enum GenType { + GEN_SERVICE("gen_service"), + GEN_CLIENT("gen_client"), + GEN_BOTH("gen_both"); + + private String name; + + GenType(String name) { + this.name = name; + } + + @Override + public String toString() { + return this.name; + } + } + public static final String DEFAULT_CLIENT_PKG = "client"; + public static final String CLIENT_FILE_NAME = "client.bal"; + public static final String TYPE_FILE_NAME = "types.bal"; + public static final String TEST_DIR = "tests"; + public static final String TEST_FILE_NAME = "test.bal"; + public static final String CONFIG_FILE_NAME = "Config.toml"; + public static final String DEFAULT_MOCK_PKG = "mock"; + + static { + Map typeMap = new HashMap<>(); + typeMap.put("integer", "int"); + typeMap.put("string", "string"); + typeMap.put("boolean", "boolean"); + typeMap.put("array", "[]"); + typeMap.put("object", "record {}"); + typeMap.put("decimal", "decimal"); + typeMap.put("number", "decimal"); + typeMap.put("double", "decimal"); + typeMap.put("float", "float"); + typeMap.put("binary", "byte[]"); + typeMap.put("byte", "byte[]"); + TYPE_MAP = Collections.unmodifiableMap(typeMap); + } + +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/CmdUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/CmdUtils.java new file mode 100644 index 000000000..f6a732d71 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/cmd/websockets/CmdUtils.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd.websockets; + +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.asyncapi.websocketscore.model.GenSrcFile; +import io.ballerina.tools.diagnostics.DiagnosticInfo; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.ballerina.tools.diagnostics.Location; + +import java.io.File; +import java.util.List; + +/** + * Contains all the util functions used for asyncapi commands. + * + */ +public class CmdUtils { + + /** + * This util method is used to generate {@code Diagnostic} for asyncapi command errors. + */ + public static AsyncAPIDiagnostic constructAsyncAPIDiagnostic(String code, String message, + DiagnosticSeverity severity, Location location, + Object... args) { + + DiagnosticInfo diagnosticInfo = new DiagnosticInfo(code, message, severity); + if (location == null) { + location = new ConverterCommonUtils.NullLocation(); + } + return new AsyncAPIDiagnostic(diagnosticInfo, location, args); + } + + /** + * This method for setting the file name for generated file. + * + * @param listFiles generated files + * @param gFile GenSrcFile object + * @param duplicateCount add the tag with duplicate number if file already exist + */ + public static void setGeneratedFileName(List listFiles, GenSrcFile gFile, int duplicateCount) { + for (File listFile : listFiles) { + String listFileName = listFile.getName(); + if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2) && + (listFileName.split("\\.")[0].equals(gFile.getFileName().split("\\.")[0]))) { + duplicateCount = 1 + duplicateCount; + } + } + gFile.setFileName(gFile.getFileName().split("\\.")[0] + "." + (duplicateCount) + "." + + gFile.getFileName().split("\\.")[1]); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/application/CodeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/application/CodeGenerator.java index 3a744f181..cbd128157 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/application/CodeGenerator.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/application/CodeGenerator.java @@ -18,6 +18,7 @@ package io.ballerina.asyncapi.codegenerator.application; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.configuration.Constants; import io.ballerina.asyncapi.codegenerator.controller.AsyncApiSpecController; @@ -27,7 +28,6 @@ import io.ballerina.asyncapi.codegenerator.controller.SchemaController; import io.ballerina.asyncapi.codegenerator.controller.ServiceTypesController; import io.ballerina.asyncapi.codegenerator.controller.SpecController; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.entity.ServiceType; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; @@ -59,7 +59,7 @@ public void generate(String specPath, String outputPath) throws BallerinaAsyncAp String asyncApiSpecJson = getFileContent(fileRepository, specPath); SpecController specController = new AsyncApiSpecController(asyncApiSpecJson); - Map schemas = specController.getSchemas(); + Map schemas = specController.getSchemas(); List serviceTypes = specController.getServiceTypes(); String eventIdentifierType = specController.getEventIdentifierType(); String eventIdentifierPath = specController.getEventIdentifierPath(); diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/AsyncApiSpecController.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/AsyncApiSpecController.java index 769886b68..3540ead44 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/AsyncApiSpecController.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/AsyncApiSpecController.java @@ -19,13 +19,12 @@ package io.ballerina.asyncapi.codegenerator.controller; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; -import io.apicurio.datamodels.core.util.ReferenceResolverChain; -import io.apicurio.datamodels.openapi.visitors.dereference.Dereferencer; +import io.apicurio.datamodels.deref.Dereferencer; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; +import io.apicurio.datamodels.refs.ReferenceResolverChain; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.entity.MultiChannel; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.entity.ServiceType; import io.ballerina.asyncapi.codegenerator.usecase.ExtractChannelsFromSpec; import io.ballerina.asyncapi.codegenerator.usecase.ExtractIdentifierPathFromSpec; @@ -35,14 +34,13 @@ import java.util.List; import java.util.Map; -import java.util.Set; /** * This class contains extraction of data into entities from the AsyncAPI specification. */ public class AsyncApiSpecController implements SpecController { private List serviceTypes; - private Map schemas; + private Map schemas; private String eventIdentifierType; private String eventIdentifierPath; @@ -51,14 +49,9 @@ public AsyncApiSpecController(String asyncApiSpecJson) throws BallerinaAsyncApiE } private void readSpec(String asyncApiSpecJson) throws BallerinaAsyncApiException { - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); - Dereferencer dereferencer = new Dereferencer(asyncApiSpec, ReferenceResolverChain.getInstance(), false); - asyncApiSpec = (Aai20Document) dereferencer.dereference(); - Set unresolvedRefs = dereferencer.getUnresolvableReferences(); - if (!unresolvedRefs.isEmpty()) { - throw new BallerinaAsyncApiException("Could not resolve some Yaml paths defined in $ref attributes: " - .concat(String.join(", ", unresolvedRefs))); - } + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); + Dereferencer dereferencer = new Dereferencer(ReferenceResolverChain.getInstance(), false); + asyncApiSpec = (AsyncApiDocument) dereferencer.dereference(asyncApiSpec); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); Extractor extractSchemas = new ExtractSchemasFromSpec(asyncApiSpec); @@ -79,7 +72,7 @@ public List getServiceTypes() { } @Override - public Map getSchemas() { + public Map getSchemas() { return schemas; } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SchemaController.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SchemaController.java index 6bfb4048a..4edac8a62 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SchemaController.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SchemaController.java @@ -18,9 +18,9 @@ package io.ballerina.asyncapi.codegenerator.controller; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.configuration.Constants; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.usecase.GenerateModuleMemberDeclarationNode; import io.ballerina.asyncapi.codegenerator.usecase.GenerateUnionDescriptorNode; import io.ballerina.asyncapi.codegenerator.usecase.Generator; @@ -45,9 +45,9 @@ * This file contains the logics and functions related to code generation of the data_types.bal. */ public class SchemaController implements BalController { - private final Map schemas; + private final Map schemas; - public SchemaController(Map schemas) { + public SchemaController(Map schemas) { this.schemas = schemas; } @@ -55,7 +55,7 @@ public SchemaController(Map schemas) { public String generateBalCode(String balTemplate) throws BallerinaAsyncApiException { List recordNodes = new ArrayList<>(); List typeDescriptorNodes = new ArrayList<>(); - for (Map.Entry fields : schemas.entrySet()) { + for (Map.Entry fields : schemas.entrySet()) { Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(fields); ModuleMemberDeclarationNode typeDefinitionNode = generateRecordNode.generate(); if (typeDefinitionNode instanceof TypeDefinitionNode) { diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SpecController.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SpecController.java index b1b99a88a..5077d6f01 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SpecController.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/controller/SpecController.java @@ -18,7 +18,7 @@ package io.ballerina.asyncapi.codegenerator.controller; -import io.ballerina.asyncapi.codegenerator.entity.Schema; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.entity.ServiceType; import java.util.List; @@ -29,7 +29,7 @@ */ public interface SpecController { List getServiceTypes(); - Map getSchemas(); + Map getSchemas(); String getEventIdentifierType(); String getEventIdentifierPath(); } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/MultiChannel.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/MultiChannel.java index 1c362b0b9..7ac2c6697 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/MultiChannel.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/MultiChannel.java @@ -18,6 +18,8 @@ package io.ballerina.asyncapi.codegenerator.entity; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; + import java.util.List; import java.util.Map; @@ -26,9 +28,9 @@ */ public class MultiChannel { private final List serviceTypes; - private final Map inlineSchemas; + private final Map inlineSchemas; - public MultiChannel(List serviceTypes, Map inlineSchemas) { + public MultiChannel(List serviceTypes, Map inlineSchemas) { this.serviceTypes = serviceTypes; this.inlineSchemas = inlineSchemas; } @@ -37,7 +39,7 @@ public List getServiceTypes() { return serviceTypes; } - public Map getInlineSchemas() { + public Map getInlineSchemas() { return inlineSchemas; } } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/Schema.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/Schema.java deleted file mode 100644 index 4c2280410..000000000 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/Schema.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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 - * - * http://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 io.ballerina.asyncapi.codegenerator.entity; - -import java.util.List; -import java.util.Map; - -/** - * Entity used for schema definition. - */ -public interface Schema { - String getRef(); - - void setRef(String ref); - - String getFormat(); - - void setFormat(String format); - - String getTitle(); - - void setTitle(String title); - - String getDescription(); - - void setDescription(String description); - - Object getDefault(); - - void setDefault(Object defaultValue); - - Number getMultipleOf(); - - void setMultipleOf(Number multipleOf); - - Number getMaximum(); - - void setMaximum(Number maximum); - - Boolean getExclusiveMaximum(); - - void setExclusiveMaximum(Boolean exclusiveMaximum); - - Number getMinimum(); - - void setMinimum(Number minimum); - - Boolean getExclusiveMinimum(); - - void setExclusiveMinimum(Boolean exclusiveMinimum); - - Number getMaxLength(); - - void setMaxLength(Number maxLength); - - Number getMinLength(); - - void setMinLength(Number minLength); - - String getPattern(); - - void setPattern(String pattern); - - Number getMaxItems(); - - void setMaxItems(Number maxItems); - - Number getMinItems(); - - void setMinItems(Number minItems); - - Boolean getUniqueItems(); - - void setUniqueItems(Boolean uniqueItems); - - Number getMaxProperties(); - - void setMaxProperties(Number maxProperties); - - Number getMinProperties(); - - void setMinProperties(Number minProperties); - - List getRequired(); - - void setRequired(List required); - - List getEnum(); - - void setEnum(List enumValue); - - String getType(); - - void setType(String type); - - Object getItems(); - - void setItems(Object items); - - List getAllOf(); - - List getOneOf(); - - List getAnyOf(); - - Schema getNot(); - - Map getSchemaProperties(); - - Object getAdditionalProperties(); - - void setAdditionalProperties(Object additionalProperties); - - Boolean getReadOnly(); - - void setReadOnly(Boolean readOnly); - - Boolean getWriteOnly(); - - void setWriteOnly(Boolean writeOnly); - - String getDiscriminator(); - - void setDiscriminator(String discriminator); - - Boolean getDeprecated(); - - void setDeprecated(Boolean deprecated); - - Object getExample(); - - void setExample(Object example); - - Object getExtension(String name); - - boolean hasExtraProperties(); - - List getExtraPropertyNamesList(); - - Object getExtraProperty(String name); -} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/SchemaDecorator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/SchemaDecorator.java deleted file mode 100644 index 9ea1df2b6..000000000 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/entity/SchemaDecorator.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you 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 - * - * http://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 io.ballerina.asyncapi.codegenerator.entity; - -import io.apicurio.datamodels.asyncapi.models.AaiSchema; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * Decorator which implements the interface Schema and purpose of this is to hide the ApiCurio Library entities from - * the other layers. - */ -public class SchemaDecorator implements Schema { - private final AaiSchema aaiSchema; - - @Override - public Object getExtension(String name) { - return aaiSchema.getExtension(name); - } - - public SchemaDecorator(AaiSchema aaiSchema) { - this.aaiSchema = aaiSchema; - } - - @Override - public String getRef() { - return aaiSchema.$ref; - } - - @Override - public void setRef(String ref) { - aaiSchema.$ref = ref; - } - - @Override - public String getFormat() { - return aaiSchema.format; - } - - @Override - public void setFormat(String format) { - aaiSchema.format = format; - } - - @Override - public String getTitle() { - return aaiSchema.title; - } - - @Override - public void setTitle(String title) { - aaiSchema.title = title; - } - - @Override - public String getDescription() { - return aaiSchema.description; - } - - @Override - public void setDescription(String description) { - aaiSchema.description = description; - } - - @Override - public Object getDefault() { - return aaiSchema.default_; - } - - @Override - public void setDefault(Object defaultValue) { - aaiSchema.default_ = defaultValue; - } - - @Override - public Number getMultipleOf() { - return aaiSchema.multipleOf; - } - - @Override - public void setMultipleOf(Number multipleOf) { - aaiSchema.multipleOf = multipleOf; - } - - @Override - public Number getMaximum() { - return aaiSchema.maximum; - } - - @Override - public void setMaximum(Number maximum) { - aaiSchema.maximum = maximum; - } - - @Override - public Boolean getExclusiveMaximum() { - return aaiSchema.exclusiveMaximum; - } - - @Override - public void setExclusiveMaximum(Boolean exclusiveMaximum) { - aaiSchema.exclusiveMaximum = exclusiveMaximum; - } - - @Override - public Number getMinimum() { - return aaiSchema.minimum; - } - - @Override - public void setMinimum(Number minimum) { - aaiSchema.minimum = minimum; - } - - @Override - public Boolean getExclusiveMinimum() { - return aaiSchema.exclusiveMinimum; - } - - @Override - public void setExclusiveMinimum(Boolean exclusiveMinimum) { - aaiSchema.exclusiveMinimum = exclusiveMinimum; - } - - @Override - public Number getMaxLength() { - return aaiSchema.maxLength; - } - - @Override - public void setMaxLength(Number maxLength) { - aaiSchema.maxLength = maxLength; - } - - @Override - public Number getMinLength() { - return aaiSchema.minLength; - } - - @Override - public void setMinLength(Number minLength) { - aaiSchema.minLength = minLength; - } - - @Override - public String getPattern() { - return aaiSchema.pattern; - } - - @Override - public void setPattern(String pattern) { - aaiSchema.pattern = pattern; - } - - @Override - public Number getMaxItems() { - return aaiSchema.maxItems; - } - - @Override - public void setMaxItems(Number maxItems) { - aaiSchema.maxItems = maxItems; - } - - @Override - public Number getMinItems() { - return aaiSchema.minItems; - } - - @Override - public void setMinItems(Number minItems) { - aaiSchema.minItems = minItems; - } - - @Override - public Boolean getUniqueItems() { - return aaiSchema.uniqueItems; - } - - @Override - public void setUniqueItems(Boolean uniqueItems) { - aaiSchema.uniqueItems = uniqueItems; - } - - @Override - public Number getMaxProperties() { - return aaiSchema.maxProperties; - } - - @Override - public void setMaxProperties(Number maxProperties) { - aaiSchema.maxProperties = maxProperties; - } - - @Override - public Number getMinProperties() { - return aaiSchema.minProperties; - } - - @Override - public void setMinProperties(Number minProperties) { - aaiSchema.minProperties = minProperties; - } - - @Override - public List getRequired() { - return aaiSchema.required; - } - - @Override - public void setRequired(List required) { - aaiSchema.required = required; - } - - @Override - public List getEnum() { - return aaiSchema.enum_; - } - - @Override - public void setEnum(List enumValue) { - aaiSchema.enum_ = enumValue; - } - - @Override - public String getType() { - return aaiSchema.type; - } - - @Override - public void setType(String type) { - aaiSchema.type = type; - } - - @Override - public Object getItems() { - if (aaiSchema.items instanceof AaiSchema) { - return new SchemaDecorator((AaiSchema) aaiSchema.items); - } else if (aaiSchema.items instanceof List) { - return ((List) aaiSchema.items).stream().map(SchemaDecorator::new).collect(Collectors.toList()); - } - return null; - } - - @Override - public void setItems(Object items) { - aaiSchema.items = items; - } - - @Override - public List getAllOf() { - return aaiSchema.allOf.stream().map(SchemaDecorator::new).collect(Collectors.toList()); - } - - @Override - public List getOneOf() { - return aaiSchema.oneOf.stream().map(SchemaDecorator::new).collect(Collectors.toList()); - } - - @Override - public List getAnyOf() { - return aaiSchema.anyOf.stream().map(SchemaDecorator::new).collect(Collectors.toList()); - } - - @Override - public Schema getNot() { - return new SchemaDecorator(aaiSchema.not); - } - - @Override - public Map getSchemaProperties() { - if (aaiSchema.properties == null) { - return null; - } - return aaiSchema.properties.entrySet() - .stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new SchemaDecorator(e.getValue()))); - } - - @Override - public Object getAdditionalProperties() { - return aaiSchema.additionalProperties; - } - - @Override - public void setAdditionalProperties(Object additionalProperties) { - aaiSchema.additionalProperties = additionalProperties; - } - - @Override - public Boolean getReadOnly() { - return aaiSchema.readOnly; - } - - @Override - public void setReadOnly(Boolean readOnly) { - aaiSchema.readOnly = readOnly; - } - - @Override - public Boolean getWriteOnly() { - return aaiSchema.writeOnly; - } - - @Override - public void setWriteOnly(Boolean writeOnly) { - aaiSchema.writeOnly = writeOnly; - } - - @Override - public String getDiscriminator() { - return aaiSchema.discriminator; - } - - @Override - public void setDiscriminator(String discriminator) { - aaiSchema.discriminator = discriminator; - } - - @Override - public Boolean getDeprecated() { - return aaiSchema.deprecated; - } - - @Override - public void setDeprecated(Boolean deprecated) { - aaiSchema.deprecated = deprecated; - } - - @Override - public Object getExample() { - return aaiSchema.example; - } - - @Override - public void setExample(Object example) { - aaiSchema.example = example; - } - - @Override - public boolean hasExtraProperties() { - return aaiSchema.hasExtraProperties(); - } - - @Override - public List getExtraPropertyNamesList() { - return aaiSchema.getExtraPropertyNames(); - } - - @Override - public Object getExtraProperty(String name) { - return aaiSchema.getExtraProperty(name); - } -} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpec.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpec.java index 468f173a5..8133bfd24 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpec.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpec.java @@ -18,23 +18,24 @@ package io.ballerina.asyncapi.codegenerator.usecase; -import io.apicurio.datamodels.asyncapi.models.AaiChannelItem; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.models.AaiMessage; -import io.apicurio.datamodels.asyncapi.models.AaiSchema; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20NodeFactory; -import io.apicurio.datamodels.compat.JsonCompat; -import io.apicurio.datamodels.core.factories.VisitorFactory; -import io.apicurio.datamodels.core.io.DataModelReader; -import io.apicurio.datamodels.core.models.DocumentType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.apicurio.datamodels.models.asyncapi.AsyncApiChannelItem; +import io.apicurio.datamodels.models.asyncapi.AsyncApiChannels; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiMessage; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; +import io.apicurio.datamodels.models.asyncapi.v20.AsyncApi20Schema; +import io.apicurio.datamodels.models.asyncapi.v20.AsyncApi20SchemaImpl; +import io.apicurio.datamodels.models.asyncapi.v20.io.AsyncApi20ModelReader; +import io.apicurio.datamodels.models.util.JsonUtil; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.configuration.Constants; import io.ballerina.asyncapi.codegenerator.entity.MultiChannel; import io.ballerina.asyncapi.codegenerator.entity.RemoteFunction; -import io.ballerina.asyncapi.codegenerator.entity.Schema; -import io.ballerina.asyncapi.codegenerator.entity.SchemaDecorator; import io.ballerina.asyncapi.codegenerator.entity.ServiceType; import io.ballerina.asyncapi.codegenerator.usecase.utils.CodegenUtils; +import io.ballerina.asyncapi.codegenerator.usecase.utils.ExtensionExtractor; import java.util.ArrayList; import java.util.HashMap; @@ -45,11 +46,10 @@ * Extract the service types from the AsyncAPI specification. */ public class ExtractChannelsFromSpec implements Extractor { - private final AaiDocument asyncApiSpec; + private final AsyncApiDocument asyncApiSpec; private final CodegenUtils codegenUtils = new CodegenUtils(); - private Map inlineSchemas; - - public ExtractChannelsFromSpec(AaiDocument asyncApiSpec) { + private Map inlineSchemas; + public ExtractChannelsFromSpec(AsyncApiDocument asyncApiSpec) { this.asyncApiSpec = asyncApiSpec; this.inlineSchemas = new HashMap<>(); } @@ -57,32 +57,36 @@ public ExtractChannelsFromSpec(AaiDocument asyncApiSpec) { @Override public MultiChannel extract() throws BallerinaAsyncApiException { List serviceTypes = new ArrayList<>(); - for (Map.Entry channel : asyncApiSpec.channels.entrySet()) { + AsyncApiChannels channels = asyncApiSpec.getChannels(); + List channelNames = channels.getItemNames(); + List channelItems = channels.getItems(); + for (int i = 0; i < channelNames.size(); i++) { String serviceTypeName; List remoteFunctions = new ArrayList<>(); - if (channel.getValue().getExtension(Constants.X_BALLERINA_SERVICE_TYPE) == null) { - serviceTypeName = codegenUtils.getValidName(channel.getKey(), true); + if (!ExtensionExtractor.getExtensions(channelItems.get(i)) + .containsKey(Constants.X_BALLERINA_SERVICE_TYPE)) { + serviceTypeName = codegenUtils.getValidName(channelNames.get(i), true); } else { - serviceTypeName = channel.getValue() - .getExtension(Constants.X_BALLERINA_SERVICE_TYPE).value.toString(); + serviceTypeName = ExtensionExtractor.getExtensions(channelItems.get(i)) + .get(Constants.X_BALLERINA_SERVICE_TYPE).asText(); } - AaiMessage mainMessage = channel.getValue().subscribe.message; - if (mainMessage.oneOf != null) { - for (AaiMessage message : mainMessage.oneOf) { - validateMessage(channel, message); - String xBallerinaEventType = - message.getExtension(Constants.X_BALLERINA_EVENT_TYPE).value.toString(); + AsyncApiMessage mainMessage = channelItems.get(i).getSubscribe().getMessage(); + if (mainMessage.getOneOf() != null) { + for (AsyncApiMessage message : mainMessage.getOneOf()) { + validateMessage(channelNames.get(i), channelItems.get(i), message); + String xBallerinaEventType = ExtensionExtractor.getExtensions(message) + .get(Constants.X_BALLERINA_EVENT_TYPE).asText(); RemoteFunction remoteFunction = new RemoteFunction( xBallerinaEventType, - getEventType(message, channel.getKey(), xBallerinaEventType)); + getEventType(message, channelNames.get(i), xBallerinaEventType)); remoteFunctions.add(remoteFunction); } } else { - validateMessage(channel, mainMessage); - String xBallerinaEventType = channel.getValue() - .subscribe.message.getExtension(Constants.X_BALLERINA_EVENT_TYPE).value.toString(); + validateMessage(channelNames.get(i), channelItems.get(i), mainMessage); + String xBallerinaEventType = ExtensionExtractor.getExtensions(channelItems.get(i) + .getSubscribe().getMessage()).get(Constants.X_BALLERINA_EVENT_TYPE).asText(); RemoteFunction remoteFunction = new RemoteFunction(xBallerinaEventType, - getEventType(mainMessage, channel.getKey(), xBallerinaEventType)); + getEventType(mainMessage, channelNames.get(i), xBallerinaEventType)); remoteFunctions.add(remoteFunction); } ServiceType serviceType = new ServiceType(serviceTypeName, remoteFunctions); @@ -91,38 +95,46 @@ public MultiChannel extract() throws BallerinaAsyncApiException { return new MultiChannel(serviceTypes, inlineSchemas); } - private String getEventType(AaiMessage message, String channelName, String xBallerinaEventType) + private String getEventType(AsyncApiMessage message, String channelName, String xBallerinaEventType) throws BallerinaAsyncApiException { - if (!JsonCompat.isPropertyDefined(message.payload, "$ref")) { - DataModelReader reader = VisitorFactory.createDataModelReader(DocumentType.asyncapi2); - AaiSchema schemaModel = (new Aai20NodeFactory()).createSchemaDefinition(null, xBallerinaEventType); - reader.readSchema(message.payload, schemaModel); - inlineSchemas.put(xBallerinaEventType, new SchemaDecorator(schemaModel)); + if (!JsonUtil.isPropertyDefined(message.getPayload(), "$ref")) { + AsyncApi20Schema schemaModel = new AsyncApi20SchemaImpl().createSchema(); + AsyncApi20ModelReader reader = new AsyncApi20ModelReader(); + if (message.getPayload() instanceof ObjectNode) { + reader.readSchema((ObjectNode) message.getPayload(), schemaModel); + } else { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode messagePayLoadObject = mapper.createObjectNode(); + message.getPayload().fields().forEachRemaining(entry -> + messagePayLoadObject.set(entry.getKey(), entry.getValue())); + reader.readSchema(messagePayLoadObject, schemaModel); + } + inlineSchemas.put(xBallerinaEventType, schemaModel); return xBallerinaEventType; //TODO: handle the scenario with both $ref is there directly under the properties } - String ref = JsonCompat.getPropertyString(message.payload, "$ref"); + String ref = JsonUtil.getStringProperty((ObjectNode) message.getPayload(), "$ref"); String[] refParts = ref.split("/"); String schemaName = refParts[refParts.length - 1]; - if (asyncApiSpec.components == null || asyncApiSpec.components.schemas == null - || !asyncApiSpec.components.schemas.containsKey(schemaName)) { + if (asyncApiSpec.getComponents() == null || asyncApiSpec.getComponents().getSchemas() == null + || !asyncApiSpec.getComponents().getSchemas().containsKey(schemaName)) { throw new BallerinaAsyncApiException("Could not find the schema '" + schemaName + "' in the the path #/components/schemas"); } return schemaName; } - private void validateMessage(Map.Entry channel, AaiMessage message) + private void validateMessage(String channelName, AsyncApiChannelItem channelItem, AsyncApiMessage message) throws BallerinaAsyncApiException { - if (message.getExtension(Constants.X_BALLERINA_EVENT_TYPE) == null) { + if (!ExtensionExtractor.getExtensions(message).containsKey(Constants.X_BALLERINA_EVENT_TYPE)) { throw new BallerinaAsyncApiException( "Could not find the ".concat(Constants.X_BALLERINA_EVENT_TYPE) - .concat(" attribute in the message of the channel ").concat(channel.getKey())); + .concat(" attribute in the message of the channel ").concat(channelName)); } - if (message.payload == null) { + if (message.getPayload() == null) { throw new BallerinaAsyncApiException( "Could not find the payload reference in the message of the channel " - .concat(channel.getKey())); + .concat(channelName)); } } } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpec.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpec.java index 4c66a00de..768c2d921 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpec.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpec.java @@ -18,29 +18,37 @@ package io.ballerina.asyncapi.codegenerator.usecase; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.core.models.Extension; +import com.fasterxml.jackson.databind.JsonNode; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.configuration.Constants; +import io.ballerina.asyncapi.codegenerator.usecase.utils.ExtensionExtractor; import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; /** * Extract the identifier path from the AsyncAPI specification. */ public class ExtractIdentifierPathFromSpec implements Extractor { - private final AaiDocument asyncApiSpec; + private final AsyncApiDocument asyncApiSpec; - public ExtractIdentifierPathFromSpec(AaiDocument asyncApiSpec) { + public ExtractIdentifierPathFromSpec(AsyncApiDocument asyncApiSpec) { this.asyncApiSpec = asyncApiSpec; } @Override public String extract() throws BallerinaAsyncApiException { - Extension identifier = asyncApiSpec.getExtension( - Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER); - HashMap valuesMap = (HashMap) identifier.value; - StringBuilder eventPathString = new StringBuilder(""); + JsonNode identifier = ExtensionExtractor.getExtensions(asyncApiSpec) + .get(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER); + Iterator> values = identifier.fields(); + HashMap valuesMap = new HashMap<>(); + while (values.hasNext()) { + Map.Entry entry = values.next(); + valuesMap.put(entry.getKey(), entry.getValue().asText()); + } + StringBuilder eventPathString = new StringBuilder(); if (valuesMap.get(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER_TYPE) .equals(Constants.X_BALLERINA_EVENT_TYPE_HEADER)) { // Handle header event path diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpec.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpec.java index f95d90a39..7887531d9 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpec.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpec.java @@ -18,32 +18,40 @@ package io.ballerina.asyncapi.codegenerator.usecase; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.core.models.Extension; +import com.fasterxml.jackson.databind.JsonNode; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.configuration.Constants; +import io.ballerina.asyncapi.codegenerator.usecase.utils.ExtensionExtractor; import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; /** * Extract the identifier type from the AsyncAPI specification. */ public class ExtractIdentifierTypeFromSpec implements Extractor { - private final AaiDocument asyncApiSpec; + private final AsyncApiDocument asyncApiSpec; - public ExtractIdentifierTypeFromSpec(AaiDocument asyncApiSpec) { + public ExtractIdentifierTypeFromSpec(AsyncApiDocument asyncApiSpec) { this.asyncApiSpec = asyncApiSpec; } @Override public String extract() throws BallerinaAsyncApiException { - if (asyncApiSpec.getExtension(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER) == null) { + if (!ExtensionExtractor.getExtensions(asyncApiSpec).containsKey(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER)) { throw new BallerinaAsyncApiException(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER .concat(" attribute is not found in the Async API Specification")); } - Extension identifier = asyncApiSpec.getExtension( - Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER); - HashMap valuesMap = (HashMap) identifier.value; + JsonNode identifier = ExtensionExtractor.getExtensions(asyncApiSpec) + .get(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER); + Iterator> values = identifier.fields(); + HashMap valuesMap = new HashMap<>(); + while (values.hasNext()) { + Map.Entry entry = values.next(); + valuesMap.put(entry.getKey(), entry.getValue().asText()); + } if (!valuesMap.containsKey(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER_TYPE)) { throw new BallerinaAsyncApiException(Constants.X_BALLERINA_EVENT_FIELD_IDENTIFIER_TYPE .concat(" attribute is not found within the attribute " diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpec.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpec.java index 807924590..09522be9e 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpec.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpec.java @@ -18,10 +18,9 @@ package io.ballerina.asyncapi.codegenerator.usecase; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; -import io.ballerina.asyncapi.codegenerator.entity.Schema; -import io.ballerina.asyncapi.codegenerator.entity.SchemaDecorator; import java.util.HashMap; import java.util.Map; @@ -31,18 +30,18 @@ * Extract the schemas from the AsyncAPI specification. */ public class ExtractSchemasFromSpec implements Extractor { - private final AaiDocument asyncApiSpec; + private final AsyncApiDocument asyncApiSpec; - public ExtractSchemasFromSpec(AaiDocument asyncApiSpec) { + public ExtractSchemasFromSpec(AsyncApiDocument asyncApiSpec) { this.asyncApiSpec = asyncApiSpec; } @Override - public Map extract() throws BallerinaAsyncApiException { - if (asyncApiSpec.components != null && asyncApiSpec.components.schemas != null - && !asyncApiSpec.components.schemas.entrySet().isEmpty()) { - return asyncApiSpec.components.schemas.entrySet() - .stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new SchemaDecorator(e.getValue()))); + public Map extract() throws BallerinaAsyncApiException { + if (asyncApiSpec.getComponents() != null && asyncApiSpec.getComponents().getSchemas() != null + && !asyncApiSpec.getComponents().getSchemas().entrySet().isEmpty()) { + return asyncApiSpec.getComponents().getSchemas().entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, entry -> (AsyncApiSchema) entry.getValue())); } return new HashMap<>(); } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNode.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNode.java index e1a3d3d19..838803b07 100644 --- a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNode.java +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNode.java @@ -18,13 +18,16 @@ package io.ballerina.asyncapi.codegenerator.usecase; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.TextNode; -import io.apicurio.datamodels.core.models.Extension; +import io.apicurio.datamodels.models.Referenceable; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.configuration.Constants; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.usecase.utils.CodegenUtils; import io.ballerina.asyncapi.codegenerator.usecase.utils.DocCommentsUtils; +import io.ballerina.asyncapi.codegenerator.usecase.utils.ExtensionExtractor; import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.ArrayDimensionNode; import io.ballerina.compiler.syntax.tree.IdentifierToken; @@ -41,6 +44,7 @@ import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -72,12 +76,12 @@ * Generate the record node for data_types.bal. */ public class GenerateModuleMemberDeclarationNode implements Generator { - private final Map.Entry recordFields; + private final Map.Entry recordFields; private final CodegenUtils codegenUtils = new CodegenUtils(); private final DocCommentsUtils commentsUtils = new DocCommentsUtils(); - public GenerateModuleMemberDeclarationNode(Map.Entry recordFields) { + public GenerateModuleMemberDeclarationNode(Map.Entry recordFields) { this.recordFields = recordFields; } @@ -108,7 +112,7 @@ public ModuleMemberDeclarationNode generate() throws BallerinaAsyncApiException return createEnumDeclarationNode(metadataNode, createToken(PUBLIC_KEYWORD), createToken(ENUM_KEYWORD), typeName, createToken(OPEN_BRACE_TOKEN), createSeparatedNodeList(enums), createToken(CLOSE_BRACE_TOKEN), null); - } else if (recordFields.getValue().getSchemaProperties() == null && recordFields.getValue().getType() != null) { + } else if (recordFields.getValue().getProperties() == null && recordFields.getValue().getType() != null) { // Handle when the schema is defined directly under the name // (i.e. there is no properties attribute under the schema) TypeDescriptorNode fieldTypeName = getTypeDescriptorNode(recordFields.getValue()); @@ -118,10 +122,14 @@ typeName, createOptionalTypeDescriptorNode( fieldTypeName, createToken(QUESTION_MARK_TOKEN)), createToken(SEMICOLON_TOKEN)); return typeDefinitionNode; - } else if (recordFields.getValue().getSchemaProperties() != null) { + } else if (recordFields.getValue().getProperties() != null) { // Handle when the properties attribute is there inside the schema - for (Map.Entry field : recordFields.getValue().getSchemaProperties().entrySet()) { - addRecordField(requiredList, recordFieldList, field); + for (Map.Entry field : recordFields.getValue().getProperties().entrySet()) { + Map.Entry castedField = new AbstractMap.SimpleEntry<>( + field.getKey(), + (AsyncApiSchema) field.getValue() + ); + addRecordField(requiredList, recordFieldList, castedField); } } else if (recordFields.getValue().hasExtraProperties()) { // TODO: handle when the fields are directly under the Schema. @@ -140,7 +148,8 @@ typeName, createOptionalTypeDescriptorNode( /** * This method generates a record field with given schema properties. */ - private void addRecordField(List required, List recordFieldList, Map.Entry field) + private void addRecordField(List required, List recordFieldList, Map.Entry field) throws BallerinaAsyncApiException { // TODO: Handle allOf , oneOf, anyOf RecordFieldNode recordFieldNode; @@ -175,13 +184,13 @@ private void addRecordField(List required, List recordFieldList, M recordFieldList.add(recordFieldNode); } - private TypeDescriptorNode getTypeDescriptorNode(Schema schema) + private TypeDescriptorNode getTypeDescriptorNode(AsyncApiSchema schema) throws BallerinaAsyncApiException { - if (schema.getType() != null || schema.getSchemaProperties() != null) { + if (schema.getType() != null || schema.getProperties() != null) { TypeDescriptorNode originalTypeDesc = getTypeDescriptorNodeForObjects(schema); return addNullableType(schema, originalTypeDesc); - } else if (schema.getRef() != null) { - String type = codegenUtils.extractReferenceType(schema.getRef()); + } else if ((schema instanceof Referenceable) && ((Referenceable) schema).get$ref() != null) { + String type = codegenUtils.extractReferenceType(((Referenceable) schema).get$ref()); type = codegenUtils.getValidName(type, true); Token typeName = AbstractNodeFactory.createIdentifierToken(type); TypeDescriptorNode originalTypeDesc = createBuiltinSimpleNameReferenceNode(null, typeName); @@ -195,8 +204,9 @@ private TypeDescriptorNode getTypeDescriptorNode(Schema schema) } } - private TypeDescriptorNode getTypeDescriptorNodeForObjects(Schema schema) throws BallerinaAsyncApiException { - if (schema.getSchemaProperties() != null) { + private TypeDescriptorNode getTypeDescriptorNodeForObjects(AsyncApiSchema schema) + throws BallerinaAsyncApiException { + if (schema.getProperties() != null) { return getRecordTypeDescriptorNode(schema); } else if (schema.getType() != null) { return getTypeDescriptorNodeFroPreDefined(schema); @@ -206,7 +216,8 @@ private TypeDescriptorNode getTypeDescriptorNodeForObjects(Schema schema) throws } } - private TypeDescriptorNode getTypeDescriptorNodeFroPreDefined(Schema schema) throws BallerinaAsyncApiException { + private TypeDescriptorNode getTypeDescriptorNodeFroPreDefined(AsyncApiSchema schema) + throws BallerinaAsyncApiException { switch (schema.getType()) { case Constants.INTEGER: case Constants.STRING: @@ -224,9 +235,9 @@ private TypeDescriptorNode getTypeDescriptorNodeFroPreDefined(Schema schema) thr case Constants.ARRAY: return getTypeDescriptorNodeForArraySchema(schema); case Constants.OBJECT: - if (schema.getRef() != null) { + if ((schema instanceof Referenceable) && ((Referenceable) schema).get$ref() != null) { type = codegenUtils.getValidName( - codegenUtils.extractReferenceType(schema.getRef()), true); + codegenUtils.extractReferenceType(((Referenceable) schema).get$ref()), true); typeName = AbstractNodeFactory.createIdentifierToken(type); } else { typeName = AbstractNodeFactory.createIdentifierToken( @@ -239,15 +250,20 @@ private TypeDescriptorNode getTypeDescriptorNodeFroPreDefined(Schema schema) thr } } - private RecordTypeDescriptorNode getRecordTypeDescriptorNode(Schema schema) throws BallerinaAsyncApiException { - Map properties = schema.getSchemaProperties(); + private RecordTypeDescriptorNode getRecordTypeDescriptorNode(AsyncApiSchema schema) + throws BallerinaAsyncApiException { + Map properties = schema.getProperties(); Token recordKeyWord = AbstractNodeFactory.createIdentifierToken("record "); Token bodyStartDelimiter = AbstractNodeFactory.createIdentifierToken("{ "); Token bodyEndDelimiter = AbstractNodeFactory.createIdentifierToken("} "); List recordFList = new ArrayList<>(); List required = schema.getRequired(); for (Map.Entry property : properties.entrySet()) { - addRecordField(required, recordFList, property); + Map.Entry castedProperty = new AbstractMap.SimpleEntry<>( + property.getKey(), + (AsyncApiSchema) property.getValue() + ); + addRecordField(required, recordFList, castedProperty); } NodeList fieldNodes = AbstractNodeFactory.createNodeList(recordFList); @@ -294,20 +310,21 @@ public static String convertAsyncAPITypeToBallerina(String type) throws Ballerin } - public TypeDescriptorNode getTypeDescriptorNodeForArraySchema(Schema schema) throws BallerinaAsyncApiException { + public TypeDescriptorNode getTypeDescriptorNodeForArraySchema(AsyncApiSchema schema) + throws BallerinaAsyncApiException { if (schema.getItems() != null) { String type; Token typeName; TypeDescriptorNode memberTypeDesc; Token openSBracketToken = AbstractNodeFactory.createIdentifierToken("["); // TODO: handle this when schema.items is a List in the below line - Schema schemaItem = (Schema) schema.getItems(); + AsyncApiSchema schemaItem = (AsyncApiSchema) schema.getItems(); Token closeSBracketToken = AbstractNodeFactory.createIdentifierToken("]"); ArrayDimensionNode arrayDimensionNode = NodeFactory.createArrayDimensionNode(openSBracketToken, null, closeSBracketToken); - if (schemaItem.getRef() != null) { + if ((schemaItem instanceof Referenceable) && ((Referenceable) schemaItem).get$ref() != null) { type = codegenUtils.getValidName(codegenUtils.extractReferenceType( - schemaItem.getRef()), true); + ((Referenceable) schemaItem).get$ref()), true); typeName = AbstractNodeFactory.createIdentifierToken(type); memberTypeDesc = createBuiltinSimpleNameReferenceNode(null, typeName); // TODO: memberTypeDesc != ArrayTypeDescriptorNode @@ -332,10 +349,11 @@ public TypeDescriptorNode getTypeDescriptorNodeForArraySchema(Schema schema) thr } } - private TypeDescriptorNode addNullableType(Schema schema, TypeDescriptorNode originalTypeDesc) { - if (schema.getExtension("x-nullable") != null) { - Extension identifier = (Extension) schema.getExtension("x-nullable"); - if (identifier.value.equals(true)) { + private TypeDescriptorNode addNullableType(AsyncApiSchema schema, TypeDescriptorNode originalTypeDesc) { + Map ext = ExtensionExtractor.getExtensions(schema); + if (ExtensionExtractor.getExtensions(schema).containsKey("x-nullable")) { + JsonNode identifier = ExtensionExtractor.getExtensions(schema).get("x-nullable"); + if (identifier.asText().equals("true")) { return createOptionalTypeDescriptorNode(originalTypeDesc, createToken(QUESTION_MARK_TOKEN)); } } diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/utils/ExtensionExtractor.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/utils/ExtensionExtractor.java new file mode 100644 index 000000000..f0405e6f8 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/codegenerator/usecase/utils/ExtensionExtractor.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.codegenerator.usecase.utils; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * This class provides utility methods to extract extensions from a JsonNode. + * + */ +public class ExtensionExtractor { + public static Map getExtensions(Object object) { + try { + Class cls = object.getClass(); + Method method = cls.getMethod("getExtensions"); + Object map = method.invoke(object); + if (map instanceof Map) { + return (Map) map; + } + throw new ClassCastException(); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassCastException e) { + return new HashMap<>(); + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/ErrorMessages.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/ErrorMessages.java new file mode 100644 index 000000000..4e800b506 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/ErrorMessages.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore; + +/** + * Container for error messages of the AsyncAPI command. + * + */ +public class ErrorMessages { + + public static String invalidFilePath(String path) { + return String.format("AsyncAPI contract doesn't exist in the given location:%n%s", path); + } + + public static String invalidFileType() { + return "Invalid file type. Provide either a .yaml or .json file."; + } + +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/GeneratorConstants.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/GeneratorConstants.java new file mode 100644 index 000000000..704f234b7 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/GeneratorConstants.java @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore; + +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.StatementNode; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createExpressionStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionCallExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createQualifiedNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_CALL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; + +/** + * Constants for asyncapi code generator. + * + */ +public class GeneratorConstants { + + public static final String UTIL_FILE_NAME = "utils.bal"; + public static final String ASYNCAPI_PATH_SEPARATOR = "/"; + public static final String ESCAPE_PATTERN = "([\\[\\]\\\\?!<>@#&~`*\\-=^+();:\\/{}\\s|.$])"; + public static final String HTTP = "http"; + public static final String WEBSOCKET = "websocket"; + public static final String SIMPLE_PIPE = "pipe"; + public static final String UUID = "uuid"; + public static final String CAPITAL_PIPE = "Pipe"; + public static final String CAPITAL_ERROR = "Error"; + public static final QualifiedNameReferenceNode PIPE_ERROR_NODE = createQualifiedNameReferenceNode( + createIdentifierToken(SIMPLE_PIPE), createToken(COLON_TOKEN), createIdentifierToken(CAPITAL_ERROR)); + public static final QualifiedNameReferenceNode WS_ERROR = createQualifiedNameReferenceNode( + createIdentifierToken(WEBSOCKET), createToken(COLON_TOKEN), createIdentifierToken(CAPITAL_ERROR)); + public static final OptionalTypeDescriptorNode WS_ERROR_OPTIONAL = createOptionalTypeDescriptorNode( + WS_ERROR, createToken(QUESTION_MARK_TOKEN)); + public static final String TRUE = "true"; + public static final String URL = "url"; + public static final String MODULE_TEST = "test"; + public static final String BALLERINA = "ballerina"; + //Honour goes to Nuvindu + public static final String XLIBB = "xlibb"; + public static final String XLIBB_PIPE = "pipe"; + public static final String LOG = "log"; + public static final String X_DISPATCHER_KEY = "x-dispatcherKey"; + public static final String X_DISPATCHER_STREAM_ID = "x-dispatcherStreamId"; + public static final String CLIENT_CLASS_NAME = "Client"; + public static final String CLIENT_EP = "clientEp"; + public static final String WEBSOCKET_EP = "websocketEp"; + public static final String MAP_ANY_DATA = "map"; + public static final String SPACE = " "; + public static final String EQUAL_SPACE = " = "; + public static final String PLUS_SPACE = " + "; + public static final String NOT = "!"; + public static final String CONNECTION_CLOSE = "connectionClose"; + public static final String CHECK_PATH_FOR_QUERY_PARAM = "check getPathForQueryParam(queryParam)"; + public static final String MAP_STRING = "map"; + public static final String GET_COMBINE_HEADERS = "getCombineHeaders(clientConfig.customHeaders,headerParam)"; + public static final String CLOSE = "close"; + public static final String WRITE_MESSAGE_QUEUE = "writeMessageQueue"; + public static final String START_MESSAGE_READING = "startMessageReading"; + public static final String START_MESSAGE_WRITING = "startMessageWriting"; + public static final String CONSUME = "consume"; + public static final String PRODUCE = "produce"; + public static final String DEFAULT_PIPE_TIME_OUT = "5"; + public static final String WRITE_MESSAGE = "writeMessage"; + public static final String READ_MESSAGE = "readMessage"; + public static final String MESSAGE = "Message"; + public static final String MESSAGE_WITH_ID = "MessageWithId"; + public static final String CONNECTION_CLOSED_MESSAGE = "\"ConnectionError: Connection has been closed\""; + public static final String DATABINDING_ERR_TEMPLATE = "\"DataBindingError: Error in cloning message\""; + public static final String PIPE_ERR_TEMPLATE = "\"PipeError: Error in %s message\""; + public static final String MESSAGE_VAR_NAME = "message"; + public static final String CONNECTION_ERR = "\"ConnectionError\", connectionClose"; + public static final String ATTEMPT_TO_CLOSE_CONNECTION = "attemptToCloseConnection"; + public static final String MESSAGE_WITH_ID_VAR_NAME = "messageWithId"; + public static final String TYPE_INCLUSION_GENERATOR = "Generator"; + public static final String WORKER_SLEEP_TIME_OUT = "0.01"; + public static final String STREAM_GENERATORS_MAP = "StreamGeneratorsMap"; + public static final String PIPES_MAP = "PipesMap"; + public static final String SLEEP = "sleep"; + public static final String RUNTIME = "runtime"; + public static final String PIPES = "pipes"; + public static final String STREAM_GENERATORS = "streamGenerators"; + public static final String STREAM_GENERATOR = "streamGenerator"; + public static final String STREAM_GENERATOR_CAPITAL = "StreamGenerator"; + public static final String EQUAL = "="; + public static final String CLIENT_CONFIG = "clientConfig"; + public static final String PREFIX_TEST = " test"; + public static final String ANNOT_TEST = "test:Config"; + public static final String TEST_DIR = "tests"; + public static final String STRING = "string"; + public static final String XML = "xml"; + public static final String JSON = "json"; + public static final String SERVICE_URL = "serviceUrl"; + public static final String BINARY = "binary"; + public static final String FLOAT = "float"; + public static final String HEADER_PARAM = "headerParam"; + public static final String PDF = "pdf"; + public static final String QUERY_PARAM = "queryParam"; + public static final String SELF = "self"; + public static final String MIME = "mime"; + public static final String CUSTOM_HEADERS = "customHeaders"; + public static final String MODIFIED_URL = "modifiedUrl"; + public static final String ERROR = "error"; + public static final String ENSURE_TYPE = "ensureType"; + public static final String HTTP_API_KEY = "httpApiKey"; + public static final String USER_PASSWORD = "userPassword"; + public static final String API_KEY = "apiKey"; + public static final String API_KEYS_CONFIG = "ApiKeysConfig"; + public static final String API_KEY_CONFIG = "apiKeyConfig"; + public static final String AUTH = "auth"; + public static final String PING_PONG_SERVICE = "websocket:PingPongService"; + public static final String PING_PONG_HANDLER_FIELD = "pingPongHandler"; + public static final String SECURE_SOCKET = "websocket:ClientSecureSocket"; + public static final String SECURE_SOCKET_FIELD = "secureSocket"; + public static final String PING_PONG_SERVICE_FIELD = "pingPongHandler"; + public static final String WEB_SOCKET_RETRY_CONFIG = "websocket:WebSocketRetryConfig"; + public static final String BASIC = "basic"; + public static final String BEARER = "bearer"; + public static final String REFRESH_TOKEN = "refresh_token"; + public static final String CLIENT_CRED = "client_cred"; + public static final String PASSWORD = "password"; + public static final String REMOTE_METHOD_NAME_PREFIX = "do"; + public static final String CONNECTION_CONFIG = "websocket:ClientConfiguration"; + public static final String OAUTH2 = "oauth2"; + public static final String CONFIG = "config"; + public static final String CONFIG_DESCRIPTION = "The configurations to be used when initializing the `connector`"; + public static final String RETURN = "return"; + public static final String RETURN_DESCRIPTION = "An error if connector initialization failed"; + public static final String RETRY_CONFIG_FIELD = "retryConfig"; + public static final String VALIDATION = "validation"; + public static final String DEFAULT_API_KEY_DESC = "API keys for authorization"; + public static final String ANY_DATA = "anydata"; + public static final String X_BALLERINA_INIT_DESCRIPTION = "x-ballerina-init-description"; + public static final String X_BALLERINA_MESSAGE_WRITE_DESCRIPTION = "x-ballerina-write-message-description"; + public static final String X_BALLERINA_MESSAGE_READ_DESCRIPTION = "x-ballerina-read-message-description"; + public static final String X_RESPONSE = "x-response"; + public static final String X_RESPONSE_TYPE = "x-response-type"; + public static final String DECIMAL = "decimal"; + public static final String DESCRIPTION = "description"; + public static final String TIMEOUT = "timeout"; + public static final String SERVER_STREAMING = "server-streaming"; + public static final String SIMPLE_RPC = "simple-rpc"; + public static final String INTEGER = "integer"; + public static final String BOOLEAN = "boolean"; + public static final String IS_ACTIVE = "isActive"; + public static final String OPTIONAL_ERROR = "error?"; + public static final String IMMEDIATE_CLOSE = "immediateClose"; + public static final String REMOVE_PIPES = "removePipes"; + public static final String REMOVE_STREAM_GENERATORS = "removeStreamGenerators"; + public static final String NUMBER = "number"; + public static final String OBJECT = "object"; + public static final String ARRAY = "array"; + public static final Integer MAX_ARRAY_LENGTH = 2147483637; + public static final String LINE_SEPARATOR = System.lineSeparator(); + public static final String SPECIAL_CHARACTERS_REGEX = "[^a-zA-Z0-9]"; + public static final String SLASH = "/"; + public static final String CONSTRAINT = "constraint"; + public static final String CONSTRAINT_STRING = "constraint:String"; + public static final String CONSTRAINT_NUMBER = "constraint:Number"; + public static final String CONSTRAINT_FLOAT = "constraint:Float"; + public static final String CONSTRAINT_INT = "constraint:Int"; + public static final String CONSTRAINT_ARRAY = "constraint:Array"; + public static final String OPEN_BRACE = "{"; + public static final String CLOSE_BRACE = "}"; + public static final String COLON = ":"; + public static final String IF = "if"; + public static final String CLIENT_CONFIG_CUSTOM_HEADERS = "clientConfig.customHeaders"; + public static final String S_DOT = "s."; + public static final String DOT_TO_STRING = ".toString()"; + public static final String HEADER_PARAMS = "headerParams"; + public static final String QUERY_PARAMS = "queryParams"; + public static final String PATH_PARAMS = "pathParams"; + public static final String PATH_PARAMETERS = "path parameters"; + public static final String QUERY_PARAMETERS = "query parameters"; + public static final String HEADER_PARAMETERS = "header parameters"; + public static final String FAIL_TO_READ_ENDPOINT_DETAILS = "Failed to read endpoint details of the server: "; + public static final String DISPATCHER_KEY_AND_DISPATCHER_STREAM_ID_MUST_BE_STRING = "Both dispatcherKey and " + + "dispatcherStreamId type must be string"; + public static final String DISPATCHER_KEY_AND_DISPATCHER_STREAM_ID_MUST_BE_INSIDE_REQUIRED_PROPERTY = "Both " + + "dispatcherKey and dispatcherStreamId type must be inside required property"; + public static final String SCHEMA_MUST_BE_A_RECORD = "%s schema must be a record, and it must have" + + " properties to contain dispatcherKey as a field"; + public static final String RESPONSE_TYPE_MUST_BE_A_RECORD = "Response type must be a record, " + + "invalid response type %s in %s schema, schema must contain " + + "properties field to contain dispatcherKey"; + public static final String X_NULLABLE = "x-nullable"; + public static final String INVALID_RESPONSE_SCHEMA = "Response type must be a record, invalid response schema"; + public static final String REF = "$ref"; + public static final String DOT = "."; + public static final String SEMICOLON = ";"; + public static final String IS = " is "; + public static final String RESPONSE = "response"; + public static final String WS_ERR = "wsErr"; + public static final String PIPE_ERR_CAPITAL = "PipeError"; + public static final String PIPE_ERR = "pipeErr"; + public static final String RESPONSE_MESSAGE = "responseMessage"; + public static final String WITHIN_PAREN_TEMPLATE = "(%s)"; + public static final String WITHIN_BRACE_TEMPLATE = "{%s}"; + public static final String CONSUMING = "consuming"; + public static final String PRODUCING = "producing"; + public static final ExpressionNode OP_TIMEOUT_EXPR = NodeParser.parseExpression("\"Operation has timed out\""); + public static final String LOG_PRINT_ERR = "log:printError(%s);"; + public static final String LOG_PRINT_DEBUG_TEMPLATE = "log:printDebug(\"%s: %s\", %s);"; + public static final String ERROR_PIPE_CLOSE = "Error in closing pipe."; + public static final StatementNode ATTEMPT_CON_CLOSE = createExpressionStatementNode(FUNCTION_CALL, + createFunctionCallExpressionNode(createSimpleNameReferenceNode(createIdentifierToken(SELF + DOT + + ATTEMPT_TO_CLOSE_CONNECTION)), createToken(OPEN_PAREN_TOKEN), createSeparatedNodeList(), + createToken(CLOSE_PAREN_TOKEN)), createToken(SEMICOLON_TOKEN)); + public static final String WRITE_MESSAGE_PIPE_CONSUME_ERROR = "\"PipeError: Failed to consume message from the " + + "pipe\", %s"; + public static final String WRITE_MESSAGE_CLIENT_WRITE_ERROR = "\"WsError: Failed to write message to the client\"" + + ", %s"; + public static final String READ_MESSAGE_CLIENT_READ_ERROR = "\"WsError: Failed to read message from the client\"" + + ", %s"; + public static final String READ_MESSAGE_PIPE_PRODUCE_ERROR = "\"PipeError: Failed to produce message to the pipe\"" + + ", %s"; + public static final String WSS = "wss"; + public static final String DEFAULT_URL = "ws://localhost:9090/v1"; + public static final String SERVICE_URL_DESCRIPTION = "URL of the target service"; + public static final String DOUBLE_QUOTE = "\""; + public static final String COMMA = ","; + public static final String MAX_LENGTH = "maxLength"; + public static final String MIN_LENGTH = "minLength"; + public static final String MINIMUM = "minValue"; + public static final String MAXIMUM = "maxValue"; + public static final String EXCLUSIVE_MAX = "maxValueExclusive"; + public static final String EXCLUSIVE_MIN = "minValueExclusive"; + public static final String SPECIAL_CHARACTER_REGEX = "([\\[\\]\\\\?!<>@#&~`*\\-=^+'();:\\/\\_{}\\s|.$])"; + public static final String PIPE = "|"; + public static final String READ_ONLY = "readOnly"; + public static final String PIPE_ID = "pipeId"; + public static final String CLONE_WITH_TYPE = "cloneWithType"; + public static final String PIPE_CLOSE_STATEMENT = "error? %s = self.pipes.removePipe(%s);"; + public static final String INIT = "init"; + public static final String NEXT = "next"; + public static final String QUEUE_DEFAULT_SIZE = "1000"; + public static final String BALLERINA_WEBSOCKET_DOESNT_SUPPORT_FOR_MULTIPLE_CHANNELS = + "Ballerina websocket doesn't support for multiple channels"; + public static final String X_DISPATCHER_KEY_MUST_INCLUDE_IN_THE_SPECIFICATION = "x-dispatcherKey must include" + + " in the specification"; + public static final String X_DISPATCHER_KEY_CANNOT_BE_EMPTY = "x-dispatcherKey cannot be empty"; + public static final String X_DISPATCHER_STREAM_ID_CANNOT_BE_EMPTY = "x-dispatcherStreamId cannot be empty"; + public static final String BALLERINA_CLIENT_CANNOT_BE_GENERATED = "Ballerina client cannot be " + + "generated enter correct specification and adhere to tool's rules"; + public static final String START_MESSAGE_READING_DESCRIPTION = "Used to read messages from the websocket."; + public static final String START_MESSAGE_WRITING_DESCRIPTION = "Used to write messages to the websocket."; + public static final String DEFAULT_RETURN = "null"; + public static final String STREAM_NEXT_CONSUME_MESSAGE = "anydata|error? message = self.pipes.getPipe" + + "(self.pipeId).consume(self.timeout);"; + public static final String STREAM_NEXT_RESPONSE_CLONE = "%s response = check message.cloneWithType();"; + public static final String CLOSE_STREAM_STATEMENT = "check self.pipes.removePipe(self.pipeId);"; + public static final String SELF_PIPES_GET_PIPE = "self.pipes.getPipe(%s)"; + public static final String PIPE_COLON_PIPE = "pipe:Pipe"; + public static final String MESSAGE_WITH_ID_VAR_CLONE = "MessageWithId|error messageWithId = " + + "message.cloneWithType(MessageWithId);"; + public static final String PIPE_VAR = PIPE_COLON_PIPE + SPACE + SIMPLE_PIPE; + public static final String CONNECTION_CLOSE_STATEMENT = "error? connectionClose = self->connectionClose();"; + public static final String CREATE_UUID_STATEMENT = "%s.%s = uuid:createType1AsString();"; + public static final Map TYPE_MAP; + + static { + Map typeMap = new HashMap<>(); + typeMap.put("integer", "int"); + typeMap.put("string", "string"); + typeMap.put("boolean", "boolean"); + typeMap.put("array", "[]"); + typeMap.put("object", "record {}"); + typeMap.put("decimal", "decimal"); + typeMap.put("number", "decimal"); + typeMap.put("double", "decimal"); + typeMap.put("float", "float"); + typeMap.put("binary", "byte[]"); + typeMap.put("byte", "byte[]"); + typeMap.put("{}", "json"); + TYPE_MAP = Collections.unmodifiableMap(typeMap); + } + + /** + * Enum to select the code generation mode. + * Ballerina service, mock and client generation is available + */ + public enum GenType { + GEN_SERVICE("gen_service"), + GEN_CLIENT("gen_client"), + GEN_BOTH("gen_both"); + + private final String name; + + GenType(String name) { + this.name = name; + } + + @Override + public String toString() { + return this.name; + } + } + + /** + * Enum to select the relevant ballerina http auth record. + */ + public enum AuthConfigTypes { + BASIC("websocket:CredentialsConfig"), + BEARER("websocket:BearerTokenConfig"), + CLIENT_CREDENTIAL("websocket:OAuth2ClientCredentialsGrantConfig"), + CUSTOM_CLIENT_CREDENTIAL("OAuth2ClientCredentialsGrantConfig"), + REFRESH_TOKEN("websocket:OAuth2RefreshTokenGrantConfig"), + CUSTOM_REFRESH_TOKEN("OAuth2RefreshTokenGrantConfig"), + PASSWORD("websocket:OAuth2PasswordGrantConfig"), + CUSTOM_PASSWORD("OAuth2PasswordGrantConfig"); + + private final String authType; + + AuthConfigTypes(String authType) { + this.authType = authType; + } + + public String getValue() { + return authType; + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/GeneratorUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/GeneratorUtils.java new file mode 100644 index 000000000..4fa78a681 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/GeneratorUtils.java @@ -0,0 +1,451 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.apicurio.datamodels.Library; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.ServerVariable; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.validation.ValidationProblem; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.model.GenSrcFile; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.ExpressionStatementNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.ImportOrgNameNode; +import io.ballerina.compiler.syntax.tree.Minutiae; +import io.ballerina.compiler.syntax.tree.MinutiaeList; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.SyntaxInfo; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BALLERINA; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLOSE_BRACE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.LINE_SEPARATOR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OPEN_BRACE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SLASH; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SPECIAL_CHARACTERS_REGEX; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.JSON_EXTENSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.YAML_EXTENSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.YML_EXTENSION; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createExpressionStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; + +/** + * This class util for store all the common scenarios. + * + */ +public class GeneratorUtils { + + public static final MinutiaeList SINGLE_WS_MINUTIAE = getSingleWSMinutiae(); + public static final List BAL_KEYWORDS = SyntaxInfo.keywords(); + public static final MinutiaeList SINGLE_END_OF_LINE_MINUTIAE = getEndOfLineMinutiae(); + + //Create imports; + public static ImportDeclarationNode getImportDeclarationNode(String orgName, String moduleName) { + Token importKeyword = AbstractNodeFactory.createIdentifierToken("import", SINGLE_WS_MINUTIAE, + SINGLE_WS_MINUTIAE); + Token orgNameToken = AbstractNodeFactory.createIdentifierToken(orgName); + Token slashToken = AbstractNodeFactory.createIdentifierToken("/"); + ImportOrgNameNode importOrgNameNode = NodeFactory.createImportOrgNameNode(orgNameToken, slashToken); + Token moduleNameToken = AbstractNodeFactory.createIdentifierToken(moduleName); + SeparatedNodeList moduleNodeList = AbstractNodeFactory.createSeparatedNodeList( + moduleNameToken); + Token semicolon = AbstractNodeFactory.createIdentifierToken(";"); + return NodeFactory.createImportDeclarationNode(importKeyword, importOrgNameNode, moduleNodeList, null, + semicolon); + } + + /** + * Method for convert asyncAPI type to ballerina type. + * + * @param type AsyncAPI parameter types + * @return ballerina type + */ + public static String convertAsyncAPITypeToBallerina(String type) throws BallerinaAsyncApiExceptionWs { + if (GeneratorConstants.TYPE_MAP.containsKey(type)) { + return GeneratorConstants.TYPE_MAP.get(type); + } else { + throw new BallerinaAsyncApiExceptionWs("Unsupported AsyncAPI data type `" + type + "`"); + } + } + + /** + * This method will escape special characters used in method names and identifiers. + * + * @param identifier - identifier or method name + * @return - escaped string + */ + public static String escapeIdentifier(String identifier) { + if (identifier.matches("\\b[0-9]*\\b")) { + return "'" + identifier; + } else if (!identifier.matches("\\b[_a-zA-Z][_a-zA-Z0-9]*\\b") || BAL_KEYWORDS.contains(identifier)) { + identifier = identifier.replaceAll(GeneratorConstants.ESCAPE_PATTERN, "\\\\$1"); + return "'" + identifier; + } + return identifier; + } + + /** + * Generate operationId by removing special characters. + * + * @param identifier input function name, record name or operation Id + * @return string with new generated name + */ + public static String getValidName(String identifier, boolean isSchema) { + //For the flatten enable we need to remove first Part of valid name check + // this - > !identifier.matches("\\b[a-zA-Z][a-zA-Z0-9]*\\b") && + if (!identifier.matches("\\b[0-9]*\\b")) { + String[] split = identifier.split(GeneratorConstants.ESCAPE_PATTERN); + StringBuilder validName = new StringBuilder(); + for (String part : split) { + if (!part.isBlank()) { + if (split.length > 1) { + part = part.substring(0, 1).toUpperCase(Locale.ENGLISH) + + part.substring(1).toLowerCase(Locale.ENGLISH); + } + validName.append(part); + } + } + identifier = validName.toString(); + } + if (isSchema) { + return identifier.substring(0, 1).toUpperCase(Locale.ENGLISH) + identifier.substring(1); + } else { + return escapeIdentifier(identifier.substring(0, 1).toLowerCase(Locale.ENGLISH) + + identifier.substring(1)); + } + } + + /** + * This util function is for updating the list of nodes {@link TypeDefinitionNode}. + * It updates the list while checking the duplicates. + * + * @param typeName - Given node name + * @param typeDefNode - Generated node + * @param typeDefinitionNodeList - Current node list + */ + public static void updateTypeDefNodeList(String typeName, TypeDefinitionNode typeDefNode, + List typeDefinitionNodeList) { + boolean anyMatch = typeDefinitionNodeList.stream().anyMatch(node -> + (node.typeName().text().trim().equals(typeName))); + if (!anyMatch) { + typeDefinitionNodeList.add(typeDefNode); + } + } + + /** + * Check the given recordName is valid name. + * + * @param recordName - String record name + * @return - boolean value + */ + public static boolean isValidSchemaName(String recordName) { + return !recordName.matches("\\b[0-9]*\\b"); + } + + /** + * This method will extract reference type by splitting the reference string. + * + * @param referenceVariable - Reference String + * @return Reference variable name + * @throws BallerinaAsyncApiExceptionWs - Throws an exception if the reference string is incompatible. + * Note : Current implementation will not support external links a references. + */ + public static String extractReferenceType(String referenceVariable) throws BallerinaAsyncApiExceptionWs { + if (referenceVariable.startsWith("#") && referenceVariable.contains("/")) { + String[] refArray = referenceVariable.split("/"); + return refArray[refArray.length - 1]; + } else { + throw new BallerinaAsyncApiExceptionWs("Invalid reference value : " + referenceVariable + + "\nBallerina only supports local reference values."); + } + } + + public static boolean hasTags(List tags, List filterTags) { + return !Collections.disjoint(filterTags, tags); + } + + /** + * Util for take AsyncAPI spec from given yaml file. + */ + public static AsyncApi25DocumentImpl getAsyncAPIFromAsyncAPIParser(Path definitionPath) throws + IOException, BallerinaAsyncApiExceptionWs { + + Path contractPath = java.nio.file.Paths.get(definitionPath.toString()); + if (!Files.exists(contractPath)) { + throw new BallerinaAsyncApiExceptionWs(ErrorMessages.invalidFilePath(definitionPath.toString())); + } + if (!(definitionPath.toString().endsWith(YAML_EXTENSION) || + definitionPath.toString().endsWith(JSON_EXTENSION) || + definitionPath.toString().endsWith(YML_EXTENSION))) { + throw new BallerinaAsyncApiExceptionWs(ErrorMessages.invalidFileType()); + } + // add a parser + String asyncAPIFileContent = Files.readString(definitionPath); + ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory()); + Object obj = yamlReader.readValue(asyncAPIFileContent, Object.class); + + ObjectMapper jsonWriter = new ObjectMapper(); + AsyncApi25DocumentImpl document; + try { + document = (AsyncApi25DocumentImpl) Library.readDocumentFromJSONString + (jsonWriter.writeValueAsString(obj)); + } catch (ClassCastException e) { + throw new BallerinaAsyncApiExceptionWs("AsyncAPI definition has errors. " + + "Ballerina client code can only be generate for 2.5.0 version"); + } + + List validationProblems = Library.validate(document, null); + if (!validationProblems.isEmpty()) { + StringBuilder errorMessage = new StringBuilder("AsyncAPI definition has errors: \n"); + for (ValidationProblem validationProblem : validationProblems) { + errorMessage.append(validationProblem.message).append(LINE_SEPARATOR); + } + throw new BallerinaAsyncApiExceptionWs(errorMessage.toString()); + } + return document; + } + + public static String getStreamGeneratorName(String returnType) { + if (returnType.contains("|")) { + returnType = returnType.replaceAll("\\|", ""); + } + return returnType.substring(0, 1).toUpperCase(Locale.ENGLISH) + + returnType.substring(1); + } + + /* + * Generate expressionStatementNode. + */ + public static ExpressionStatementNode getSimpleExpressionStatementNode(String expression) { + SimpleNameReferenceNode expressionNode = createSimpleNameReferenceNode( + createIdentifierToken(expression)); + return createExpressionStatementNode(null, expressionNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * If there are template values in the {@code absUrl} derive resolved url using {@code variables}. + * + * @param absUrl abstract url with template values + * @param variables variable values to populate the url template + * @return resolved url + */ + public static String buildUrl(String absUrl, Map variables) { + String url = absUrl; + if (variables != null) { + for (Map.Entry entry : variables.entrySet()) { + // According to the oas spec, default value must be specified + String replaceKey = "\\{" + entry.getKey() + '}'; + url = url.replaceAll(replaceKey, entry.getValue().getDefault()); + } + } + return url; + } + + private static MinutiaeList getSingleWSMinutiae() { + Minutiae whitespace = AbstractNodeFactory.createWhitespaceMinutiae(" "); + MinutiaeList leading = AbstractNodeFactory.createMinutiaeList(whitespace); + return leading; + } + + private static MinutiaeList getEndOfLineMinutiae() { + Minutiae endOfLineMinutiae = AbstractNodeFactory.createEndOfLineMinutiae(LINE_SEPARATOR); + MinutiaeList leading = AbstractNodeFactory.createMinutiaeList(endOfLineMinutiae); + return leading; + } + + /** + * This method for setting the file name for generated file. + * + * @param listFiles generated files + * @param gFile GenSrcFile object + * @param duplicateCount add the tag with duplicate number if file already exist + */ + public static void setGeneratedFileName(List listFiles, GenSrcFile gFile, int duplicateCount) { + for (File listFile : listFiles) { + String listFileName = listFile.getName(); + if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2) && + (listFileName.split("\\.")[0].equals(gFile.getFileName().split("\\.")[0]))) { + duplicateCount = 1 + duplicateCount; + } + } + gFile.setFileName(gFile.getFileName().split("\\.")[0] + "." + (duplicateCount) + "." + + gFile.getFileName().split("\\.")[1]); + } + + public static boolean checkImportDuplicate(List imports, String module) { + for (ImportDeclarationNode importModule : imports) { + StringBuilder moduleBuilder = new StringBuilder(); + for (IdentifierToken identifierToken : importModule.moduleName()) { + moduleBuilder.append(identifierToken.toString().trim()); + } + if (BALLERINA.equals((importModule.orgName().get()).orgName().toString().trim()) && + module.equals(moduleBuilder.toString())) { + return true; + } + } + return false; + } + + public static void addImport(List imports, String module) { + if (!checkImportDuplicate(imports, module)) { + ImportDeclarationNode importModule = GeneratorUtils.getImportDeclarationNode(BALLERINA, module); + imports.add(importModule); + } + } + + /** + * Check the given URL include complex scenarios. + * ex: /admin/api/2021-10/customers/{customer_id}.json parameterised path parameters + * TODO: address the other /{id}.json.{name}, /report.{format} + */ + public static boolean isComplexURL(String path) { + String[] subPathSegment = path.split(SLASH); + Pattern pattern = Pattern.compile(SPECIAL_CHARACTERS_REGEX); + for (String subPath : subPathSegment) { + if (subPath.contains(OPEN_BRACE) && + pattern.matcher(subPath.split(CLOSE_BRACE, 2)[1]).find()) { + return true; + } + } + return false; + } + + /** + * Add function statements for handle complex URL ex: /admin/api/2021-10/customers/{customer_id}.json. + * + *
+     *     if !customerIdDotJson.endsWith(".json") { return error("bad URL"); }
+     *     string customerId = customerIdDotJson.substring(0, customerIdDotJson.length() - 4);
+     * 
+ */ + public static List generateBodyStatementForComplexUrl(String path) { + String[] subPathSegment = path.split(SLASH); + Pattern pattern = Pattern.compile(SPECIAL_CHARACTERS_REGEX); + List bodyStatements = new ArrayList<>(); + for (String subPath : subPathSegment) { + if (subPath.contains(OPEN_BRACE) && + pattern.matcher(subPath.split(CLOSE_BRACE, 2)[1]).find()) { + String pathParam = subPath; + pathParam = pathParam.substring(pathParam.indexOf(OPEN_BRACE) + 1); + pathParam = pathParam.substring(0, pathParam.indexOf(CLOSE_BRACE)); + pathParam = getValidName(pathParam, false); + String[] subPathSplit = subPath.split(CLOSE_BRACE, 2); + String pathParameter = getValidName(subPath, false); + String restSubPath = subPathSplit[1]; + String resSubPathLength = String.valueOf(restSubPath.length() - 1); + String ifBlock = "if !" + pathParameter + ".endsWith(\"" + restSubPath + "\") { return error(\"bad " + + "URL\"); }"; + StatementNode ifBlockStatement = NodeParser.parseStatement(ifBlock); + + String pathParameterState = "string " + pathParam + " = " + pathParameter + ".substring(0, " + + pathParameter + ".length() - " + resSubPathLength + ");"; + StatementNode pathParamStatement = NodeParser.parseStatement(pathParameterState); + bodyStatements.add(ifBlockStatement); + bodyStatements.add(pathParamStatement); + } + } + return bodyStatements; + } + + /** + * This util is to check if the given schema contains any constraints. + */ + public static boolean hasConstraints(Schema schema) { + AsyncApi25SchemaImpl value = (AsyncApi25SchemaImpl) schema; + if (value.getProperties() != null) { + boolean constraintExists = value.getProperties().values().stream() + .anyMatch(GeneratorUtils::hasConstraints); + if (constraintExists) { + return true; + } + } else if ((value.getProperties() != null && + (value.getOneOf() != null || value.getAllOf() != null || value.getAnyOf() != null))) { + List allOf = value.getAllOf(); + List oneOf = value.getOneOf(); + List anyOf = value.getAnyOf(); + boolean constraintExists = false; + if (allOf != null) { + constraintExists = allOf.stream().anyMatch(GeneratorUtils::hasConstraints); + } else if (oneOf != null) { + constraintExists = oneOf.stream().anyMatch(GeneratorUtils::hasConstraints); + } else if (anyOf != null) { + constraintExists = anyOf.stream().anyMatch(GeneratorUtils::hasConstraints); + } + if (constraintExists) { + return true; + } + } else if (value.getType() != null && value.getType().equals("array")) { + if (!isConstraintExists(value)) { + return isConstraintExists((AsyncApi25SchemaImpl) value.getItems()); + } + } + return isConstraintExists(value); + } + + private static boolean isConstraintExists(AsyncApi25SchemaImpl propertyValue) { + return propertyValue.getMaximum() != null || propertyValue.getMinimum() != null || + propertyValue.getMaxLength() != null || propertyValue.getMinLength() != null || + propertyValue.getMaxItems() != null || propertyValue.getMinItems() != null || + propertyValue.getExclusiveMinimum() != null || propertyValue.getExclusiveMaximum() != null; + } + + /** + * Normalized AsyncAPI specification with adding proper naming to schema. + * + * @param asyncAPIPath - asyncAPI file path + * @return - asyncAPI specification + * @throws IOException + * @throws BallerinaAsyncApiExceptionWs + */ + public static AsyncApi25DocumentImpl normalizeAsyncAPI(Path asyncAPIPath) throws IOException, + BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = getAsyncAPIFromAsyncAPIParser(asyncAPIPath); + //TODO: have to add a asyncapi validator to here + return asyncAPI; + } + + public static String removeNonAlphanumeric(String input) { + return input.replaceAll("[^a-zA-Z0-9]", ""); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/exception/BallerinaAsyncApiExceptionWs.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/exception/BallerinaAsyncApiExceptionWs.java new file mode 100644 index 000000000..daecce4f4 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/exception/BallerinaAsyncApiExceptionWs.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.exception; + +/** + * Exception type definition for AsyncApi to Ballerina parsing related errors. + * + */ +public class BallerinaAsyncApiExceptionWs extends Exception { + public BallerinaAsyncApiExceptionWs(String message, Throwable e) { + super(message, e); + } + + public BallerinaAsyncApiExceptionWs(String message) { + super(message); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/Constants.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/Constants.java new file mode 100644 index 000000000..0ad03f082 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/Constants.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec; + +/** + * Ballerina To AsyncApi Service Constants. + * + */ +public class Constants { + public static final String ATTR_HOST = "host"; + public static final String SECURE_SOCKET = "secureSocket"; + public static final String INT = "int"; + public static final String INTEGER = "integer"; + public static final String NUMBER = "number"; + public static final String STRING = "string"; + public static final String BOOLEAN = "boolean"; + public static final String DECIMAL = "decimal"; + public static final String ARRAY = "array"; + public static final String FLOAT = "float"; + public static final String DOUBLE = "double"; + public static final String OBJECT = "object"; + public static final String TYPE_REFERENCE = "type_reference"; + public static final String WEBSOCKET = "websocket"; + public static final String DISPATCHER_KEY = "dispatcherKey"; + public static final String DISPATCHER_STREAM_ID = "dispatcherStreamId"; + public static final String BALLERINA = "ballerina"; + public static final String TYPEREFERENCE = "typeReference"; + public static final String HTTP_HEADER = "http:Header"; + public static final String BYTE_ARRAY = "byte[]"; + public static final String OCTET_STREAM = "octet-stream"; + public static final String XML = "xml"; + public static final String JSON = "json"; + public static final String PLAIN = "plain"; + public static final String ASYNC_API_SUFFIX = "_asyncapi"; + public static final String SERVER = "server"; + public static final String SERVER_TYPE = "development"; + public static final String WS = "ws"; + public static final String ASYNC_API_VERSION = "2.5.0"; + public static final String WS_PROTOCOL_VERSION = "13"; + public static final String BINDING_VERSION_VALUE = "0.1.0"; + public static final String PORT = "port"; + public static final String BINDING_VERSION = "bindingVersion"; + public static final String QUERY = "query"; + public static final String HEADERS = "headers"; + public static final String MAP_JSON = "map"; + public static final String MAP = "map"; + public static final String TUPLE = "tuple"; + public static final String SCHEMA_REFERENCE = "#/components/schemas/"; + public static final String REF = "$ref"; + public static final String ONEOF = "oneOf"; + public static final String MESSAGE_REFERENCE = "#/components/messages/"; + public static final String X_RESPONSE = "x-response"; + public static final String X_RESPONSE_TYPE = "x-response-type"; + public static final String X_REQUIRED = "x-required"; + public static final String PAYLOAD = "payload"; + public static final String SIMPLE_RPC = "simple-rpc"; + public static final String SERVER_STREAMING = "server-streaming"; + public static final String X_NULLABLE = "x-nullable"; + public static final String RETURN = "return"; + public static final String DESCRIPTION = "description"; + public static final String REMOTE_DESCRIPTION = "remoteDescription"; + public static final String SPECIAL_CHAR_REGEX = "([\\[\\]\\\\?!<>@#&~`*\\-=^+();:\\/\\_{}\\s|.$])"; + public static final String TRUE = "true"; + public static final String FALSE = "false"; + public static final String WS_LOCALHOST = "ws://localhost"; + public static final String WSS_LOCALHOST = "wss://localhost"; + public static final String WS_PREFIX = "ws://"; + public static final String WSS_PREFIX = "wss://"; + public static final String SLASH = "/"; + public static final String HYPHEN = "-"; + public static final String CONTRACT = "contract"; + public static final String VERSION = "'version"; + public static final String TITLE = "title"; + //TODO : Use this annotation after implementing this one + public static final String ASYNCAPI_ANNOTATION = "asyncapi:ServiceInfo"; + public static final String YAML_EXTENSION = ".yaml"; + public static final String JSON_EXTENSION = ".json"; + public static final String YML_EXTENSION = ".yml"; + public static final String UNDERSCORE = "_"; + public static final String CAMEL_CASE_PATTERN = "^on[A-Z][a-z0-9A-Z]*$"; + public static final String ON_MESSAGE = "onMessage"; + public static final String ON_TEXT_MESSAGE = "onTextMessage"; + public static final String ON_BINARY_MESSAGE = "onBinaryMessage"; + public static final String ON_CLOSE = "onClose"; + public static final String ON_OPEN = "onOpen"; + public static final String ON_PING = "onPing"; + public static final String ON_PONG = "onPong"; + //Exception Constants + public static final String DISPATCHERKEY_NULLABLE_EXCEPTION = "ERROR: dispatcherKey '%s' cannot be " + + "nullable in %s record"; + //dispatcherKey name + public static final String DISPATCHER_KEY_TYPE_EXCEPTION = "ERROR: dispatcherKey '%s' type must be a string " + + "in a record field"; + //dispatcherKey name + //record name + public static final String DISPATCHERKEY_OPTIONAL_EXCEPTION = "ERROR: dispatcherKey '%s' cannot be" + + " optional in %s record"; + //dispatcherKey name + //record name + public static final String DISPATCHERKEY_NOT_PRESENT_IN_RECORD_FIELD = "ERROR: dispatcherKey '%s' is not present " + + "in %s record field, those should be equal"; + //type name + //type + public static final String FUNCTION_SIGNATURE_WRONG_TYPE = "ERROR: %s type must be a record,%s given"; + public static final String FUNCTION_WRONG_NAME = "ERROR: Function name must start with 'on' and use camelCase " + + "convention ex-onHeartBeat,onRemoteFunctionTestName"; + public static final String FUNCTION_PARAMETERS_EXCEEDED = "ERROR: Function name can only have two parameters," + + " websocket:caller and type"; + public static final String FUNCTION_DEFAULT_NAME_CONTAINS_ERROR = "ERROR: onIdleTimeOut, onMessage, onTextMessage," + + " onBinaryMessage, onClose, onOpen, and onError names are not permitted in a function's name"; + public static final String NO_ANNOTATION_PRESENT = "ERROR: No Annotation present, " + + "use @websocket:ServiceConfig{dispatcherKey: \"event\"} above the service"; + public static final String NO_DISPATCHER_KEY = "ERROR: No dispatcherKey field is present in " + + "@websocket:ServiceConfig annotation"; + public static final String DISPATCHER_KEY_VALUE_CANNOT_BE_EMPTY = "ERROR: dispatcherKey cannot be empty"; + public static final String DISPATCHER_STREAM_ID_VALUE_CANNOT_BE_EMPTY = "ERROR: dispatcherStreamId cannot be empty"; + public static final String NO_TYPE_IN_STREAM = "ERROR: No type present in stream"; + public static final String NO_SERVICE_CLASS = "ERROR: No service class present"; + public static final String UNION_STREAMING_SIMPLE_RPC_ERROR = "ERROR: Response server streaming types cannot be " + + "union with simple rpc types"; + public static final String PATH_PARAM_DASH_CONTAIN_ERROR = "ERROR: Path parameter contains an invalid" + + " character '-'"; + /** + * Enum to select the Ballerina Type. + * Ballerina service, mock and client generation is available + */ + public enum AsyncAPIType { + INTEGER("integer"), + STRING("string"), + NUMBER("number"), + BOOLEAN("boolean"), + OBJECT("object"), + ARRAY("array"); + + private final String name; + + AsyncAPIType(String name) { + this.name = name; + } + + @Override + public String toString() { + return this.name; + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/AsyncApiConverterDiagnostic.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/AsyncApiConverterDiagnostic.java new file mode 100644 index 000000000..d14dbab30 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/AsyncApiConverterDiagnostic.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic; + +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.ballerina.tools.diagnostics.Location; + +import java.util.Optional; +/** + * This {@code AsyncAPIConverterDiagnostic} represents diagnostic type in the ballerina to AsyncApi command. + * + */ +public interface AsyncApiConverterDiagnostic { + + DiagnosticSeverity getDiagnosticSeverity(); + + String getMessage(); + + Optional getLocation(); + + String getCode(); +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/DiagnosticMessages.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/DiagnosticMessages.java new file mode 100644 index 000000000..00ce54f25 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/DiagnosticMessages.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic; + +import io.ballerina.tools.diagnostics.DiagnosticSeverity; + +/** + * This {@code DiagnosticMessages} enum class for containing the error message related to ballerina to AsyncApi command. + * + */ +public enum DiagnosticMessages { + + AAS_CONVERTOR_100("AAS_CONVERTOR_100", "Given Ballerina file contains compilation error(s).", + DiagnosticSeverity.ERROR), + AAS_CONVERTOR_101("AAS_CONVERTOR_101", "No Ballerina service found with name '%s' to" + + " generate an AsyncAPI specification. These are the available services: %s", DiagnosticSeverity.ERROR), + AAS_CONVERTOR_102("AAS_CONVERTOR_102", "Failed to generate AsyncAPI definition due to: %s", + DiagnosticSeverity.ERROR), + AAS_CONVERTOR_103("AAS_CONVERTOR_103", "AsyncAPI contract path can not be blank.", + DiagnosticSeverity.ERROR), + AAS_CONVERTOR_104("AAS_CONVERTOR_104", "Unsupported file type. Provide a valid contract " + + "file in .yaml or .json format.", DiagnosticSeverity.ERROR), + AAS_CONVERTOR_105("AAS_CONVERTOR_105", "Provided AsyncAPI contract contains parsing error(s).", + DiagnosticSeverity.ERROR), + AAS_CONVERTOR_106("AAS_CONVERTOR_106", "Generated AsyncAPI definition does not contain information " + + "for Ballerina type '%s'. ", DiagnosticSeverity.WARNING), + AAS_CONVERTER_107("AAS_CONVERTOR_107", "Generated AsyncAPI definition contains parsing error(s)", + DiagnosticSeverity.ERROR), + AAS_CONVERTOR_108("AAS_CONVERTOR_108", "Unexpected value: %s", DiagnosticSeverity.ERROR); + + private final String code; + private final String description; + private final DiagnosticSeverity severity; + + DiagnosticMessages(String code, String description, DiagnosticSeverity severity) { + this.code = code; + this.description = description; + this.severity = severity; + } + + public String getCode() { + return code; + } + + public String getDescription() { + return description; + } + + public DiagnosticSeverity getSeverity() { + return severity; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/ExceptionDiagnostic.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/ExceptionDiagnostic.java new file mode 100644 index 000000000..ee00b4c5f --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/ExceptionDiagnostic.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic; + +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.ballerina.tools.diagnostics.Location; + +import java.util.Optional; + +/** + * This {@code ExceptionDiagnostic} represents all the errors that happens during the code generation process. + * + */ +public class ExceptionDiagnostic implements AsyncApiConverterDiagnostic { + private final String code; + private final String message; + private final DiagnosticSeverity diagnosticSeverity; + private final Location location; + + public ExceptionDiagnostic(String code, String message, Location location, Object... args) { + this.code = code; + this.message = String.format(message, args); + this.diagnosticSeverity = DiagnosticSeverity.ERROR; + this.location = location; + } + + @Override + public String getCode() { + return code; + } + + @Override + public DiagnosticSeverity getDiagnosticSeverity() { + return diagnosticSeverity; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public Optional getLocation() { + return Optional.ofNullable(location); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/IncompatibleRemoteDiagnostic.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/IncompatibleRemoteDiagnostic.java new file mode 100644 index 000000000..32522f9fb --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/diagnostic/IncompatibleRemoteDiagnostic.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic; + +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.ballerina.tools.diagnostics.Location; + +import java.util.Optional; + +/** + * This {@code IncompatibleRemoteDiagnostic} represents the diagnostic that AsyncApiSpec not compatible with ballerina + * implementation. + * + */ +public class IncompatibleRemoteDiagnostic implements AsyncApiConverterDiagnostic { + private final String code; + private final String message; + private final Location location; + private final DiagnosticSeverity severity; + + public IncompatibleRemoteDiagnostic(DiagnosticMessages details, Location location, Object... args) { + this.code = details.getCode(); + this.message = generateDescription(details, args); + this.location = location; + this.severity = details.getSeverity(); + } + + /** + * This method is to create message description with args values. + */ + private static String generateDescription(DiagnosticMessages details, Object[] args) { + return String.format(details.getDescription(), args); + } + + @Override + public String getCode() { + return code; + } + + @Override + public DiagnosticSeverity getDiagnosticSeverity() { + return severity; + } + + @Override + public String getMessage() { + return message; + } + + public Optional getLocation() { + return Optional.ofNullable(location); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/AsyncApiInfo.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/AsyncApiInfo.java new file mode 100644 index 000000000..81191d4c1 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/AsyncApiInfo.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.model; + +import java.util.Optional; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.normalizeTitle; + +/** + * This {@code AsyncAPIInfo} contains details related to AsyncApi info section. + * + */ +public class AsyncApiInfo { + private final String title; + private final String version; + private final String contractPath; + + public AsyncApiInfo(AsyncAPIInfoBuilder asyncAPIInfoBuilder) { + this.title = asyncAPIInfoBuilder.title; + this.version = asyncAPIInfoBuilder.version; + this.contractPath = asyncAPIInfoBuilder.contractPath; + } + + public Optional getTitle() { + return Optional.ofNullable(normalizeTitle(this.title)); + } + + public Optional getVersion() { + return Optional.ofNullable(this.version); + } + + public Optional getContractPath() { + return Optional.ofNullable(this.contractPath); + } + + /** + * This is the builder class for the {@link AsyncApiInfo}. + */ + public static class AsyncAPIInfoBuilder { + private String title; + private String version; + private String contractPath; + + public AsyncAPIInfoBuilder title(String title) { + this.title = title; + return this; + } + + public AsyncAPIInfoBuilder version(String version) { + this.version = version; + return this; + } + + public AsyncAPIInfoBuilder contractPath(String contractPath) { + this.contractPath = contractPath; + return this; + } + + public AsyncApiInfo build() { + AsyncApiInfo asyncAPIInfo = new AsyncApiInfo(this); + return asyncAPIInfo; + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/AsyncApiResult.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/AsyncApiResult.java new file mode 100644 index 000000000..59668c91b --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/AsyncApiResult.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.model; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; +import io.apicurio.datamodels.Library; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25Document; +import io.apicurio.datamodels.models.util.JsonUtil; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * This {@code AsyncAPIResult} is used to contain AsyncApi definition in string format and error list. + * + */ +public class AsyncApiResult { + + private final List diagnostics; + private AsyncApi25Document asyncAPI; + private String serviceName; // added base path for key to definition + + /** + * This constructor is used to store the details that Map of {@code AsyncAPI} objects and diagnostic list. + */ + public AsyncApiResult(AsyncApi25Document asyncAPI, List diagnostics) { + this.asyncAPI = asyncAPI; + this.diagnostics = diagnostics != null ? Collections.unmodifiableList(diagnostics) : + Collections.unmodifiableList(new ArrayList<>()); + } + + public List getDiagnostics() { + return diagnostics; + } + + public Optional getAsyncAPI() { + return Optional.ofNullable(asyncAPI); + } + + public String getServiceName() { + return this.serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + // Take yaml file + public Optional getYaml() { + ObjectNode json = Library.writeDocument(this.asyncAPI); + YAMLFactory factory = new YAMLFactory(); + factory.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER); + factory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES); + factory.enable(YAMLGenerator.Feature.SPLIT_LINES); + factory.enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS); + + String finalYaml; + try { + finalYaml = new ObjectMapper(factory).writer(new DefaultPrettyPrinter()).writeValueAsString(json); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + return Optional.ofNullable(finalYaml); + } + // Take json file + public Optional getJson() { + ObjectNode json = Library.writeDocument(this.asyncAPI); + String finalJson = JsonUtil.stringify(json); + return Optional.ofNullable(finalJson); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalAsyncApi25MessageImpl.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalAsyncApi25MessageImpl.java new file mode 100644 index 000000000..7346edb59 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalAsyncApi25MessageImpl.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.model; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25MessageImpl; + +/** + * Because JsonNodes are used for bindings in the Apicurio data model, we must use Jackson ObjectMapper to + * transform a Java object to a Jackson ObjectNode. But by default true values will not be excluded when try to convert + * Java objects to Json nodes, therefore this approach has overridden the original Apicurio isEntity function + * and changed it to false,thus it will not be included in the output AsyncApi specification. + * + */ +public class BalAsyncApi25MessageImpl extends AsyncApi25MessageImpl { + @Override + public boolean isEntity() { + return false; + } + +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalAsyncApi25SchemaImpl.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalAsyncApi25SchemaImpl.java new file mode 100644 index 000000000..bb88536dc --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalAsyncApi25SchemaImpl.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.models.union.BooleanSchemaUnion; +import io.apicurio.datamodels.models.union.SchemaSchemaListUnion; + +/** + * Because JsonNodes are used for bindings in the Apicurio data model, we must use Jackson ObjectMapper to + * transform a Java object to a Jackson ObjectNode. But by default true values will not be excluded when try to convert + * Java objects to Json nodes, therefore this approach has overridden the original Apicurio isEntity function + * and changed it to false,thus it will not be included in the output AsyncApi specification. + */ +public class BalAsyncApi25SchemaImpl extends AsyncApi25SchemaImpl { + + // @JsonDeserialize is using to identify the correct class when deserializing, here it is SchemaSchemaListUnion + @JsonDeserialize(as = BalAsyncApi25SchemaImpl.class) + private SchemaSchemaListUnion items; + + @JsonDeserialize(as = BalAsyncApi25SchemaImpl.class) + private BooleanSchemaUnion additionalProperties; + + // @JsonIgnore is using to ignore the attributes when serializing + @JsonIgnore + @Override + public boolean isEntity() { + return true; + } + + @JsonIgnore + @Override + public boolean isSchema() { + return true; + } +} + + diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalBooleanSchema.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalBooleanSchema.java new file mode 100644 index 000000000..85e64146c --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/model/BalBooleanSchema.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import io.apicurio.datamodels.models.union.BooleanUnionValueImpl; + +/** + * This {@code BalBooleanSchema} contains details related to AsyncApi Boolean schema. + * In Apicurio data model ,they are using BooleanSchemaUnion but boolean: true and value: true fields need to be ignored + * therefore those defined as @JsonIgnore + */ +public class BalBooleanSchema extends BooleanUnionValueImpl { + + public BalBooleanSchema(Boolean value) { + super(value); + } + + @JsonIgnore + @Override + public boolean isBoolean() { + return true; + } + + @JsonIgnore + @Override + public Boolean getValue() { + return true; + } + +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiComponentMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiComponentMapper.java new file mode 100644 index 000000000..4b852387d --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiComponentMapper.java @@ -0,0 +1,668 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.apicurio.datamodels.models.union.BooleanUnionValueImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.DiagnosticMessages; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.IncompatibleRemoteDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalBooleanSchema; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.api.symbols.ArrayTypeSymbol; +import io.ballerina.compiler.api.symbols.ConstantSymbol; +import io.ballerina.compiler.api.symbols.Documentable; +import io.ballerina.compiler.api.symbols.Documentation; +import io.ballerina.compiler.api.symbols.EnumSymbol; +import io.ballerina.compiler.api.symbols.IntersectionTypeSymbol; +import io.ballerina.compiler.api.symbols.MapTypeSymbol; +import io.ballerina.compiler.api.symbols.ReadonlyTypeSymbol; +import io.ballerina.compiler.api.symbols.RecordFieldSymbol; +import io.ballerina.compiler.api.symbols.RecordTypeSymbol; +import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.api.symbols.SymbolKind; +import io.ballerina.compiler.api.symbols.TupleTypeSymbol; +import io.ballerina.compiler.api.symbols.TypeDefinitionSymbol; +import io.ballerina.compiler.api.symbols.TypeDescKind; +import io.ballerina.compiler.api.symbols.TypeReferenceTypeSymbol; +import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.api.symbols.UnionTypeSymbol; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.AsyncAPIType; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHERKEY_NOT_PRESENT_IN_RECORD_FIELD; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHERKEY_NULLABLE_EXCEPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHERKEY_OPTIONAL_EXCEPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_KEY_TYPE_EXCEPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DOUBLE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FALSE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FLOAT; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.INTEGER; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NUMBER; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.OBJECT; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SCHEMA_REFERENCE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.STRING; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.TRUE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.X_NULLABLE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.getAsyncApiSchema; + + +/** + * This util class for processing the mapping in between ballerina record and AsyncApi object schema. + * + */ +public class AsyncApiComponentMapper { + private final AsyncApi25ComponentsImpl components; + private final List diagnostics; + + public AsyncApiComponentMapper(AsyncApi25ComponentsImpl components) { + this.components = components; + this.diagnostics = new ArrayList<>(); + } + + public List getDiagnostics() { + return Collections.unmodifiableList(diagnostics); + } + + /** + * This function is to map ballerina type references. + * + * @param typeSymbol Type reference name as the TypeSymbol + */ + public void createComponentSchema(TypeSymbol typeSymbol, String dispatcherValue) { + String componentName = ConverterCommonUtils.unescapeIdentifier(typeSymbol.getName().orElseThrow().trim()); + //Check schema has created before, then skip recreating it + boolean isComponentContains = false; + + Map allSchemas = this.components.getSchemas(); + + if (allSchemas != null) { + isComponentContains = allSchemas.containsKey(componentName); + } + + if (allSchemas == null || !isComponentContains || dispatcherValue != null) { + Map apiDocs = getRecordFieldsAPIDocsMap((TypeReferenceTypeSymbol) typeSymbol, + componentName); + String typeDoc = null; + if (!apiDocs.isEmpty()) { + typeDoc = apiDocs.get(typeSymbol.getName().get()); + } + TypeReferenceTypeSymbol typeRef = (TypeReferenceTypeSymbol) typeSymbol; + TypeSymbol type = typeRef.typeDescriptor(); + // Handle record type request body + if (type.typeKind() == TypeDescKind.INTERSECTION) { + // Check if Read only present and then avoid it + type = excludeReadonlyIfPresent(type); + } + BalAsyncApi25SchemaImpl schema = new BalAsyncApi25SchemaImpl(); + switch (type.typeKind()) { + case RECORD: + // Handle typeInclusions with allOf type binding + handleRecordTypeSymbol((RecordTypeSymbol) type, componentName, apiDocs, dispatcherValue); + break; + case TYPE_REFERENCE: + schema.setType(OBJECT); + schema.set$ref(ConverterCommonUtils.unescapeIdentifier( + type.getName().orElseThrow().trim())); + components.addSchema(componentName, schema); + TypeReferenceTypeSymbol referredType = (TypeReferenceTypeSymbol) type; + createComponentSchema(referredType, dispatcherValue); + break; + case STRING: + schema.setType(STRING); + schema.setDescription(typeDoc); + components.addSchema(componentName, schema); + break; + case INT: + schema.setType(INTEGER); + schema.setDescription(typeDoc); + components.addSchema(componentName, schema); + break; + case DECIMAL: + schema.setType(NUMBER); + schema.setFormat(DOUBLE); + schema.setDescription(typeDoc); + components.addSchema(componentName, schema); + break; + case FLOAT: + schema.setType(NUMBER); + schema.setFormat(FLOAT); + schema.setDescription(typeDoc); + components.addSchema(componentName, schema); + break; + case ARRAY: + case TUPLE: + BalAsyncApi25SchemaImpl arraySchema = mapArrayToArraySchema(type, componentName); + arraySchema.setDescription(typeDoc); + components.addSchema(componentName, arraySchema); + break; + case UNION: + BalAsyncApi25SchemaImpl unionSchema = handleUnionType((UnionTypeSymbol) type, + new BalAsyncApi25SchemaImpl(), componentName, null, null); + unionSchema.setDescription(typeDoc); + components.addSchema(componentName, unionSchema); + break; + case MAP: + MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) type; + TypeSymbol typeParam = mapTypeSymbol.typeParam(); + if (typeParam.typeKind() == TypeDescKind.TYPE_REFERENCE) { + TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) typeParam; + BalAsyncApi25SchemaImpl objectSchema = new BalAsyncApi25SchemaImpl(); + objectSchema.setType(AsyncAPIType.OBJECT.toString()); + BalAsyncApi25SchemaImpl objectSchema2 = new BalAsyncApi25SchemaImpl(); + objectSchema2.setType(AsyncAPIType.OBJECT.toString()); + objectSchema2.set$ref(ConverterCommonUtils.unescapeIdentifier( + typeReferenceTypeSymbol.getName().orElseThrow().trim())); + objectSchema.setAdditionalProperties(objectSchema2); + components.addSchema(componentName, objectSchema); + createComponentSchema(typeReferenceTypeSymbol, dispatcherValue); + } else { + TypeDescKind typeDescKind = mapTypeSymbol.typeParam().typeKind(); + BalAsyncApi25SchemaImpl asyncApiSchema = getAsyncApiSchema(typeDescKind.getName()); + //TODO : have to check here asyncApiSchema.getType() == null ? true : asyncApiSchema + BalAsyncApi25SchemaImpl objectSchema = new BalAsyncApi25SchemaImpl(); + objectSchema.setType(AsyncAPIType.OBJECT.toString()); + objectSchema.setAdditionalProperties(asyncApiSchema.getType() == null ? + new BalBooleanSchema(true) : asyncApiSchema); + components.addSchema(componentName, objectSchema); + } + break; + default: + // Diagnostic for currently unsupported data types. + DiagnosticMessages errorMessage = DiagnosticMessages.AAS_CONVERTOR_106; + IncompatibleRemoteDiagnostic error = new IncompatibleRemoteDiagnostic(errorMessage, + typeRef.getLocation().get(), type.typeKind().getName()); + diagnostics.add(error); + break; + } + } + } + + private BalAsyncApi25SchemaImpl handleRecordTypeSymbol(RecordTypeSymbol recordTypeSymbol, String componentName, + Map apiDocs, String dispatcherValue) { + // Handle typeInclusions with allOf type binding + List typeInclusions = recordTypeSymbol.typeInclusions(); + Map recordFields = recordTypeSymbol.fieldDescriptors(); + HashSet unionKeys = new HashSet<>(recordFields.keySet()); + BalAsyncApi25SchemaImpl recordSchema = null; + if (typeInclusions.isEmpty()) { + recordSchema = generateObjectSchemaFromRecordFields(componentName, recordFields, apiDocs, dispatcherValue); + } else { + mapTypeInclusionToAllOfSchema(componentName, typeInclusions, recordFields, + unionKeys, apiDocs, dispatcherValue); + } + return recordSchema; + } + + /** + * Creating API docs related to given record fields. + */ + private Map getRecordFieldsAPIDocsMap(TypeReferenceTypeSymbol typeSymbol, String componentName) { + Map apiDocs = new LinkedHashMap<>(); + + // Record field apidoc mapping + TypeDefinitionSymbol recordTypeDefinitionSymbol = (TypeDefinitionSymbol) ((typeSymbol).definition()); + if (recordTypeDefinitionSymbol.typeDescriptor() instanceof RecordTypeSymbol) { + RecordTypeSymbol recordType = (RecordTypeSymbol) recordTypeDefinitionSymbol.typeDescriptor(); + + //Take record field parameter descriptions + if (recordTypeDefinitionSymbol.documentation().isPresent()) { + apiDocs = recordTypeDefinitionSymbol.documentation().get().parameterMap(); + } + Map recordFieldSymbols = recordType.fieldDescriptors(); + + //Take record each field descriptions (If there is a description using parameter + // description then this will be not taken) + for (Map.Entry fields : recordFieldSymbols.entrySet()) { + Optional fieldDoc = (fields.getValue()).documentation(); + if (fieldDoc.isPresent() && fieldDoc.get().description().isPresent()) { + String field = ConverterCommonUtils.unescapeIdentifier(fields.getKey()); + if (!apiDocs.containsKey(field)) { + apiDocs.put(field, fieldDoc.get().description().get()); + } + } + } + } + + // Take Record description + Symbol recordSymbol = typeSymbol.definition(); + Optional documentation = ((Documentable) recordSymbol).documentation(); + if (documentation.isPresent() && documentation.get().description().isPresent()) { + Optional description = (documentation.get().description()); + apiDocs.put(componentName, description.get().trim()); + } + return apiDocs; + } + + /** + * This function is to map the ballerina typeInclusion to AsyncApiSpec allOf composedSchema. + */ + private void mapTypeInclusionToAllOfSchema( + String componentName, List typeInclusions, Map recordFields, HashSet unionKeys, Map apiDocs, + String dispatcherValue) { + + BalAsyncApi25SchemaImpl allOfSchema = new BalAsyncApi25SchemaImpl(); + // Set schema + for (TypeSymbol typeInclusion : typeInclusions) { + BalAsyncApi25SchemaImpl referenceSchema = new BalAsyncApi25SchemaImpl(); + String typeInclusionName = typeInclusion.getName().orElseThrow(); + referenceSchema.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier(typeInclusionName)); + + allOfSchema.addAllOf(referenceSchema); + if (typeInclusion.typeKind().equals(TypeDescKind.TYPE_REFERENCE)) { + TypeReferenceTypeSymbol typeRecord = (TypeReferenceTypeSymbol) typeInclusion; + apiDocs.putAll(getRecordFieldsAPIDocsMap(typeRecord, typeInclusionName)); + if (typeRecord.typeDescriptor() instanceof RecordTypeSymbol typeInclusionRecord) { + Map tInFields = typeInclusionRecord.fieldDescriptors(); + unionKeys.addAll(tInFields.keySet()); + unionKeys.removeAll(tInFields.keySet()); + generateObjectSchemaFromRecordFields(typeInclusionName, tInFields, apiDocs, null); + + } + } + } + Map filteredField = new LinkedHashMap<>(); + recordFields.forEach((key1, value) -> unionKeys.stream().filter(key -> + ConverterCommonUtils.unescapeIdentifier(key1.trim()). + equals(ConverterCommonUtils.unescapeIdentifier(key))).forEach(key -> + filteredField.put(ConverterCommonUtils.unescapeIdentifier(key1), value))); + BalAsyncApi25SchemaImpl objectSchema = generateObjectSchemaFromRecordFields(componentName, filteredField, + apiDocs, dispatcherValue); + allOfSchema.addAllOf(objectSchema); + this.components.addSchema(componentName, allOfSchema); + } + + /** + * This function is to map ballerina record type fields to AsyncAPI objectSchema fields. + */ + public BalAsyncApi25SchemaImpl generateObjectSchemaFromRecordFields(String componentName, + Map rfields, + Map apiDocs, + String dispatcherValue) { + BalAsyncApi25SchemaImpl componentSchema = new BalAsyncApi25SchemaImpl(); + componentSchema.setType(AsyncAPIType.OBJECT.toString()); + List required = new ArrayList<>(); + boolean dispatcherValuePresent = false; + componentSchema.setDescription(apiDocs.get(componentName)); + for (Map.Entry field : rfields.entrySet()) { + String fieldName = ConverterCommonUtils.unescapeIdentifier(field.getKey().trim()); + TypeDescKind fieldTypeKind = excludeReadonlyIfPresent(field.getValue().typeDescriptor()).typeKind(); + String fieldType = fieldTypeKind.toString().toLowerCase(Locale.ENGLISH).trim(); + BalAsyncApi25SchemaImpl property = getAsyncApiSchema(fieldType); + + boolean fieldIsOptional = field.getValue().isOptional(); + + if (fieldTypeKind == TypeDescKind.TYPE_REFERENCE) { // ex:- public type Subscribe string; Cat + TypeReferenceTypeSymbol typeReference = (TypeReferenceTypeSymbol) field.getValue().typeDescriptor(); + property = handleTypeReference(typeReference, property, isSameRecord(componentName, typeReference)); + } else if (fieldTypeKind == TypeDescKind.UNION) { // ex:- Cat|Dog Schema fields inside Pet schema , string? + property = handleUnionType((UnionTypeSymbol) field.getValue().typeDescriptor(), property, componentName, + fieldName, dispatcherValue); + } else if (fieldTypeKind == TypeDescKind.MAP) { // map field inside Pet schema + MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) field.getValue().typeDescriptor(); + property = handleMapType(componentName, property, mapTypeSymbol); + } else if (fieldTypeKind == TypeDescKind.RECORD) { + property = handleRecordTypeSymbol((RecordTypeSymbol) field.getValue().typeDescriptor(), + null, new HashMap<>(), null); + } else if (fieldTypeKind == TypeDescKind.JSON) { + property.setAdditionalProperties(new BooleanUnionValueImpl(true)); + } + if (property.getType() != null) { + if (property.getType().equals(AsyncAPIType.ARRAY.toString()) && !((property).getItems() != null && + ((BalAsyncApi25SchemaImpl) (property).getItems().asSchema()).getOneOf() != null)) { + BooleanNode booleanNode = null; + if (property.getExtensions() != null) { + booleanNode = (BooleanNode) (property.getExtensions().get(X_NULLABLE)); + } + property = mapArrayToArraySchema(field.getValue().typeDescriptor(), componentName); + if (booleanNode != null) { + property.addExtension(X_NULLABLE, booleanNode); + } + } + } + // Add API documentation for record field + if (dispatcherValue != null && dispatcherValue.equals(fieldName)) { + if (fieldType.equals(STRING)) { + if (!fieldIsOptional) { + dispatcherValuePresent = true; + property.setConst(new TextNode(componentName)); + } else { + throw new NoSuchElementException(String.format(DISPATCHERKEY_OPTIONAL_EXCEPTION, + fieldName, componentName)); + } + } else { + throw new NoSuchElementException(String.format(DISPATCHER_KEY_TYPE_EXCEPTION, dispatcherValue)); + } + } + if (!fieldIsOptional) { // Check if the field is optional or not + required.add(fieldName); + } + + if (apiDocs.containsKey(fieldName)) { + property.setDescription(apiDocs.get(fieldName)); + } + componentSchema.addProperty(fieldName, property); + } + if (dispatcherValue != null && !dispatcherValuePresent) { + throw new NoSuchElementException(String.format(DISPATCHERKEY_NOT_PRESENT_IN_RECORD_FIELD, + dispatcherValue, componentName)); + } + if (!required.isEmpty()) { + componentSchema.setRequired(required); + } + if (componentName != null) { + // Set properties for the schema + this.components.addSchema(componentName, componentSchema); + } + return componentSchema; + } + + private BalAsyncApi25SchemaImpl handleMapType(String componentName, BalAsyncApi25SchemaImpl property, + MapTypeSymbol mapTypeSymbol) { + TypeDescKind typeDescKind = mapTypeSymbol.typeParam().typeKind(); + if (typeDescKind == TypeDescKind.TYPE_REFERENCE) { + TypeReferenceTypeSymbol typeReference = (TypeReferenceTypeSymbol) mapTypeSymbol.typeParam(); + BalAsyncApi25SchemaImpl reference = handleTypeReference(typeReference, new BalAsyncApi25SchemaImpl(), + isSameRecord(componentName, typeReference)); + property.setAdditionalProperties(reference); + } else if (typeDescKind == TypeDescKind.ARRAY) { + BalAsyncApi25SchemaImpl arraySchema = mapArrayToArraySchema(mapTypeSymbol.typeParam(), componentName); + property.setAdditionalProperties(arraySchema); + } else { + BalAsyncApi25SchemaImpl asyncApiSchema = getAsyncApiSchema(typeDescKind.getName()); + property.setAdditionalProperties(asyncApiSchema.getType() == null ? + new BalBooleanSchema(true) : asyncApiSchema); + } + return property; + } + + /** + * This function uses to handle the field datatype has TypeReference(ex: Record or Enum). + */ + private BalAsyncApi25SchemaImpl handleTypeReference(TypeReferenceTypeSymbol typeReferenceSymbol, + BalAsyncApi25SchemaImpl property, boolean isCyclicRecord) { + if (typeReferenceSymbol.definition().kind() == SymbolKind.ENUM) { + EnumSymbol enumSymbol = (EnumSymbol) typeReferenceSymbol.definition(); + property = mapEnumValues(enumSymbol); + } else { + property.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier( + typeReferenceSymbol.getName().orElseThrow().trim())); + if (!isCyclicRecord) { + createComponentSchema(typeReferenceSymbol, null); + } + } + return property; + } + + /** + * This function uses to generate schema when field has union type as data type. + *
+     *     type Pet record {
+     *         Dog|Cat type;
+     *     };
+     * 
+ */ + private BalAsyncApi25SchemaImpl handleUnionType(UnionTypeSymbol unionType, BalAsyncApi25SchemaImpl property, + String parentComponentName, String fieldName, + String dispatcherValue) { + List unionTypes = unionType.memberTypeDescriptors(); + List properties = new ArrayList<>(); + String nullable = FALSE; + for (TypeSymbol union : unionTypes) { + if (union.typeKind() == TypeDescKind.NIL && fieldName != null && fieldName.equals(dispatcherValue)) { + throw new NoSuchElementException(String.format(DISPATCHERKEY_NULLABLE_EXCEPTION, + fieldName, parentComponentName)); + } else if (union.typeKind() == TypeDescKind.NIL) { + nullable = TRUE; + } else if (union.typeKind() == TypeDescKind.TYPE_REFERENCE) { + property = getAsyncApiSchema(union.typeKind().getName().trim()); + TypeReferenceTypeSymbol typeReferenceTypeSymbol = (TypeReferenceTypeSymbol) union; + property = handleTypeReference(typeReferenceTypeSymbol, property, + isSameRecord(parentComponentName, typeReferenceTypeSymbol)); + properties.add(property); + // TODO: uncomment after fixing ballerina lang union type handling issue + } else if (union.typeKind() == TypeDescKind.UNION) { + property = handleUnionType((UnionTypeSymbol) union, property, parentComponentName, + null, null); + properties.add(property); + } else if (union.typeKind() == TypeDescKind.ARRAY || union.typeKind() == TypeDescKind.TUPLE) { + property = mapArrayToArraySchema(union, parentComponentName); + properties.add(property); + } else if (union.typeKind() == TypeDescKind.MAP) { + if (parentComponentName != null) { + MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) union; + TypeDescKind typeDescKind = mapTypeSymbol.typeParam().typeKind(); + BalAsyncApi25SchemaImpl asyncApiSchema = getAsyncApiSchema(typeDescKind.getName()); + BalAsyncApi25SchemaImpl objectSchema = getAsyncApiSchema(AsyncAPIType.OBJECT.toString()); + objectSchema.setAdditionalProperties( + asyncApiSchema.getType() == null ? + new BalBooleanSchema(true) : asyncApiSchema + ); + property = objectSchema; + properties.add(property); + components.addSchema(parentComponentName, property); + } + } else { + property = getAsyncApiSchema(union.typeKind().getName().trim()); + properties.add(property); + } + } + + property = generateOneOfSchema(property, properties); + if (nullable.equals(TRUE)) { + property.addExtension(X_NULLABLE, BooleanNode.TRUE); + } + return property; + } + + private boolean isSameRecord(String parentComponentName, TypeReferenceTypeSymbol typeReferenceTypeSymbol) { + if (parentComponentName == null) { + return false; + } + return typeReferenceTypeSymbol.getName().isPresent() && + parentComponentName.equals(typeReferenceTypeSymbol.getName().get().trim()); + } + + /** + * This function generate oneOf composed schema for record fields. + */ + private BalAsyncApi25SchemaImpl generateOneOfSchema(BalAsyncApi25SchemaImpl property, + List properties) { + boolean isTypeReference = properties.size() == 1; + if (!isTypeReference) { + BalAsyncApi25SchemaImpl oneOf = new BalAsyncApi25SchemaImpl(); + for (BalAsyncApi25SchemaImpl asyncApi25Schema : properties) { + oneOf.addOneOf(asyncApi25Schema); + + } + property = oneOf; + } + return property; + } + + private BalAsyncApi25SchemaImpl mapEnumValues(EnumSymbol enumSymbol) { +// Schema property; + BalAsyncApi25SchemaImpl property = new BalAsyncApi25SchemaImpl(); + property.setType(AsyncAPIType.STRING.toString()); + List enums = new ArrayList<>(); + List enumMembers = enumSymbol.members(); + for (int i = enumMembers.size() - 1; i >= 0; i--) { + ConstantSymbol enumMember = enumMembers.get(i); + if (enumMember.typeDescriptor().typeKind() == TypeDescKind.SINGLETON) { + String signatureValue = enumMember.typeDescriptor().signature(); + if (signatureValue.startsWith("\"") && signatureValue.endsWith("\"")) { + signatureValue = signatureValue.substring(1, signatureValue.length() - 1); + } + enums.add(new TextNode(signatureValue)); + } else { + enums.add(new TextNode(enumMember.constValue().toString().trim())); + } + } + property.setEnum(enums); + return property; + } + + /** + * Generate arraySchema for ballerina array type. + */ + private BalAsyncApi25SchemaImpl mapArrayToArraySchema(TypeSymbol symbol, String componentName) { + BalAsyncApi25SchemaImpl property = new BalAsyncApi25SchemaImpl(); + property.setType(AsyncAPIType.ARRAY.toString()); + int arrayDimensions = 0; + while (symbol instanceof ArrayTypeSymbol) { + arrayDimensions = arrayDimensions + 1; + ArrayTypeSymbol arrayTypeSymbol = (ArrayTypeSymbol) symbol; + symbol = arrayTypeSymbol.memberTypeDescriptor(); + } + // Handle record fields have reference record array type (ex: Tag[] tags) + BalAsyncApi25SchemaImpl symbolProperty = getAsyncApiSchema(symbol.typeKind().getName()); + // Handle record fields have union type array (ex: string[]? name) + if (symbol.typeKind() == TypeDescKind.UNION) { + symbolProperty = getSchemaForUnionType((UnionTypeSymbol) symbol, symbolProperty, componentName); + } + // Set the record model to the definition + if (symbol.typeKind().equals(TypeDescKind.TYPE_REFERENCE)) { + symbolProperty = getSchemaForTypeReferenceSymbol(symbol, symbolProperty, componentName); + } + // Handle record fields have union type array (ex: map[] name) + if (symbol.typeKind() == TypeDescKind.MAP) { + MapTypeSymbol mapTypeSymbol = (MapTypeSymbol) symbol; + symbolProperty = handleMapType(componentName, symbolProperty, mapTypeSymbol); + } + + // Handle the tuple type + if (symbol.typeKind().equals(TypeDescKind.TUPLE)) { + // Add all the schema related to typeSymbols into the list. Then the list can be mapped into oneOf + // type. + TupleTypeSymbol tuple = (TupleTypeSymbol) symbol; + BalAsyncApi25SchemaImpl composedSchema = new BalAsyncApi25SchemaImpl(); + for (TypeSymbol typeSymbol : tuple.memberTypeDescriptors()) { + BalAsyncApi25SchemaImpl asyncApiSchema = getAsyncApiSchema(typeSymbol.signature()); + if (typeSymbol instanceof TypeReferenceTypeSymbol) { + asyncApiSchema.set$ref(SCHEMA_REFERENCE + typeSymbol.signature()); + createComponentSchema(typeSymbol, null); + } + composedSchema.addOneOf(asyncApiSchema); + } + symbolProperty = composedSchema; + } + // Handle nested array type + if (arrayDimensions > 1) { + BalAsyncApi25SchemaImpl arraySchema = new BalAsyncApi25SchemaImpl(); + arraySchema.setType(AsyncAPIType.ARRAY.toString()); + property.setItems(handleArray(arrayDimensions - 1, symbolProperty, arraySchema)); + } else { + property.setItems(symbolProperty); + } + return property; + } + + /** + * This function is used to map union type of BUNION type (ex: string[]? name). + *

+ * TODO: Map for different array type unions (ex:float|int[] ids, float|int[]? ids) + * `string[]? name` here it takes union member types as array and nil,fix should do with array type and map to + * oneOf AsyncApiSpec. + */ + private BalAsyncApi25SchemaImpl getSchemaForUnionType(UnionTypeSymbol symbol, + BalAsyncApi25SchemaImpl symbolProperty, + String componentName) { + List typeSymbols = symbol.userSpecifiedMemberTypes(); + for (TypeSymbol typeSymbol : typeSymbols) { + if (typeSymbol.typeKind() == TypeDescKind.ARRAY) { + TypeSymbol arrayType = ((ArrayTypeSymbol) typeSymbol).memberTypeDescriptor(); + // Set the record model to the definition + if (arrayType.typeKind().equals(TypeDescKind.TYPE_REFERENCE)) { + symbolProperty = getSchemaForTypeReferenceSymbol(arrayType, symbolProperty, componentName); + } else { + symbolProperty = getAsyncApiSchema(arrayType.typeKind().getName()); + } + } else if (typeSymbol.typeKind() != TypeDescKind.NIL) { + symbolProperty = getAsyncApiSchema(typeSymbol.typeKind().getName()); + } + } + return symbolProperty; + } + + /** + * This util function is to handle the type reference symbol is record type or enum type. + */ + private BalAsyncApi25SchemaImpl getSchemaForTypeReferenceSymbol(TypeSymbol arrayType, + BalAsyncApi25SchemaImpl symbolProperty, + String componentName) { + if (((TypeReferenceTypeSymbol) arrayType).definition().kind() == SymbolKind.ENUM) { + TypeReferenceTypeSymbol typeRefEnum = (TypeReferenceTypeSymbol) arrayType; + EnumSymbol enumSymbol = (EnumSymbol) typeRefEnum.definition(); + symbolProperty = mapEnumValues(enumSymbol); + } else { + symbolProperty.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier( + arrayType.getName().orElseThrow().trim())); + TypeReferenceTypeSymbol typeRecord = (TypeReferenceTypeSymbol) arrayType; + if (!isSameRecord(componentName, typeRecord)) { + createComponentSchema(typeRecord, null); + } + } + return symbolProperty; + } + + /** + * Handle nested array. + */ + //TODO : Here needs to check objectMapper.valueToTree(property) because it may contatins entity:true + private BalAsyncApi25SchemaImpl handleArray(int arrayDimensions, BalAsyncApi25SchemaImpl property, + BalAsyncApi25SchemaImpl arrayProperty) { + if (arrayDimensions > 1) { + BalAsyncApi25SchemaImpl nArray = new BalAsyncApi25SchemaImpl(); + nArray.setType(AsyncAPIType.ARRAY.toString()); + arrayProperty.setItems(handleArray(arrayDimensions - 1, property, nArray)); + } else if (arrayDimensions == 1) { + arrayProperty.setItems(property); + } + return arrayProperty; + } + + public TypeSymbol excludeReadonlyIfPresent(TypeSymbol typeSymbol) { + if (!typeSymbol.typeKind().equals(TypeDescKind.INTERSECTION)) { + return typeSymbol; + } + List typeSymbols = ((IntersectionTypeSymbol) typeSymbol).memberTypeDescriptors(); + for (TypeSymbol symbol : typeSymbols) { + if (!(symbol instanceof ReadonlyTypeSymbol)) { + typeSymbol = symbol; + break; + } + } + return typeSymbol; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiEndpointMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiEndpointMapper.java new file mode 100644 index 000000000..7fc6e06af --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiEndpointMapper.java @@ -0,0 +1,304 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import io.apicurio.datamodels.models.ServerVariable; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ServerImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ServerVariable; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ServersImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.syntax.tree.CheckExpressionNode; +import io.ballerina.compiler.syntax.tree.ExplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionArgumentNode; +import io.ballerina.compiler.syntax.tree.ImplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.ListenerDeclarationNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.NamedArgumentNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.ParenthesizedArgList; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ATTR_HOST; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FALSE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.PORT; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SECURE_SOCKET; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SERVER; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SERVER_TYPE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.TRUE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WS; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WSS_LOCALHOST; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WSS_PREFIX; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WS_LOCALHOST; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WS_PREFIX; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WS_PROTOCOL_VERSION; + +/** + * Extract AsyncApi server information from and Ballerina endpoint. + */ +public class AsyncApiEndpointMapper { + public static final AsyncApiEndpointMapper ENDPOINT_MAPPER = new AsyncApiEndpointMapper(); + + /** + * Convert endpoints bound to {@code service} asyncapi server information. + * + * @param asyncAPI asyncapi definition to attach extracted information + * @param endpoints all endpoints defined in ballerina source + * @param service service node with bound endpoints + * @return AsyncApi25DocumentImpl definition with Server information + */ + public AsyncApi25DocumentImpl getServers(AsyncApi25DocumentImpl asyncAPI, List endpoints, + ServiceDeclarationNode service) { + List servers = extractServerForExpressionNode(service.expressions(), service); + if (!endpoints.isEmpty()) { + for (ListenerDeclarationNode ep : endpoints) { + SeparatedNodeList exprNodes = service.expressions(); + for (ExpressionNode node : exprNodes) { + if (node.toString().trim().equals(ep.variableName().text().trim())) { + String serviceBasePath = getServiceBasePath(service); + AsyncApi25ServerImpl server = extractServer(ep, serviceBasePath); + servers.add(server); + } + } + } + } + + if (servers.size() > 1) { + AsyncApi25ServerImpl mainServer = addEnumValues(servers); + AsyncApi25ServersImpl asyncApi25Servers = new AsyncApi25ServersImpl(); + asyncApi25Servers.addItem(SERVER_TYPE, mainServer); + asyncAPI.setServers(asyncApi25Servers); + } else { + AsyncApi25ServersImpl asyncApi25Servers = new AsyncApi25ServersImpl(); + asyncApi25Servers.addItem(SERVER_TYPE, servers.get(0)); + asyncAPI.setServers(asyncApi25Servers); + } + return asyncAPI; + } + + private AsyncApi25ServerImpl addEnumValues(List servers) { + AsyncApi25ServerImpl mainServer = servers.get(0); + List rotated = new ArrayList<>(servers); + Map mainVariable = mainServer.getVariables(); + ServerVariable hostVariable = mainVariable.get(SERVER); + ServerVariable portVariable = mainVariable.get(PORT); + if (servers.size() > 1) { + Collections.rotate(rotated, servers.size() - 1); + for (AsyncApi25ServerImpl server : rotated) { + Map variables = server.getVariables(); + + setServerVariables(hostVariable, variables, SERVER); + + setServerVariables(portVariable, variables, PORT); + } + } + return mainServer; + } + + /** + * Set server variables as Enum. + * + * @param variable server variable object + * @param variables all server variables in the asyncAPI specification + * @param variableName variable name to set + */ + private void setServerVariables(ServerVariable variable, + Map variables, + String variableName) { + if (variables.get(variableName) != null) { + List hostVariableEnum = variable.getEnum(); + if (hostVariableEnum == null) { + hostVariableEnum = new ArrayList<>(); + } + hostVariableEnum.add(variables.get(variableName).getDefault()); + variable.setEnum(hostVariableEnum); + } + } + + /** + * Extract server URL from given listener node. + */ + private AsyncApi25ServerImpl extractServer(ListenerDeclarationNode ep, String serviceBasePath) { + Optional list; + if (ep.initializer().kind() == SyntaxKind.CHECK_EXPRESSION) { + ExpressionNode expression = ((CheckExpressionNode) ep.initializer()).expression(); + list = extractListenerNodeType(expression); + } else { + list = extractListenerNodeType(ep.initializer()); + } + return generateServer(serviceBasePath, list); + } + + private Optional extractListenerNodeType(Node expression2) { + Optional list = Optional.empty(); + if (expression2.kind() == SyntaxKind.EXPLICIT_NEW_EXPRESSION) { + ExplicitNewExpressionNode bTypeExplicit = (ExplicitNewExpressionNode) expression2; + list = Optional.ofNullable(bTypeExplicit.parenthesizedArgList()); + } else if (expression2.kind() == SyntaxKind.IMPLICIT_NEW_EXPRESSION) { + ImplicitNewExpressionNode bTypeInit = (ImplicitNewExpressionNode) expression2; + list = bTypeInit.parenthesizedArgList(); + } + return list; + } + + // Function for handle both ExplicitNewExpressionNode in listener. + private List extractServerForExpressionNode(SeparatedNodeList bTypeExplicit, + ServiceDeclarationNode service) { + String serviceBasePath = getServiceBasePath(service); + Optional list; + List asyncApi25Servers = new ArrayList<>(); + for (ExpressionNode expressionNode : bTypeExplicit) { + if (expressionNode.kind().equals(SyntaxKind.EXPLICIT_NEW_EXPRESSION)) { + ExplicitNewExpressionNode explicit = (ExplicitNewExpressionNode) expressionNode; + list = Optional.ofNullable(explicit.parenthesizedArgList()); + AsyncApi25ServerImpl server = generateServer(serviceBasePath, list); + asyncApi25Servers.add(server); + } + + } + return asyncApi25Servers; + } + + //Assign host and port values + private AsyncApi25ServerImpl generateServer(String serviceBasePath, Optional list) { + + String port = null; + String host = null; + String secured = FALSE; + + AsyncApi25ServerImpl server = new AsyncApi25ServerImpl(); + + if (list.isPresent()) { + SeparatedNodeList arg = (list.get()).arguments(); + port = arg.get(0).toString().trim().replaceAll("\"", ""); + if (arg.size() > 1 && (arg.get(1) instanceof NamedArgumentNode)) { + ExpressionNode bLangRecordLiteral = ((NamedArgumentNode) arg.get(1)).expression(); + if (bLangRecordLiteral instanceof MappingConstructorExpressionNode) { + ArrayList extractedValues = extractHostAndCheckSecured( + (MappingConstructorExpressionNode) bLangRecordLiteral); + host = extractedValues.get(0); + secured = extractedValues.get(1); + } + } + } + server.setProtocol(WS); + server.setProtocolVersion(WS_PROTOCOL_VERSION); + setServerVariableValues(serviceBasePath, port, host, secured, server); + return server; + } + + /** + * Set server variables port and server. + */ + private void setServerVariableValues(String serviceBasePath, String port, String host, String secured, + AsyncApi25ServerImpl server) { + + String serverUrl; + if (host != null && port != null) { + AsyncApi25ServerVariable serverUrlVariable = server.createServerVariable(); + if (secured.equals(TRUE)) { + serverUrlVariable.setDefault(WSS_PREFIX + host); + } else { + serverUrlVariable.setDefault(WS_PREFIX + host); + + } + AsyncApi25ServerVariable portVariable = server.createServerVariable(); + portVariable.setDefault(port); + server.addVariable(SERVER, serverUrlVariable); + server.addVariable(PORT, portVariable); + serverUrl = String.format("{server}:{port}%s", serviceBasePath); + server.setUrl(serverUrl); + } else if (host != null) { + AsyncApi25ServerVariable serverUrlVariable = server.createServerVariable(); + serverUrlVariable.setDefault(host); + server.addVariable(SERVER, serverUrlVariable); + serverUrl = "{server}" + serviceBasePath; + server.setUrl(serverUrl); + } else if (port != null) { + AsyncApi25ServerVariable serverUrlVariable = server.createServerVariable(); + if (secured.equals(TRUE)) { + serverUrlVariable.setDefault(WSS_LOCALHOST); + } else { + serverUrlVariable.setDefault(WS_LOCALHOST); + } + AsyncApi25ServerVariable portVariable = server.createServerVariable(); + portVariable.setDefault(port); + server.addVariable(SERVER, serverUrlVariable); + server.addVariable(PORT, portVariable); + serverUrl = "{server}:{port}" + serviceBasePath; + server.setUrl(serverUrl); + } + } + + // Extract host value for creating URL. + private ArrayList extractHostAndCheckSecured(MappingConstructorExpressionNode bLangRecordLiteral) { + ArrayList returnValues = new ArrayList<>(); + String host = null; + String secured = FALSE; + if (bLangRecordLiteral.fields() != null && !bLangRecordLiteral.fields().isEmpty()) { + SeparatedNodeList recordFields = bLangRecordLiteral.fields(); + for (MappingFieldNode filed : recordFields) { + if (filed instanceof SpecificFieldNode) { + Node fieldNode = ((SpecificFieldNode) filed).fieldName(); + String fieldName = ConverterCommonUtils.unescapeIdentifier(fieldNode.toString().trim()); + if (fieldName.trim().equals(ATTR_HOST)) { + if (((SpecificFieldNode) filed).valueExpr().isPresent()) { + host = ((SpecificFieldNode) filed).valueExpr().get().toString().trim(); + } + } else if (fieldName.trim().equals(SECURE_SOCKET)) { + secured = TRUE; + } + } + } + } + if (host != null) { + host = host.replaceAll("\"", ""); + } + returnValues.add(host); + returnValues.add(secured); + return returnValues; + } + + + /** + * Gets the base path of a service. + * + * @param serviceDefinition The service definition node. + * @return The base path. + */ + public String getServiceBasePath(ServiceDeclarationNode serviceDefinition) { + StringBuilder currentServiceName = new StringBuilder(); + NodeList serviceNameNodes = serviceDefinition.absoluteResourcePath(); + for (Node serviceBasedPathNode : serviceNameNodes) { + currentServiceName.append(ConverterCommonUtils.unescapeIdentifier(serviceBasedPathNode.toString())); + } + return currentServiceName.toString().trim(); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiHeaderMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiHeaderMapper.java new file mode 100644 index 000000000..19e21d3eb --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiHeaderMapper.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.AsyncAPIType; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.X_NULLABLE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.unescapeIdentifier; + +/** + * This class for the mapping ballerina headers with AsyncApiSpec header parameter sections. + * + */ +public class AsyncApiHeaderMapper { + private final Map apiDocs; + + public AsyncApiHeaderMapper(Map apiDocs) { + this.apiDocs = apiDocs; + } + + /** + * Handle header parameters in ballerina data type. + * + * @param headerParam - {@link RequiredParameterNode} type header parameter node + */ + public void setHeaderParameter(RequiredParameterNode headerParam, BalAsyncApi25SchemaImpl bindingHeaderObject) { + String extractedHeaderName = extractHeaderName(headerParam); + if (extractedHeaderName != null) { + String headerName = unescapeIdentifier(extractedHeaderName); + Node node = headerParam.typeName(); + BalAsyncApi25SchemaImpl headerTypeSchema = + ConverterCommonUtils.getAsyncApiSchema(getHeaderType(headerParam)); + enableHeaderRequiredOption(node, headerTypeSchema); + if (apiDocs != null && apiDocs.containsKey(headerName)) { + headerTypeSchema.setDescription(apiDocs.get(headerName.trim())); + } + completeHeaderParameter(headerName, headerTypeSchema, + headerParam.annotations(), headerParam.typeName(), bindingHeaderObject); + } + } + + private String extractHeaderName(ParameterNode headerParam) { + if (headerParam instanceof DefaultableParameterNode) { + if (((DefaultableParameterNode) headerParam).paramName().isPresent()) { + return ((DefaultableParameterNode) headerParam).paramName().get().text(). + replaceAll("\\\\", ""); + } + } + if (((RequiredParameterNode) headerParam).paramName().isPresent()) { + return ((RequiredParameterNode) headerParam).paramName().get().text(). + replaceAll("\\\\", ""); + } + return null; + } + + /** + * Handle header parameters in ballerina data type. + * + * @param headerParam - {@link DefaultableParameterNode} type header parameter node + */ + public void setHeaderParameter(DefaultableParameterNode headerParam, BalAsyncApi25SchemaImpl bindingHeaderObject) { + String headerName = extractHeaderName(headerParam); + BalAsyncApi25SchemaImpl headerTypeSchema = ConverterCommonUtils.getAsyncApiSchema(getHeaderType(headerParam)); + String defaultValue = headerParam.expression().toString().trim(); + if (defaultValue.length() > 1 && + defaultValue.charAt(0) == '"' && + defaultValue.charAt(defaultValue.length() - 1) == '"') { + defaultValue = defaultValue.substring(1, defaultValue.length() - 1); + } + List allowedTypes = new ArrayList<>(); + allowedTypes.addAll(Arrays.asList(SyntaxKind.STRING_LITERAL, + SyntaxKind.NUMERIC_LITERAL, SyntaxKind.BOOLEAN_LITERAL)); + if (allowedTypes.contains(headerParam.expression().kind())) { + headerTypeSchema.setDefault(new TextNode(defaultValue)); + } else if (headerParam.expression().kind() == SyntaxKind.LIST_CONSTRUCTOR) { + headerTypeSchema = new BalAsyncApi25SchemaImpl(); + headerTypeSchema.setDefault(new TextNode(defaultValue)); + } + if (headerParam.typeName().kind() == SyntaxKind.OPTIONAL_TYPE_DESC) { + headerTypeSchema.addExtension(X_NULLABLE, BooleanNode.TRUE); + } + if (apiDocs != null && apiDocs.containsKey(headerName)) { + headerTypeSchema.setDescription(apiDocs.get(headerName.trim())); + } + completeHeaderParameter(headerName, headerTypeSchema, + headerParam.annotations(), headerParam.typeName(), bindingHeaderObject); + } + + /** + * Extract header type by removing its optional and array types. + */ + private String getHeaderType(ParameterNode headerParam) { + if (headerParam instanceof DefaultableParameterNode) { + return ((DefaultableParameterNode) headerParam).typeName().toString(). + replaceAll("\\?", "").replaceAll("\\[", ""). + replaceAll("\\]", "").trim(); + } + return ((RequiredParameterNode) headerParam).typeName().toString(). + replaceAll("\\?", "").replaceAll("\\[", ""). + replaceAll("\\]", "").trim(); + } + + /** + * Assign header values to AsyncApiSpec header parameter. + */ + private void completeHeaderParameter(String headerName, BalAsyncApi25SchemaImpl headerSchema, + NodeList annotations, Node node, + BalAsyncApi25SchemaImpl bindingHeaderObject) { + + if (!annotations.isEmpty()) { + AnnotationNode annotationNode = annotations.get(0); + headerName = getHeaderName(headerName, annotationNode); + } + if (node instanceof ArrayTypeDescriptorNode) { + ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) node; + BalAsyncApi25SchemaImpl arraySchema = new BalAsyncApi25SchemaImpl(); + arraySchema.setType(AsyncAPIType.ARRAY.toString()); + SyntaxKind kind = arrayNode.memberTypeDesc().kind(); + BalAsyncApi25SchemaImpl itemSchema = ConverterCommonUtils.getAsyncApiSchema(kind); + if (headerSchema.getDefault() != null) { + arraySchema.setDefault(headerSchema.getDefault()); + } + arraySchema.setItems(itemSchema); + bindingHeaderObject.addProperty(headerName, arraySchema); + } else { + bindingHeaderObject.addProperty(headerName, headerSchema); + } + } + + private void enableHeaderRequiredOption(Node node, BalAsyncApi25SchemaImpl headerSchema) { + if (node.kind() == SyntaxKind.OPTIONAL_TYPE_DESC) { + headerSchema.addExtension(X_NULLABLE, BooleanNode.TRUE); + } + } + + /** + * Extract header name from header annotation value. + * + * @param headerName - Header name + * @param annotationNode - Related annotation for extract details + * @return - Updated header name + */ + private String getHeaderName(String headerName, AnnotationNode annotationNode) { + if (annotationNode.annotValue().isPresent()) { + MappingConstructorExpressionNode fieldNode = annotationNode.annotValue().get(); + SeparatedNodeList fields = fieldNode.fields(); + for (MappingFieldNode field : fields) { + SpecificFieldNode sField = (SpecificFieldNode) field; + if (sField.fieldName().toString().trim().equals("name") && sField.valueExpr().isPresent()) { + return sField.valueExpr().get().toString().trim().replaceAll("\"", ""); + } + } + } + return headerName; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiParameterMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiParameterMapper.java new file mode 100644 index 000000000..b83fedbe3 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiParameterMapper.java @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25BindingImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ChannelBindingsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ChannelItemImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ParameterImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ParametersImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.ResourcePathParameterNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import java.util.Map; +import java.util.NoSuchElementException; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.AsyncAPIType; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.BINDING_VERSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.BINDING_VERSION_VALUE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.HEADERS; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.PATH_PARAM_DASH_CONTAIN_ERROR; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.QUERY; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SCHEMA_REFERENCE; + +/** + * AsyncApiParameterMapper provides functionality for converting ballerina parameter to AsyncApiSpec parameter model. + * + */ +public class AsyncApiParameterMapper { + private final FunctionDefinitionNode functionDefinitionNode; + private final Map apidocs; + private final AsyncApi25ComponentsImpl components; + private final SemanticModel semanticModel; + + public AsyncApiParameterMapper(FunctionDefinitionNode functionDefinitionNode, Map apidocs, + AsyncApi25ComponentsImpl components, SemanticModel semanticModel) { + + this.functionDefinitionNode = functionDefinitionNode; + this.apidocs = apidocs; + this.components = components; + this.semanticModel = semanticModel; + } + + /** + * Create {@code Parameters} model for asyncAPI operation. + */ + public void getResourceInputs(AsyncApi25ChannelItemImpl channelItem) { + //Set path parameters + NodeList pathParams = functionDefinitionNode.relativeResourcePath(); + if (!pathParams.isEmpty()) { + AsyncApi25ParametersImpl pathParameters = createPathParameters(pathParams); + if (!pathParameters.getItems().isEmpty()) { + channelItem.setParameters(pathParameters); + } + } + + // Set query parameters, headers + FunctionSignatureNode functionSignature = functionDefinitionNode.functionSignature(); + SeparatedNodeList parameterList = functionSignature.parameters(); + if (!parameterList.isEmpty()) { + channelItem.setBindings(createQueryParameters(parameterList)); + } + } + + private AsyncApi25ChannelBindingsImpl createQueryParameters(SeparatedNodeList parameterList) { + AsyncApi25ChannelBindingsImpl channelBindings = new AsyncApi25ChannelBindingsImpl(); + AsyncApi25BindingImpl asyncApi25Binding = new AsyncApi25BindingImpl(); + BalAsyncApi25SchemaImpl bindingQueryObject = new BalAsyncApi25SchemaImpl(); + BalAsyncApi25SchemaImpl bindingHeaderObject = new BalAsyncApi25SchemaImpl(); + bindingQueryObject.setType(AsyncAPIType.OBJECT.toString()); + bindingHeaderObject.setType(AsyncAPIType.OBJECT.toString()); + AsyncApiQueryParameterMapper queryParameterMapper = new AsyncApiQueryParameterMapper(apidocs, components, + semanticModel); + for (ParameterNode parameterNode : parameterList) { + if (parameterNode.kind() == SyntaxKind.REQUIRED_PARAM) { + RequiredParameterNode requiredParameterNode = (RequiredParameterNode) parameterNode; + if (requiredParameterNode.typeName().kind() != SyntaxKind.QUALIFIED_NAME_REFERENCE && + requiredParameterNode.annotations().isEmpty()) { + queryParameterMapper.createQueryParameter(requiredParameterNode, bindingQueryObject); + } + // Handle header, payload parameter + if (requiredParameterNode.typeName() instanceof TypeDescriptorNode && !requiredParameterNode + .annotations().isEmpty()) { + handleHeaderParameters(requiredParameterNode, bindingHeaderObject); + } + } else if (parameterNode.kind() == SyntaxKind.DEFAULTABLE_PARAM) { + DefaultableParameterNode defaultableParameterNode = (DefaultableParameterNode) parameterNode; + // Handle header parameter + if (defaultableParameterNode.typeName() instanceof TypeDescriptorNode && !defaultableParameterNode + .annotations().isEmpty()) { + handleDefaultableHeaderParameters(defaultableParameterNode, bindingHeaderObject); + } else { + queryParameterMapper.createQueryParameter(defaultableParameterNode, bindingQueryObject); + } + } + } + ObjectMapper objectMapper = ConverterCommonUtils.callObjectMapper(); + + TextNode bindingVersion = new TextNode(BINDING_VERSION_VALUE); + asyncApi25Binding.addItem(BINDING_VERSION, bindingVersion); + + if (bindingQueryObject.getProperties() != null) { + ObjectNode queryObj = objectMapper.valueToTree(bindingQueryObject); + asyncApi25Binding.addItem(QUERY, queryObj); + } + if (bindingHeaderObject.getProperties() != null) { + ObjectNode headerObj = objectMapper.valueToTree(bindingHeaderObject); + asyncApi25Binding.addItem(HEADERS, headerObj); + } + channelBindings.setWs(asyncApi25Binding); + return channelBindings; + + } + + /** + * Map path parameter data to AsyncApiSpec path parameter. + */ + private AsyncApi25ParametersImpl createPathParameters(NodeList pathParams) { + AsyncApi25ParametersImpl parameters = new AsyncApi25ParametersImpl(); + for (Node param : pathParams) { + if (param instanceof ResourcePathParameterNode) { + AsyncApi25ParameterImpl pathParameterAAS = new AsyncApi25ParameterImpl(); + ResourcePathParameterNode pathParam = (ResourcePathParameterNode) param; + String parameterItemName = ConverterCommonUtils.unescapeIdentifier(pathParam.paramName().get().text()); + if (parameterItemName.contains("-")) { + throw new NoSuchElementException(PATH_PARAM_DASH_CONTAIN_ERROR); + } + if (pathParam.typeDescriptor().kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) { + SimpleNameReferenceNode queryNode = (SimpleNameReferenceNode) pathParam.typeDescriptor(); + AsyncApiComponentMapper componentMapper = new AsyncApiComponentMapper(components); + TypeSymbol typeSymbol = (TypeSymbol) semanticModel.symbol(queryNode).orElseThrow(); + componentMapper.createComponentSchema(typeSymbol, null); + BalAsyncApi25SchemaImpl schema = new BalAsyncApi25SchemaImpl(); + schema.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier(queryNode.name() + .text().trim())); + pathParameterAAS.setSchema(schema); + } else { + pathParameterAAS.setSchema(ConverterCommonUtils.getAsyncApiSchema(pathParam.typeDescriptor() + .toString().trim())); + } + // Check the parameter has doc + if (!apidocs.isEmpty() && apidocs.containsKey(pathParam.paramName().get().text().trim())) { + pathParameterAAS.setDescription(apidocs.get(pathParam.paramName().get().text().trim())); + } + // Set param description + parameters.addItem(parameterItemName, pathParameterAAS); + } + } + return parameters; + } + + /** + * This function is to handle header parameters with annotation @http:Header. + */ + private void handleHeaderParameters(RequiredParameterNode requiredParameterNode, + BalAsyncApi25SchemaImpl bindingHeaderObject) { + NodeList annotations = requiredParameterNode.annotations(); + for (AnnotationNode annotation : annotations) { + if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_HEADER)) { + // Handle headers. + AsyncApiHeaderMapper asyncAPIHeaderMapper = new AsyncApiHeaderMapper(apidocs); + asyncAPIHeaderMapper.setHeaderParameter(requiredParameterNode, bindingHeaderObject); + } + } + } + + /** + * This function is to handle defaultable header parameters with annotation @http:Header. + */ + private void handleDefaultableHeaderParameters(DefaultableParameterNode defaultableParameterNode, + BalAsyncApi25SchemaImpl bindingHeaderObject) { + NodeList annotations = defaultableParameterNode.annotations(); + for (AnnotationNode annotation : annotations) { + if ((annotation.annotReference().toString()).trim().equals(Constants.HTTP_HEADER)) { + // Handle headers. + AsyncApiHeaderMapper asyncAPIHeaderMapper = new AsyncApiHeaderMapper(apidocs); + asyncAPIHeaderMapper.setHeaderParameter(defaultableParameterNode, bindingHeaderObject); + } + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiQueryParameterMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiQueryParameterMapper.java new file mode 100644 index 000000000..0fd6ccc1f --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiQueryParameterMapper.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.AsyncAPIType; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import java.util.Arrays; +import java.util.Map; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SCHEMA_REFERENCE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.X_NULLABLE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.unescapeIdentifier; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BOOLEAN_LITERAL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.LIST_CONSTRUCTOR; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.MAPPING_CONSTRUCTOR; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.NIL_LITERAL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.NUMERIC_LITERAL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPTIONAL_TYPE_DESC; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_LITERAL; + +/** + * This class processes mapping query parameters in between Ballerina and AsyncApiSpec. + * + */ +public class AsyncApiQueryParameterMapper { + private final AsyncApi25ComponentsImpl components; + private final SemanticModel semanticModel; + private final Map apidocs; + private final SyntaxKind[] validExpressionKind = {STRING_LITERAL, NUMERIC_LITERAL, BOOLEAN_LITERAL, + LIST_CONSTRUCTOR, NIL_LITERAL, MAPPING_CONSTRUCTOR}; + + public AsyncApiQueryParameterMapper(Map apidocs, AsyncApi25ComponentsImpl components, + SemanticModel semanticModel) { + this.apidocs = apidocs; + this.components = components; + this.semanticModel = semanticModel; + } + + /** + * Handle function query parameters for required parameters. + */ + public void createQueryParameter(RequiredParameterNode queryParam, BalAsyncApi25SchemaImpl bindingObject) { + String queryParamName = unescapeIdentifier(queryParam.paramName().get().text()); + if (queryParam.typeName() instanceof BuiltinSimpleNameReferenceNode) { //int offset + BalAsyncApi25SchemaImpl asyncApiQueryParamSchema = + ConverterCommonUtils.getAsyncApiSchema(queryParam.typeName().toString().trim()); + if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) { + asyncApiQueryParamSchema.setDescription(apidocs.get(queryParamName.trim())); + } + bindingObject.addProperty(queryParamName, asyncApiQueryParamSchema); + } else if (queryParam.typeName().kind() == OPTIONAL_TYPE_DESC) { //int? offset // int[]? pet + // Handle optional query parameter + BalAsyncApi25SchemaImpl asyncApiQueryParamSchema = setOptionalQueryParameter(queryParamName, + ((OptionalTypeDescriptorNode) queryParam.typeName())); + bindingObject.addProperty(queryParamName, asyncApiQueryParamSchema); + } else if (queryParam.typeName().kind() == SyntaxKind.ARRAY_TYPE_DESC) { //string[] //string?[] + // Handle required array type query parameter + ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) queryParam.typeName(); + // string[] //string?[] + BalAsyncApi25SchemaImpl asyncApiQueryParamSchema = handleArrayTypeQueryParameter(queryParamName, arrayNode); + bindingObject.addProperty(queryParamName, asyncApiQueryParamSchema); + } else if (queryParam.typeName() instanceof SimpleNameReferenceNode) { //HeartBeat + SimpleNameReferenceNode queryNode = (SimpleNameReferenceNode) queryParam.typeName(); + AsyncApiComponentMapper componentMapper = new AsyncApiComponentMapper(components); + TypeSymbol typeSymbol = (TypeSymbol) semanticModel.symbol(queryNode).orElseThrow(); + componentMapper.createComponentSchema(typeSymbol, null); + BalAsyncApi25SchemaImpl schema = new BalAsyncApi25SchemaImpl(); + schema.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier(queryNode.name().text().trim())); + if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) { + schema.setDescription(apidocs.get(queryParamName.trim())); + } + bindingObject.addProperty(queryParamName, schema); + } else { + BalAsyncApi25SchemaImpl schema = createContentTypeForMapJson(queryParamName, false); + if (!apidocs.isEmpty() && queryParam.paramName().isPresent() && apidocs.containsKey(queryParamName)) { + schema.setDescription(apidocs.get(queryParamName.trim())); + } + bindingObject.addProperty(queryParamName, schema); + } + } + + /** + * Create AsyncAPISpec query parameter for default query parameters. + */ + public void createQueryParameter(DefaultableParameterNode defaultableQueryParam, + BalAsyncApi25SchemaImpl bindingQueryObject) { + String queryParamName = defaultableQueryParam.paramName().get().text(); + BalAsyncApi25SchemaImpl asyncApiQueryParamDefaultSchema = null; + if (defaultableQueryParam.typeName() instanceof BuiltinSimpleNameReferenceNode) { + asyncApiQueryParamDefaultSchema = ConverterCommonUtils.getAsyncApiSchema( + defaultableQueryParam.typeName().toString().trim()); + if (!apidocs.isEmpty() && defaultableQueryParam.paramName().isPresent() && + apidocs.containsKey(queryParamName)) { + asyncApiQueryParamDefaultSchema.setDescription(apidocs.get(queryParamName.trim())); + } + } else if (defaultableQueryParam.typeName().kind() == OPTIONAL_TYPE_DESC) { + // Handle optional query parameter + asyncApiQueryParamDefaultSchema = setOptionalQueryParameter(queryParamName, + ((OptionalTypeDescriptorNode) defaultableQueryParam.typeName())); + } else if (defaultableQueryParam.typeName() instanceof ArrayTypeDescriptorNode) { + // Handle required array type query parameter + ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) defaultableQueryParam.typeName(); + asyncApiQueryParamDefaultSchema = handleArrayTypeQueryParameter(queryParamName, arrayNode); + } else { + asyncApiQueryParamDefaultSchema = createContentTypeForMapJson(queryParamName, false); + if (!apidocs.isEmpty() && defaultableQueryParam.paramName().isPresent() && + apidocs.containsKey(queryParamName)) { + asyncApiQueryParamDefaultSchema.setDescription(apidocs.get(queryParamName.trim())); + } + } + + if (Arrays.stream(validExpressionKind).anyMatch(syntaxKind -> syntaxKind == + defaultableQueryParam.expression().kind())) { + String defaultValue = defaultableQueryParam.expression().toString().trim(). + replaceAll("\"", ""); + if (defaultableQueryParam.expression().kind() == NIL_LITERAL) { + defaultValue = null; + } + asyncApiQueryParamDefaultSchema.setDefault(new TextNode(defaultValue)); + bindingQueryObject.addProperty(queryParamName, asyncApiQueryParamDefaultSchema); + } else { + bindingQueryObject.addProperty(queryParamName, asyncApiQueryParamDefaultSchema); + } + } + + /** + * Handle array type query parameter. + */ + private BalAsyncApi25SchemaImpl handleArrayTypeQueryParameter(String queryParamName, + ArrayTypeDescriptorNode arrayNode) { + BalAsyncApi25SchemaImpl arraySchema = new BalAsyncApi25SchemaImpl(); + arraySchema.setType(AsyncAPIType.ARRAY.toString()); + TypeDescriptorNode itemTypeNode = arrayNode.memberTypeDesc(); + BalAsyncApi25SchemaImpl itemSchema; + if (arrayNode.memberTypeDesc().kind() == OPTIONAL_TYPE_DESC) { + itemSchema = ConverterCommonUtils.getAsyncApiSchema( + ((OptionalTypeDescriptorNode) itemTypeNode).typeDescriptor().toString().trim()); + itemSchema.addExtension(X_NULLABLE, BooleanNode.TRUE); + } else { + itemSchema = ConverterCommonUtils.getAsyncApiSchema(itemTypeNode.toString().trim()); + } + arraySchema.setItems(itemSchema); + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + arraySchema.setDescription(apidocs.get(queryParamName)); + } + return arraySchema; + } + + /** + * Handle optional query parameter. + */ + private BalAsyncApi25SchemaImpl setOptionalQueryParameter(String queryParamName, + OptionalTypeDescriptorNode typeNode) { + Node node = typeNode.typeDescriptor(); + if (node.kind() == SyntaxKind.ARRAY_TYPE_DESC) { //int[]? offset + BalAsyncApi25SchemaImpl arraySchema = ConverterCommonUtils.getAsyncApiSchema(AsyncAPIType.ARRAY.toString()); + arraySchema.addExtension(X_NULLABLE, BooleanNode.TRUE); + ArrayTypeDescriptorNode arrayNode = (ArrayTypeDescriptorNode) node; + TypeDescriptorNode itemTypeNode = arrayNode.memberTypeDesc(); + BalAsyncApi25SchemaImpl itemSchema = ConverterCommonUtils.getAsyncApiSchema(itemTypeNode.toString().trim()); + arraySchema.setItems(itemSchema); + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + arraySchema.setDescription(apidocs.get(queryParamName)); + } + return arraySchema; + } else if (node.kind() == SyntaxKind.MAP_TYPE_DESC) { //map? offset={"x":{"id":"sss"}} + BalAsyncApi25SchemaImpl mapJsonSchema = createContentTypeForMapJson(queryParamName, true); + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + mapJsonSchema.setDescription(apidocs.get(queryParamName)); + } + return mapJsonSchema; + } else { //int? offset + BalAsyncApi25SchemaImpl asyncApiSchema = ConverterCommonUtils.getAsyncApiSchema(node.toString().trim()); + asyncApiSchema.addExtension(X_NULLABLE, BooleanNode.TRUE); + if (!apidocs.isEmpty() && apidocs.containsKey(queryParamName)) { + asyncApiSchema.setDescription(apidocs.get(queryParamName)); + } + return asyncApiSchema; + } + } + + private BalAsyncApi25SchemaImpl createContentTypeForMapJson(String queryParamName, boolean nullable) { + BalAsyncApi25SchemaImpl objectSchema = ConverterCommonUtils.getAsyncApiSchema(AsyncAPIType.OBJECT.toString()); + BalAsyncApi25SchemaImpl emptyObjectSchema = ConverterCommonUtils.getAsyncApiSchema(queryParamName); + if (nullable) { + objectSchema.addExtension(X_NULLABLE, BooleanNode.TRUE); + } + objectSchema.setAdditionalProperties(emptyObjectSchema); + return objectSchema; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiRemoteMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiRemoteMapper.java new file mode 100644 index 000000000..d23ebf522 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiRemoteMapper.java @@ -0,0 +1,369 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ChannelItemImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ChannelsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25OperationImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25MessageImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.Documentable; +import io.ballerina.compiler.api.symbols.Documentation; +import io.ballerina.compiler.api.symbols.FunctionSymbol; +import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.api.symbols.TypeDescKind; +import io.ballerina.compiler.api.symbols.TypeReferenceTypeSymbol; +import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.syntax.tree.ChildNodeList; +import io.ballerina.compiler.syntax.tree.ClassDefinitionNode; +import io.ballerina.compiler.syntax.tree.ExplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionBodyNode; +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.ResourcePathParameterNode; +import io.ballerina.compiler.syntax.tree.ReturnStatementNode; +import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.CAMEL_CASE_PATTERN; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FALSE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FUNCTION_DEFAULT_NAME_CONTAINS_ERROR; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FUNCTION_PARAMETERS_EXCEEDED; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FUNCTION_SIGNATURE_WRONG_TYPE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FUNCTION_WRONG_NAME; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_SERVICE_CLASS; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_BINARY_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_CLOSE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_OPEN; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_PING; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_PONG; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ON_TEXT_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.REMOTE_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.RETURN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUALIFIED_NAME_REFERENCE; + +/** + * This class will do resource mapping from ballerina to AsyncApi. + * + */ +public class AsyncApiRemoteMapper { + private final AsyncApi25ChannelsImpl channelObject = new AsyncApi25ChannelsImpl(); + private final AsyncApi25ComponentsImpl components = new AsyncApi25ComponentsImpl(); + private final AsyncApiComponentMapper componentMapper = new AsyncApiComponentMapper(components); + private final SemanticModel semanticModel; + + /** + * Initializes a resource parser for asyncApi. + */ + AsyncApiRemoteMapper(SemanticModel semanticModel) { + this.semanticModel = semanticModel; + } + + public AsyncApi25ComponentsImpl getComponents() { + return components; + } + + /** + * This method will convert ballerina resource to asyncApi Paths objects. + *

+ * // * @param resources Resource list to be converted. + * + * @return map of string and asyncApi path objects. + */ + public AsyncApi25ChannelsImpl getChannels(FunctionDefinitionNode resource, + List classDefinitionNodes, + String dispatcherValue) { + AsyncApi25ChannelItemImpl channelItem = (AsyncApi25ChannelItemImpl) channelObject.createChannelItem(); + //call asyncAPIParameterMapper to map parameters + Map apiDocs = listAPIDocumentations(resource, channelItem); + AsyncApiParameterMapper asyncAPIParameterMapper = new AsyncApiParameterMapper(resource, apiDocs, components, + semanticModel); + asyncAPIParameterMapper.getResourceInputs(channelItem); + String serviceClassName = getServiceClassName(resource); + if (!serviceClassName.isEmpty()) { + for (ClassDefinitionNode node : classDefinitionNodes) { + String testClassName1 = node.className().text(); + if (testClassName1.equals(serviceClassName)) { + return handleRemoteFunctions(resource, node, dispatcherValue, channelItem); + } + } + } else { + throw new NoSuchElementException(NO_SERVICE_CLASS); + } + return channelObject; + } + + /** + * Remote mapper when there have multiple remote methods. + * @param resource functionDefinitionNode which contains resource function + * @param classDefinitionNode + * @param dispatcherValue + * @param channelItem + * @return + */ + private AsyncApi25ChannelsImpl handleRemoteFunctions(FunctionDefinitionNode resource, + ClassDefinitionNode classDefinitionNode, + String dispatcherValue, + AsyncApi25ChannelItemImpl channelItem) { + String path = ConverterCommonUtils.unescapeIdentifier(generateRelativePath(resource)); + NodeList classMethodNodes = classDefinitionNode.members(); + AsyncApi25OperationImpl publishOperationItem = new AsyncApi25OperationImpl(); + AsyncApi25OperationImpl subscribeOperationItem = new AsyncApi25OperationImpl(); + BalAsyncApi25MessageImpl subscribeMessage = new BalAsyncApi25MessageImpl(); + BalAsyncApi25MessageImpl publishMessage = new BalAsyncApi25MessageImpl(); + AsyncApiResponseMapper responseMapper = new AsyncApiResponseMapper(resource.location(), componentMapper, + semanticModel, components); + for (Node node : classMethodNodes) { + if (node.kind().equals(SyntaxKind.OBJECT_METHOD_DEFINITION)) { + FunctionDefinitionNode remoteFunctionNode = (FunctionDefinitionNode) node; + if (remoteFunctionNode.functionSignature().parameters().size() <= 2) { + String functionName = remoteFunctionNode.functionName().toString().trim(); + if (functionName.matches(CAMEL_CASE_PATTERN)) { + if (isRemoteFunctionNameValid(functionName)) { + String remoteRequestTypeName = ConverterCommonUtils. + unescapeIdentifier(functionName.substring(2)); + RequiredParameterNode requiredParameterNode = + checkParameterContainsCustomType(remoteRequestTypeName, remoteFunctionNode); + //TODO: uncomment after handle onError is capable to have in the server side + if (requiredParameterNode != null) { + String paramName = requiredParameterNode.paramName().get().toString().trim(); + Node parameterTypeNode = requiredParameterNode.typeName(); + TypeSymbol remoteFunctionNameTypeSymbol = (TypeSymbol) semanticModel. + symbol(parameterTypeNode).orElseThrow(); + TypeReferenceTypeSymbol typeRef = + (TypeReferenceTypeSymbol) remoteFunctionNameTypeSymbol; + TypeSymbol type = typeRef.typeDescriptor(); + //check if there is a readOnly & record type also + if (type.typeKind().equals(TypeDescKind.RECORD) || + (type.typeKind().equals(TypeDescKind.INTERSECTION) && + componentMapper.excludeReadonlyIfPresent(type).typeKind(). + equals(TypeDescKind.RECORD))) { + FunctionSymbol remoteFunctionSymbol = (FunctionSymbol) semanticModel. + symbol(remoteFunctionNode).get(); + Map remoteDocs = getRemoteDocumentation(remoteFunctionSymbol); + + String paramDescription = null; + if (remoteDocs.containsKey(paramName)) { + paramDescription = remoteDocs.get(paramName); + remoteDocs.remove(paramName); + } + BalAsyncApi25MessageImpl componentMessage = responseMapper. + extractMessageSchemaReference(publishMessage, remoteRequestTypeName, + remoteFunctionNameTypeSymbol, dispatcherValue, paramDescription); + if (remoteDocs.containsKey(REMOTE_DESCRIPTION)) { + componentMessage.setDescription(remoteDocs.get(REMOTE_DESCRIPTION)); + remoteDocs.remove(REMOTE_DESCRIPTION); + } + Optional optionalRemoteReturnNode = remoteFunctionNode. + functionSignature().returnTypeDesc(); + if (optionalRemoteReturnNode.isPresent()) { + Node remoteReturnType = optionalRemoteReturnNode.get().type(); + String returnDescription = null; + if (remoteDocs.containsKey(RETURN)) { + returnDescription = remoteDocs.get(RETURN); + remoteDocs.remove(RETURN); + } + //Call createResponse method to create the response + responseMapper.createResponse(subscribeMessage, componentMessage, + remoteReturnType, returnDescription, FALSE, null); + } + //Add publish message related to remote method + components.addMessage(remoteRequestTypeName, componentMessage); + } else { + throw new NoSuchElementException(String.format(FUNCTION_SIGNATURE_WRONG_TYPE, + remoteRequestTypeName, type.typeKind().getName())); + } + } + //TODO: Change because onError and onIdleTimeout in graphql over websocket + } else { + throw new NoSuchElementException(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR); + } + } else { + throw new NoSuchElementException(FUNCTION_WRONG_NAME); + } + } else { + throw new NoSuchElementException(FUNCTION_PARAMETERS_EXCEEDED); + } + } + } + if (publishMessage.getOneOf() != null) { + if (publishMessage.getOneOf().size() == 1) { + BalAsyncApi25MessageImpl publishOneMessage = new BalAsyncApi25MessageImpl(); + publishOneMessage.set$ref(((BalAsyncApi25MessageImpl) publishMessage.getOneOf().get(0)).get$ref()); + publishOperationItem.setMessage(publishOneMessage); + } else { + publishOperationItem.setMessage(publishMessage); + } + channelItem.setPublish(publishOperationItem); + } + if (subscribeMessage.getOneOf() != null) { + if (subscribeMessage.getOneOf().size() == 1) { + BalAsyncApi25MessageImpl subscribeOneMessage = new BalAsyncApi25MessageImpl(); + subscribeOneMessage.set$ref(((BalAsyncApi25MessageImpl) subscribeMessage.getOneOf().get(0)).get$ref()); + if (subscribeOneMessage.get$ref() == null) { + subscribeOneMessage.setPayload((subscribeMessage.getOneOf().get(0)).getPayload()); + } + subscribeOperationItem.setMessage(subscribeOneMessage); + } else { + subscribeOperationItem.setMessage(subscribeMessage); + } + channelItem.setSubscribe(subscribeOperationItem); + } + channelObject.addItem(path, channelItem); + return channelObject; + } + + private Boolean isRemoteFunctionNameValid(String providedFunctionName) { + String[] invalidRemoteFunctionNames = {ON_MESSAGE, ON_TEXT_MESSAGE, ON_BINARY_MESSAGE, ON_CLOSE, ON_OPEN, + ON_PING, ON_PONG}; + return Arrays.stream(invalidRemoteFunctionNames).noneMatch(remoteFunctionName -> + remoteFunctionName.equals(providedFunctionName)); + } + + private Map getRemoteDocumentation(FunctionSymbol remoteFunctionSymbol) { + Map apiDocs = new HashMap<>(); + Optional documentation = remoteFunctionSymbol.documentation(); + if (documentation.isPresent()) { + apiDocs = documentation.get().parameterMap(); + if (documentation.get().returnDescription().isPresent()) { + apiDocs.put(RETURN, documentation.get().returnDescription().get()); + } + if (documentation.get().description().isPresent()) { + Optional description = (documentation.get().description()); + if (description.isPresent() && !description.get().trim().isEmpty()) { + apiDocs.put(REMOTE_DESCRIPTION, (description.get().trim())); + } + } + } + return apiDocs; + } + + + private RequiredParameterNode checkParameterContainsCustomType(String customTypeName, + FunctionDefinitionNode remoteFunctionNode) { + SeparatedNodeList remoteParameters = remoteFunctionNode.functionSignature().parameters(); + for (ParameterNode remoteParameterNode : remoteParameters) { + if (remoteParameterNode.kind() == SyntaxKind.REQUIRED_PARAM) { + RequiredParameterNode requiredParameterNode = (RequiredParameterNode) remoteParameterNode; + Node parameterTypeNode = requiredParameterNode.typeName(); + if (parameterTypeNode.kind() == SyntaxKind.SIMPLE_NAME_REFERENCE) { + SimpleNameReferenceNode simpleNameReferenceNode = (SimpleNameReferenceNode) parameterTypeNode; + String simpleType = simpleNameReferenceNode.name().toString().trim(); + if (simpleType.equals(customTypeName)) { + return requiredParameterNode; + } + } else if (parameterTypeNode.kind() == QUALIFIED_NAME_REFERENCE) { + QualifiedNameReferenceNode qualifiedNameReferenceNode = + (QualifiedNameReferenceNode) parameterTypeNode; + String identifier = qualifiedNameReferenceNode.identifier().text(); + if (identifier.equals(customTypeName)) { + return requiredParameterNode; + } + } + } + } + return null; + } + + private String getServiceClassName(FunctionDefinitionNode resource) { + String serviceClassName = ""; + FunctionBodyNode functionBodyNode = resource.functionBody(); + ChildNodeList childNodeList = functionBodyNode.children(); + for (Node node : childNodeList) { + if (node instanceof ReturnStatementNode) { + ReturnStatementNode returnStatementNode = (ReturnStatementNode) node; + Optional expression = returnStatementNode.expression(); + if (expression.get() instanceof ExplicitNewExpressionNode) { + ExplicitNewExpressionNode explicitNewExpressionNode = (ExplicitNewExpressionNode) expression.get(); + TypeDescriptorNode typeDescriptorNode = explicitNewExpressionNode.typeDescriptor(); + serviceClassName = typeDescriptorNode.toString().trim(); + } + } + } + return serviceClassName; + } + + /** + * Filter the API documentations from resource function node. + */ + private Map listAPIDocumentations(FunctionDefinitionNode resource, + AsyncApi25ChannelItemImpl channelItem) { + Map apiDocs = new HashMap<>(); + if (resource.metadata().isPresent()) { + Optional resourceSymbol = semanticModel.symbol(resource); + if (resourceSymbol.isPresent()) { + Symbol symbol = resourceSymbol.get(); + Optional documentation = ((Documentable) symbol).documentation(); + if (documentation.isPresent()) { + Documentation documentation1 = documentation.get(); + Optional description = documentation1.description(); + if (description.isPresent()) { + String resourceFunctionAPI = description.get().trim(); + apiDocs = documentation1.parameterMap(); + channelItem.setDescription(resourceFunctionAPI); + } + } + } + } + return apiDocs; + } + + /** + * Gets the http methods of a resource. + * + * @param resource The ballerina resource. + * @return A list of http methods. + */ + private String generateRelativePath(FunctionDefinitionNode resource) { + StringBuilder relativePath = new StringBuilder(); + relativePath.append("/"); + if (!resource.relativeResourcePath().isEmpty()) { + for (Node node : resource.relativeResourcePath()) { + if (node instanceof ResourcePathParameterNode) { + ResourcePathParameterNode pathNode = (ResourcePathParameterNode) node; + relativePath.append("{"); + relativePath.append(pathNode.paramName().get()); + relativePath.append("}"); + } else if ((resource.relativeResourcePath().size() == 1) && (node.toString().trim().equals("."))) { + return relativePath.toString().trim(); + } else { + relativePath.append(node.toString().trim()); + } + } + } + return relativePath.toString().trim(); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiResponseMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiResponseMapper.java new file mode 100644 index 000000000..8828c6285 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiResponseMapper.java @@ -0,0 +1,607 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.asyncapi.AsyncApiMessage; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.DiagnosticMessages; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.IncompatibleRemoteDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25MessageImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalBooleanSchema; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.IntersectionTypeSymbol; +import io.ballerina.compiler.api.symbols.ReadonlyTypeSymbol; +import io.ballerina.compiler.api.symbols.TypeDescKind; +import io.ballerina.compiler.api.symbols.TypeReferenceTypeSymbol; +import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.MapTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.RecordFieldNode; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.StreamTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.StreamTypeParamsNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.UnionTypeDescriptorNode; +import io.ballerina.tools.diagnostics.Location; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.AsyncAPIType; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.MESSAGE_REFERENCE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_TYPE_IN_STREAM; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ONEOF; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.PAYLOAD; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.REF; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SCHEMA_REFERENCE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SERVER_STREAMING; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SIMPLE_RPC; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.TRUE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.UNION_STREAMING_SIMPLE_RPC_ERROR; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.X_REQUIRED; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.X_RESPONSE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.X_RESPONSE_TYPE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.callObjectMapper; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.getAsyncApiSchema; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ARRAY_TYPE_DESC; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUALIFIED_NAME_REFERENCE; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RECORD_FIELD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SIMPLE_NAME_REFERENCE; + +/** + * This class processes mapping responses between Ballerina and AsyncApiSpec. + * + */ +public class AsyncApiResponseMapper { + private final Location location; + private final SemanticModel semanticModel; + private final AsyncApi25ComponentsImpl components; + private final AsyncApiComponentMapper componentMapper; + private final List errors = new ArrayList<>(); + + public AsyncApiResponseMapper(Location location, AsyncApiComponentMapper componentMapper, + SemanticModel semanticModel, AsyncApi25ComponentsImpl components) { + this.location = location; + this.semanticModel = semanticModel; + this.componentMapper = componentMapper; + this.components = components; + } + + + public void createResponse(BalAsyncApi25MessageImpl subscribeMessage, BalAsyncApi25MessageImpl componentMessage, + Node remoteReturnType, String returnDescription, String isOptional, + String responseType) { + responseType = Objects.isNull(responseType) ? SIMPLE_RPC : responseType; + String remoteReturnTypeString = ConverterCommonUtils.unescapeIdentifier(remoteReturnType.toString().trim()); + ObjectMapper objectMapper = ConverterCommonUtils.callObjectMapper(); + switch (remoteReturnType.kind()) { + case FLOAT_TYPE_DESC: + case DECIMAL_TYPE_DESC: + case INT_TYPE_DESC: + case STRING_TYPE_DESC: + case BOOLEAN_TYPE_DESC: + BalAsyncApi25SchemaImpl remoteReturnSchema = getAsyncApiSchema(remoteReturnTypeString); + setResponseOfRequest(subscribeMessage, componentMessage, responseType, returnDescription, objectMapper, + remoteReturnSchema, isOptional); + break; + case JSON_TYPE_DESC: + case XML_TYPE_DESC: + BalAsyncApi25SchemaImpl jsonSchema = getAsyncApiSchema(AsyncAPIType.OBJECT.toString()); + BalAsyncApi25SchemaImpl additionalPropertyObject = new BalAsyncApi25SchemaImpl(); + jsonSchema.setAdditionalProperties(additionalPropertyObject); + setResponseOfRequest(subscribeMessage, componentMessage, responseType, + returnDescription, objectMapper, jsonSchema, isOptional); + break; + case SIMPLE_NAME_REFERENCE: + if (remoteReturnType instanceof SimpleNameReferenceNode) { + SimpleNameReferenceNode recordNode = (SimpleNameReferenceNode) remoteReturnType; + handleReferenceResponse(subscribeMessage, componentMessage, recordNode, + returnDescription, isOptional); + } + break; + case UNION_TYPE_DESC: + if (remoteReturnType instanceof UnionTypeDescriptorNode) { + mapUnionReturns(subscribeMessage, componentMessage, + (UnionTypeDescriptorNode) remoteReturnType, returnDescription, isOptional, responseType); + } + break; + case RECORD_TYPE_DESC: + //TODO : Problem in map inline record return + if (remoteReturnType instanceof RecordTypeDescriptorNode) { + mapInlineRecordInReturn(subscribeMessage, componentMessage, + (RecordTypeDescriptorNode) remoteReturnType, returnDescription, isOptional); + } + break; + case ARRAY_TYPE_DESC: + if (remoteReturnType instanceof ArrayTypeDescriptorNode) { + getApiResponsesForArrayTypes(subscribeMessage, componentMessage, + (ArrayTypeDescriptorNode) remoteReturnType, returnDescription, isOptional); + } + break; + case OPTIONAL_TYPE_DESC: + if (remoteReturnType instanceof OptionalTypeDescriptorNode) { + createResponse(subscribeMessage, componentMessage, ((OptionalTypeDescriptorNode) remoteReturnType) + .typeDescriptor(), returnDescription, TRUE, responseType); + } + break; + case MAP_TYPE_DESC: + if (remoteReturnType instanceof MapTypeDescriptorNode) { + MapTypeDescriptorNode mapNode = (MapTypeDescriptorNode) remoteReturnType; + BalAsyncApi25SchemaImpl objectSchema = getAsyncApiSchema(AsyncAPIType.OBJECT.toString()); + //TODO : I changed this kind to string + BalAsyncApi25SchemaImpl apiSchema = getAsyncApiSchema(mapNode.mapTypeParamsNode(). + typeNode().kind()); + objectSchema.setAdditionalProperties(apiSchema.getType() == null ? + new BalBooleanSchema(Boolean.TRUE) : apiSchema); + setResponseOfRequest(subscribeMessage, componentMessage, responseType, returnDescription, + objectMapper, objectSchema, isOptional); + } + break; + case STREAM_TYPE_DESC: + if (remoteReturnType instanceof StreamTypeDescriptorNode) { + if (((StreamTypeDescriptorNode) remoteReturnType).streamTypeParamsNode().isPresent()) { + Node remoteReturnStream = ((StreamTypeParamsNode) ((StreamTypeDescriptorNode) + remoteReturnType).streamTypeParamsNode().get()).leftTypeDescNode(); + if (remoteReturnStream instanceof UnionTypeDescriptorNode) { + mapUnionReturns(subscribeMessage, componentMessage, + (UnionTypeDescriptorNode) remoteReturnStream, returnDescription, isOptional, + SERVER_STREAMING); + } else { + createResponse(subscribeMessage, componentMessage, remoteReturnStream, returnDescription, + isOptional, SERVER_STREAMING); +// BalAsyncApi25SchemaImpl remoteReturnStreamSchema = getAsyncApiSchema( +// remoteReturnStream.toString().trim()); +// setResponseOfRequest(subscribeMessage, componentMessage, SERVER_STREAMING, +// returnDescription, objectMapper, remoteReturnStreamSchema, isOptional); + } + componentMessage.addExtension(X_RESPONSE_TYPE, new TextNode(SERVER_STREAMING)); + } else { + throw new NoSuchElementException(NO_TYPE_IN_STREAM); + } + } + break; + case QUALIFIED_NAME_REFERENCE: + handleQualifiedNameTypeReference(subscribeMessage, componentMessage, + returnDescription, remoteReturnType, isOptional); + break; + default: + DiagnosticMessages errorMessage = DiagnosticMessages.AAS_CONVERTOR_108; + IncompatibleRemoteDiagnostic error = new IncompatibleRemoteDiagnostic(errorMessage, location, + remoteReturnType.kind().toString()); + errors.add(error); + break; + } + } + + private void handleQualifiedNameTypeReference(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, String returnDescription, + Node remoteReturnType, String isOptional) { + TypeSymbol qualifiedNameReferenceSymbol = (TypeSymbol) semanticModel.symbol(remoteReturnType).get(); + String remoteReturnTypeName = ConverterCommonUtils.unescapeIdentifier( + qualifiedNameReferenceSymbol.getName().get()); + + if (qualifiedNameReferenceSymbol instanceof TypeReferenceTypeSymbol) { + TypeReferenceTypeSymbol typeRef = (TypeReferenceTypeSymbol) qualifiedNameReferenceSymbol; + TypeSymbol typeSymbol = typeRef.typeDescriptor(); + if (typeSymbol.typeKind() == TypeDescKind.INTERSECTION) { + List memberTypes = ((IntersectionTypeSymbol) typeSymbol).memberTypeDescriptors(); + for (TypeSymbol memberType : memberTypes) { + if (!(memberType instanceof ReadonlyTypeSymbol)) { + typeSymbol = memberType; + break; + } + } + } + + if (remoteReturnType.parent().kind().equals(ARRAY_TYPE_DESC)) { + //create Schema + updateArraySchema(subscribeMessage, componentMessage, returnDescription, + qualifiedNameReferenceSymbol, remoteReturnTypeName, isOptional); + } else if (typeSymbol.typeKind() == TypeDescKind.RECORD) { + handleRecordTypeSymbol(subscribeMessage, componentMessage, returnDescription, + qualifiedNameReferenceSymbol, + qualifiedNameReferenceSymbol.getName().get(), isOptional); + } + } + } + + private void setResponseOfRequest(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, String responseType, + String returnDescription, ObjectMapper objMapper, BalAsyncApi25SchemaImpl + schema, String isOptional) { + //create new subscribe oneOf message + BalAsyncApi25MessageImpl subscribeOneOf = new BalAsyncApi25MessageImpl(); + + //set payload of the oneOf message(but this is not a reference) + subscribeOneOf.setPayload(objMapper.valueToTree(schema)); + + //set oneOf message into Subscribe channels + setSchemasForChannelsAsOneOfSchema(subscribeMessage, subscribeOneOf); + + //create message response with its description + ObjectNode payloadObject = ConverterCommonUtils.createObjectNode(); + payloadObject.set(PAYLOAD, objMapper.valueToTree(schema)); + + //If there exist previous x-response for same request + Map xResponses = componentMessage.getExtensions(); + if (xResponses != null && xResponses.get(X_RESPONSE) != null) { + if (xResponses.get(X_RESPONSE_TYPE).equals(new TextNode(SERVER_STREAMING)) + && responseType.equals(SIMPLE_RPC) || + (xResponses.get(X_RESPONSE_TYPE).equals(new TextNode(SIMPLE_RPC)) + && responseType.equals(SERVER_STREAMING))) { + throw new NoSuchElementException(UNION_STREAMING_SIMPLE_RPC_ERROR); + } + //Create oneOfSchema + BalAsyncApi25MessageImpl oneOfSchema = new BalAsyncApi25MessageImpl(); + if (xResponses.get(X_RESPONSE).get(PAYLOAD) != null || xResponses.get(X_RESPONSE).get(REF) != null) { + + setRefPayloadAsOneOfSchemaForPreviousOneResponse(componentMessage, oneOfSchema); + //Get newly created x-response and add it to oneOf section + setSchemaForOneOfSchema(oneOfSchema, subscribeOneOf); + //Set x-response and x-response type as extensions to request + //If there are more than two responses have + } else if (xResponses.get(X_RESPONSE).get(ONEOF) != null) { + //Take all previous oneOf responses + setRefPayloadAsOneOfSchemaForPreviousOneOfResponses(componentMessage, oneOfSchema); + setSchemaForOneOfSchema(oneOfSchema, subscribeOneOf); + } + //Set the description for oneOfSchema + setDescriptionAndXResponsesForOneOf(componentMessage, returnDescription, objMapper, + oneOfSchema, responseType, isOptional); + } else { + setDescriptionForOneResponse(returnDescription, payloadObject, componentMessage, responseType, isOptional); + } + } + + public BalAsyncApi25MessageImpl extractMessageSchemaReference(BalAsyncApi25MessageImpl message, String typeName, + TypeSymbol typeSymbol, String dispatcherValue, + String paramDescription) { + + BalAsyncApi25MessageImpl messageType = new BalAsyncApi25MessageImpl(); + + //create Schema in schema section + componentMapper.createComponentSchema(typeSymbol, dispatcherValue); + + //create SchemaReference message section + ObjectNode objNode1 = ConverterCommonUtils.createObjectNode(); + objNode1.put(REF, SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier(typeName)); + + //Set description + if (paramDescription != null) { + objNode1.put(DESCRIPTION, paramDescription); + } + + //create Message in component section + BalAsyncApi25MessageImpl componentMessage = new BalAsyncApi25MessageImpl(); + componentMessage.setPayload(objNode1); + + //create MessageReference in channel section + messageType.set$ref(MESSAGE_REFERENCE + ConverterCommonUtils.unescapeIdentifier(typeName)); + setSchemasForChannelsAsOneOfSchema(message, messageType); + return componentMessage; + } + + private void setSchemasForChannelsAsOneOfSchema(BalAsyncApi25MessageImpl oneOfSchema, + BalAsyncApi25MessageImpl schema) { + + if (oneOfSchema.getOneOf() == null) { + oneOfSchema.addOneOf(schema); + } else { + if (schema.get$ref() != null) { + boolean check = false; + for (AsyncApiMessage s : oneOfSchema.getOneOf()) { + if (((BalAsyncApi25MessageImpl) s).get$ref() != null) { + if (((BalAsyncApi25MessageImpl) s).get$ref().equals(schema.get$ref())) { + check = true; + + } + } + } + if (!check) { + oneOfSchema.addOneOf(schema); + } + } else if (schema.getPayload() != null) { + boolean check = false; + for (AsyncApiMessage s : oneOfSchema.getOneOf()) { + if (s.getPayload() != null) { + if (s.getPayload().equals(schema.getPayload())) { + check = true; + } + } + } + if (!check) { + oneOfSchema.addOneOf(schema); + } + } + } + } + + private void handleReferenceResponse(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, + SimpleNameReferenceNode referenceNode, + String returnDescription, String isOptional) { + TypeSymbol returnTypeSymbol = (TypeSymbol) semanticModel.symbol(referenceNode).orElseThrow(); + String remoteReturnTypeName = ConverterCommonUtils.unescapeIdentifier(referenceNode.name().toString().trim()); + + if (referenceNode.parent().kind().equals(ARRAY_TYPE_DESC)) { + updateArraySchema(subscribeMessage, componentMessage, returnDescription, + returnTypeSymbol, remoteReturnTypeName, isOptional); + } else if (returnTypeSymbol.typeKind() == TypeDescKind.TYPE_REFERENCE) { + handleRecordTypeSymbol(subscribeMessage, componentMessage, returnDescription, + returnTypeSymbol, remoteReturnTypeName, isOptional); + } + } + + private void updateArraySchema(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, + String returnDescription, TypeSymbol returnTypeSymbol, + String remoteReturnTypeName, String isOptional) { + //create Schema + componentMapper.createComponentSchema(returnTypeSymbol, null); + errors.addAll(componentMapper.getDiagnostics()); + + //create Message (there is no message reference) + ObjectMapper objMapper = ConverterCommonUtils.callObjectMapper(); + + //Create schema reference + BalAsyncApi25SchemaImpl itemSchema = new BalAsyncApi25SchemaImpl(); + itemSchema.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier(remoteReturnTypeName)); + BalAsyncApi25SchemaImpl arraySchema = getAsyncApiSchema(AsyncAPIType.ARRAY.toString()); + arraySchema.setItems(itemSchema); + setResponseOfRequest(subscribeMessage, componentMessage, SIMPLE_RPC, returnDescription, objMapper, + arraySchema, isOptional); + } + + private void handleRecordTypeSymbol(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, String returnDescription, + TypeSymbol returnTypeSymbol, String remoteReturnTypeName, String isOptional) { + //Creating return type message reference + BalAsyncApi25MessageImpl componentReturnMessage = extractMessageSchemaReference(subscribeMessage, + remoteReturnTypeName, returnTypeSymbol, null, null); + if (!(components.getMessages() != null && components.getMessages().get(remoteReturnTypeName) != null)) { + //add created return message + components.addMessage(remoteReturnTypeName, componentReturnMessage); + } + //set message reference as a x-response of a request + ObjectNode messageRefObject = ConverterCommonUtils.createObjectNode(); + messageRefObject.put(REF, MESSAGE_REFERENCE + + ConverterCommonUtils.unescapeIdentifier(remoteReturnTypeName)); + //If there exist previous x-response for same request then start adding them to a oneOf schema + Map xResponses = componentMessage.getExtensions(); + if (xResponses != null && xResponses.get(X_RESPONSE) != null) { + if (xResponses.get(X_RESPONSE_TYPE).equals(new TextNode(SERVER_STREAMING))) { + throw new NoSuchElementException(UNION_STREAMING_SIMPLE_RPC_ERROR); + } + ObjectMapper objMapper = ConverterCommonUtils.callObjectMapper(); + //Create oneOfSchema + BalAsyncApi25MessageImpl oneOfSchema = new BalAsyncApi25MessageImpl(); + if (xResponses.get(X_RESPONSE).get(PAYLOAD) != null || xResponses.get(X_RESPONSE).get(REF) != null) { + setRefPayloadAsOneOfSchemaForPreviousOneResponse(componentMessage, oneOfSchema); + //set newly created x-response to a schema and add it to oneOf section + BalAsyncApi25MessageImpl schemaObject; + try { + schemaObject = objMapper.treeToValue(messageRefObject, BalAsyncApi25MessageImpl.class); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + setSchemaForOneOfSchema(oneOfSchema, schemaObject); + //If there are more than two responses have + } else if (xResponses.get(X_RESPONSE).get(ONEOF) != null) { + //Take all previous oneOf responses + setRefPayloadAsOneOfSchemaForPreviousOneOfResponses(componentMessage, oneOfSchema); + //create schema reference for newly created x-response + BalAsyncApi25MessageImpl schema = new BalAsyncApi25MessageImpl(); + //Get newly created x-response and add it to oneOf section of schema object + schema.set$ref(MESSAGE_REFERENCE + ConverterCommonUtils.unescapeIdentifier(remoteReturnTypeName)); + setSchemaForOneOfSchema(oneOfSchema, schema); + } + //Set the description for oneOfSchema + setDescriptionAndXResponsesForOneOf(componentMessage, returnDescription, objMapper, + oneOfSchema, SIMPLE_RPC, isOptional); + } else { + setDescriptionForOneResponse(returnDescription, messageRefObject, componentMessage, + SIMPLE_RPC, isOptional); + } + } + + + private void setDescriptionForOneResponse(String returnDescription, ObjectNode messageRefObject, + BalAsyncApi25MessageImpl componentMessage, String responseType, + String isOptional) { + //Set the description + if (returnDescription != null) { + messageRefObject.put(DESCRIPTION, returnDescription); + } + if (isOptional.equals(TRUE)) { + messageRefObject.put(X_REQUIRED, BooleanNode.FALSE); + } + //Set x-response and x-response type of the request + componentMessage.addExtension(X_RESPONSE, messageRefObject); + componentMessage.addExtension(X_RESPONSE_TYPE, new TextNode(responseType)); + } + + private void setDescriptionAndXResponsesForOneOf(BalAsyncApi25MessageImpl componentMessage, + String returnDescription, ObjectMapper objMapper, + BalAsyncApi25MessageImpl oneOfSchema, String responseType, + String isOptional) { + //Set the description + if (returnDescription != null) { + oneOfSchema.setDescription(returnDescription); + } + if (isOptional.equals(TRUE)) { + oneOfSchema.addExtension(X_REQUIRED, BooleanNode.FALSE); + } + //Set x-response and x-response type as extensions to request + componentMessage.addExtension(X_RESPONSE, objMapper.valueToTree(oneOfSchema)); + componentMessage.addExtension(X_RESPONSE_TYPE, new TextNode(responseType)); + } + + private void setSchemaForOneOfSchema(BalAsyncApi25MessageImpl oneOfSchema, BalAsyncApi25MessageImpl schema) { + oneOfSchema.addOneOf(schema); + } + + + private void setRefPayloadAsOneOfSchemaForPreviousOneOfResponses(BalAsyncApi25MessageImpl componentMessage, + BalAsyncApi25MessageImpl oneOfSchema) { + ArrayNode oneOfNode = (ArrayNode) componentMessage.getExtensions().get(X_RESPONSE).get(ONEOF); + //Add all of them into oneOf + for (int i = 0; i < oneOfNode.size(); i++) { + BalAsyncApi25MessageImpl refSchema = new BalAsyncApi25MessageImpl(); + if (oneOfNode.get(i).get(PAYLOAD) != null) { + refSchema.setPayload(oneOfNode.get(i).get(PAYLOAD)); + } else if (oneOfNode.get(i).get(REF) != null) { + refSchema.set$ref(oneOfNode.get(i).get(REF).asText()); + } + setSchemaForOneOfSchema(oneOfSchema, refSchema); + } + } + + private void setRefPayloadAsOneOfSchemaForPreviousOneResponse(BalAsyncApi25MessageImpl componentMessage, + BalAsyncApi25MessageImpl oneOfSchema) { + if (componentMessage.getExtensions().get(X_RESPONSE).get(REF) != null) { + //Get existing only one x-response + TextNode reference = (TextNode) componentMessage.getExtensions().get(X_RESPONSE).get(REF); + //add it to oneOf section + BalAsyncApi25MessageImpl testObject = new BalAsyncApi25MessageImpl(); + testObject.set$ref(reference.textValue()); + //add schema into oneOf section + setSchemaForOneOfSchema(oneOfSchema, testObject); + } else if (componentMessage.getExtensions().get(X_RESPONSE).get(PAYLOAD) != null) { + ObjectNode reference = (ObjectNode) componentMessage.getExtensions().get(X_RESPONSE).get(PAYLOAD); + //add it to oneOf section + BalAsyncApi25MessageImpl testObject = new BalAsyncApi25MessageImpl(); + testObject.setPayload(reference); + //add schema into oneOf section + setSchemaForOneOfSchema(oneOfSchema, testObject); + } + } + + + /** + * Handle the response has union type. + * + *

+     *     resource function post reservation(@http:Payload Reservation reservation)
+     *                 returns ReservationCreated|ReservationConflict {
+     *         ReservationCreated created = createReservation(reservation);
+     *         return created;
+     *     }
+     * 
+ */ + private void mapUnionReturns(BalAsyncApi25MessageImpl subscribeMessage, BalAsyncApi25MessageImpl componentMessage, + UnionTypeDescriptorNode typeNode, String returnDescription, String isOptional, + String responseType) { + TypeDescriptorNode rightNode = typeNode.rightTypeDesc(); + TypeDescriptorNode leftNode = typeNode.leftTypeDesc(); + // Handle leftNode because it is main node + createResponse(subscribeMessage, componentMessage, leftNode, returnDescription, isOptional, responseType); + // Handle rest of the union type + if (rightNode instanceof UnionTypeDescriptorNode) { + UnionTypeDescriptorNode traversRightNode = (UnionTypeDescriptorNode) rightNode; + while (traversRightNode.rightTypeDesc() != null) { + if (leftNode.kind() == QUALIFIED_NAME_REFERENCE) { + leftNode = ((UnionTypeDescriptorNode) rightNode).leftTypeDesc(); + createResponse(subscribeMessage, componentMessage, leftNode, returnDescription, isOptional, + responseType); + } + } + } else { + createResponse(subscribeMessage, componentMessage, rightNode, returnDescription, isOptional, responseType); + } + } + + + /** + * Handle response has inline record as return type. + */ + private void mapInlineRecordInReturn(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, RecordTypeDescriptorNode typeNode, + String returnDescription, String isOptional) { + + NodeList fields = typeNode.fields(); + BalAsyncApi25SchemaImpl inlineSchema = new BalAsyncApi25SchemaImpl(); + inlineSchema.setType(AsyncAPIType.OBJECT.toString()); + // 1- scenarios returns record {| int id; string body;|} - done + // 2- scenarios returns record {| int id; Person body;|} - done + for (Node field : fields) { + //TODO : Have to implement type inclusion part uncomment below code if after editing it + if (field.kind() == RECORD_FIELD) { + RecordFieldNode recordField = (RecordFieldNode) field; + Node type01 = recordField.typeName(); + if (recordField.typeName().kind() == SIMPLE_NAME_REFERENCE) { + SimpleNameReferenceNode nameRefNode = (SimpleNameReferenceNode) type01; + TypeSymbol typeSymbol = (TypeSymbol) semanticModel.symbol(nameRefNode).orElseThrow(); + componentMapper.createComponentSchema(typeSymbol, null); + BalAsyncApi25SchemaImpl referenceSchema = new BalAsyncApi25SchemaImpl(); + referenceSchema.set$ref(SCHEMA_REFERENCE + ConverterCommonUtils.unescapeIdentifier( + recordField.typeName().toString().trim())); + inlineSchema.addProperty(recordField.fieldName().text(), referenceSchema); + } else { + //TODO array fields handling + BalAsyncApi25SchemaImpl propertySchema = ConverterCommonUtils.getAsyncApiSchema( + recordField.typeName().toString().trim()); + inlineSchema.addProperty(recordField.fieldName().text(), propertySchema); + } + } + } + setResponseOfRequest(subscribeMessage, componentMessage, SIMPLE_RPC, + returnDescription, callObjectMapper(), inlineSchema, isOptional); + } + + /** + * Handle return has array types. + */ + private void getApiResponsesForArrayTypes(BalAsyncApi25MessageImpl subscribeMessage, + BalAsyncApi25MessageImpl componentMessage, ArrayTypeDescriptorNode array, + String returnDescription, String isOptional) { + if (array.memberTypeDesc().kind() == SIMPLE_NAME_REFERENCE) { + handleReferenceResponse(subscribeMessage, componentMessage, + (SimpleNameReferenceNode) array.memberTypeDesc(), returnDescription, isOptional); + } else if (array.memberTypeDesc().kind() == QUALIFIED_NAME_REFERENCE) { + handleQualifiedNameTypeReference(subscribeMessage, componentMessage, returnDescription, + array.memberTypeDesc(), isOptional); + } else { + BalAsyncApi25SchemaImpl arraySchema = getAsyncApiSchema(AsyncAPIType.ARRAY.toString()); + String type02 = array.memberTypeDesc().kind().toString().trim().split("_")[0].toLowerCase(Locale.ENGLISH); + BalAsyncApi25SchemaImpl asyncApiSchema = getAsyncApiSchema(type02); + ObjectMapper objectMapper = ConverterCommonUtils.callObjectMapper(); + arraySchema.setItems(asyncApiSchema); + setResponseOfRequest(subscribeMessage, componentMessage, SIMPLE_RPC, returnDescription, objectMapper, + arraySchema, isOptional); + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiServiceMapper.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiServiceMapper.java new file mode 100644 index 000000000..4b24d84a4 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/service/AsyncApiServiceMapper.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.service; + +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ChannelsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ClassDefinitionNode; +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; + +import java.util.List; +import java.util.NoSuchElementException; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_KEY; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_KEY_VALUE_CANNOT_BE_EMPTY; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_STREAM_ID; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_STREAM_ID_VALUE_CANNOT_BE_EMPTY; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_ANNOTATION_PRESENT; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_DISPATCHER_KEY; + +/** + * AsyncApiServiceMapper provides functionality for reading and writing AsyncApi, either to and from ballerina service, + * or to, as well as related functionality for performing conversions between AsyncApi and ballerina. + * + */ +public class AsyncApiServiceMapper { + private final AsyncApi25DocumentImpl asyncAPI; + private final SemanticModel semanticModel; + + /** + * Initializes a service parser for AsyncApi. + */ + public AsyncApiServiceMapper(SemanticModel semanticModel, AsyncApi25DocumentImpl asyncAPI) { + // Default object mapper is JSON mapper available in asyncApi utils. + this.semanticModel = semanticModel; + this.asyncAPI = asyncAPI; + } + + private String extractDispatcherValue(ServiceDeclarationNode service) { + String dispatcherValue = ""; + if (service.metadata().isPresent()) { + MetadataNode serviceMetadataNode = service.metadata().get(); + NodeList annotationNodes = serviceMetadataNode.annotations(); + AnnotationNode annotationNode = annotationNodes.get(0); + Node node = annotationNode.annotReference(); + if (node instanceof QualifiedNameReferenceNode) { + SeparatedNodeList fields = annotationNode.annotValue().get().fields(); + for (MappingFieldNode field : fields) { + if (field instanceof SpecificFieldNode) { + SpecificFieldNode specificFieldNode = (SpecificFieldNode) field; + String fieldName = specificFieldNode.fieldName().toString().trim(); + dispatcherValue = setFieldValues(dispatcherValue, specificFieldNode, fieldName); + if (fieldName.equals(DISPATCHER_STREAM_ID)) { + String dispatcherStreamIdValue = specificFieldNode.valueExpr().get().toString().trim(); + dispatcherStreamIdValue = dispatcherStreamIdValue.replaceAll("\"", ""); + if (dispatcherStreamIdValue.equals("")) { + //TODO : Give a proper name for Exception message + throw new NoSuchElementException(DISPATCHER_STREAM_ID_VALUE_CANNOT_BE_EMPTY); + } + asyncAPI.addExtension("x-dispatcherStreamId", new TextNode(dispatcherStreamIdValue)); + } + } + } + if (!dispatcherValue.equals("")) { + return dispatcherValue.trim(); + } + + if (dispatcherValue.isEmpty()) { + throw new NoSuchElementException(NO_DISPATCHER_KEY); + } + } + } else { + throw new NoSuchElementException(NO_ANNOTATION_PRESENT); + } + return null; + } + + private String setFieldValues(String dispatcherValue, SpecificFieldNode specificFieldNode, String fieldName) { + if (fieldName.equals(DISPATCHER_KEY)) { + dispatcherValue = specificFieldNode.valueExpr().get().toString().trim(); + dispatcherValue = dispatcherValue.replaceAll("\"", ""); + if (dispatcherValue.equals("")) { + //TODO : Give a proper name for Exception message + throw new NoSuchElementException(DISPATCHER_KEY_VALUE_CANNOT_BE_EMPTY); + } + asyncAPI.addExtension("x-dispatcherKey", new TextNode(dispatcherValue)); + } + return dispatcherValue; + } + + /** + * This method will convert ballerina @Service to asyncApi @AsyncApi object. + * + * @param service - Ballerina @Service object to be map to asyncApi definition + * @param asyncApi - AsyncApi model to populate + * @return AsyncApi object which represent current service. + */ + public AsyncApi25DocumentImpl convertServiceToAsyncAPI(ServiceDeclarationNode service, + List classDefinitionNodes, + AsyncApi25DocumentImpl asyncApi) { + //Take all resource functions + NodeList functions = service.members(); + + //Take dispatcherValue from @websocket:ServiceConfig annotation + String dispatcherValue = extractDispatcherValue(service); + for (Node function : functions) { + SyntaxKind kind = function.kind(); + if (kind.equals(SyntaxKind.RESOURCE_ACCESSOR_DEFINITION)) { + AsyncApiRemoteMapper resourceMapper = new AsyncApiRemoteMapper(this.semanticModel); + AsyncApi25ChannelsImpl generatedChannels = resourceMapper.getChannels((FunctionDefinitionNode) function, + classDefinitionNodes, dispatcherValue); + asyncApi.setChannels(generatedChannels); + AsyncApi25ComponentsImpl generatedComponents = resourceMapper.getComponents(); + asyncApi.setComponents(generatedComponents); + } + } + return asyncApi; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/CodegenUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/CodegenUtils.java new file mode 100644 index 000000000..33e8a4370 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/CodegenUtils.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Locale; +import java.util.Objects; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.JSON_EXTENSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.YAML_EXTENSION; + +/** + * Utilities used by ballerina asyncapi code generator. + * + */ +public final class CodegenUtils { + + /** + * Writes a file with content to specified {@code filePath}. + * + * @param filePath valid file path to write the content + * @param content content of the file + * @throws IOException when a file operation fails + */ + public static void writeFile(Path filePath, String content) throws IOException { + try (FileWriter writer = new FileWriter(filePath.toString(), StandardCharsets.UTF_8)) { + writer.write(content); + } + } + + /** + * This method use for checking the duplicate files. + * + * @param outPath output path for file generated + * @param asyncApiName given file name + * @return file name with duplicate number tag + */ + public static String resolveContractFileName(Path outPath, String asyncApiName, Boolean isJson) { + if (outPath != null && Files.exists(outPath)) { + final File[] listFiles = new File(String.valueOf(outPath)).listFiles(); + if (listFiles != null) { + asyncApiName = checkAvailabilityOfGivenName(asyncApiName, listFiles, isJson); + } + } + return asyncApiName; + } + + private static String checkAvailabilityOfGivenName(String asyncApiName, File[] listFiles, Boolean isJson) { + for (File file : listFiles) { + if (System.console() != null && file.getName().equals(asyncApiName)) { + String userInput = System.console().readLine("There is already a file named ' " + file.getName() + + "' in the target location. Do you want to overwrite the file? [y/N] "); + if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), "y")) { + asyncApiName = setGeneratedFileName(listFiles, asyncApiName, isJson); + } + } + } + return asyncApiName; + } + + /** + * This method for setting the file name for generated file. + * + * @param listFiles generated files + * @param fileName File name + */ + private static String setGeneratedFileName(File[] listFiles, String fileName, boolean isJson) { + int duplicateCount = 0; + for (File listFile : listFiles) { + String listFileName = listFile.getName(); + if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2) + && (listFileName.split("\\.")[0] + .equals(fileName.split("\\.")[0]))) { + duplicateCount++; + } + } + if (isJson) { + return fileName.split("\\.")[0] + "." + duplicateCount + JSON_EXTENSION; + } + return fileName.split("\\.")[0] + "." + duplicateCount + YAML_EXTENSION; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/ConverterCommonUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/ConverterCommonUtils.java new file mode 100644 index 000000000..e1ced33ad --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/ConverterCommonUtils.java @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import io.apicurio.datamodels.Library; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25Document; +import io.apicurio.datamodels.validation.ValidationProblem; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.DiagnosticMessages; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.ExceptionDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.AsyncApiResult; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalBooleanSchema; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.ModuleSymbol; +import io.ballerina.compiler.api.symbols.ServiceDeclarationSymbol; +import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.api.symbols.TypeDescKind; +import io.ballerina.compiler.api.symbols.TypeReferenceTypeSymbol; +import io.ballerina.compiler.api.symbols.TypeSymbol; +import io.ballerina.compiler.api.symbols.UnionTypeSymbol; +import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.runtime.api.utils.IdentifierUtils; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import io.ballerina.tools.diagnostics.Location; +import io.ballerina.tools.text.LinePosition; +import io.ballerina.tools.text.LineRange; +import io.ballerina.tools.text.TextRange; +import org.apache.commons.io.FilenameUtils; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.stream.Collectors; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.AsyncAPIType; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.BALLERINA; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.HYPHEN; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.JSON_EXTENSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SLASH; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SPECIAL_CHAR_REGEX; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.UNDERSCORE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.WEBSOCKET; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.YAML_EXTENSION; + +/** + * Utilities used in Ballerina to AsyncAPI converter. + * + */ +public class ConverterCommonUtils { + + /** + * Retrieves a matching AsyncApi {@link Schema} for a provided ballerina type. + * + * @param type ballerina type name as a String + * @return AsyncApi {@link Schema} for type defined by {@code type} + */ + public static BalAsyncApi25SchemaImpl getAsyncApiSchema(String type) { + BalAsyncApi25SchemaImpl schema = new BalAsyncApi25SchemaImpl(); + switch (type) { + case Constants.STRING: + case Constants.PLAIN: + schema.setType(AsyncAPIType.STRING.toString()); + break; + case Constants.BOOLEAN: + schema.setType(AsyncAPIType.BOOLEAN.toString()); + break; + case Constants.ARRAY: + case Constants.TUPLE: + schema.setType(AsyncAPIType.ARRAY.toString()); + break; + case Constants.INT: + case Constants.INTEGER: + schema.setType(AsyncAPIType.INTEGER.toString()); + schema.setFormat("int64"); + break; + case Constants.BYTE_ARRAY: + case Constants.OCTET_STREAM: + schema.setType(AsyncAPIType.STRING.toString()); + schema.setFormat("uuid"); + break; + case Constants.NUMBER: + case Constants.DECIMAL: + schema.setType(AsyncAPIType.NUMBER.toString()); + schema.setFormat(Constants.DOUBLE); + break; + case Constants.FLOAT: + schema.setType(AsyncAPIType.NUMBER.toString()); + schema.setFormat(Constants.FLOAT); + break; + case Constants.OBJECT: + schema.setType(AsyncAPIType.OBJECT.toString()); + //TODO: If there are so many types like map>, map>, + // map> then those also need to be handle + break; + case Constants.MAP_JSON: + case Constants.MAP: + schema.setType(AsyncAPIType.OBJECT.toString()); + schema.setAdditionalProperties(new BalBooleanSchema(true)); + break; + case Constants.TYPE_REFERENCE: + case Constants.TYPEREFERENCE: + case Constants.XML: + case Constants.JSON: + default: + schema = new BalAsyncApi25SchemaImpl(); //If json is required + break; + } + return schema; + } + + /** + * Retrieves a matching AsyncApi {@link Schema} for a provided ballerina type. + * + * @param type ballerina type with SYNTAX KIND + * @return AsyncApi {@link Schema} for type defined by {@code type} + */ + public static BalAsyncApi25SchemaImpl getAsyncApiSchema(SyntaxKind type) { + BalAsyncApi25SchemaImpl schema = new BalAsyncApi25SchemaImpl(); + switch (type) { + case STRING_TYPE_DESC: + schema.setType("string"); + break; + case BOOLEAN_TYPE_DESC: + schema.setType("boolean"); + break; + case ARRAY_TYPE_DESC: + schema.setType("array"); + break; + case INT_TYPE_DESC: + schema.setType("integer"); + schema.setFormat("int64"); + break; + case BYTE_TYPE_DESC: + schema.setType("string"); + schema.setFormat("uuid"); + break; + case DECIMAL_TYPE_DESC: + schema.setType("number"); + schema.setFormat(Constants.DOUBLE); + break; + case FLOAT_TYPE_DESC: + schema.setType("number"); + schema.setFormat(Constants.FLOAT); + break; + case MAP_TYPE_DESC: + schema.setType("object"); + break; + default: + schema = new BalAsyncApi25SchemaImpl(); + break; + } + return schema; + } + + /** + * Parse and get the {@link AsyncApi25Document} for the given AsyncAPI contract. + * + * @param definitionURI URI for the AsyncAPI contract + * @return {@link AsyncApiResult} AsyncAPI model + */ + public static AsyncApiResult parseAsyncAPIFile(String definitionURI) { + List diagnostics = new ArrayList<>(); + Path contractPath = Paths.get(definitionURI); + + if (!Files.exists(contractPath)) { + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTOR_103; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), + error.getDescription(), null); + diagnostics.add(diagnostic); + } + if (!(definitionURI.endsWith(Constants.YAML_EXTENSION) || definitionURI.endsWith(Constants.JSON_EXTENSION) + || definitionURI.endsWith(Constants.YML_EXTENSION))) { + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTOR_103; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), + error.getDescription(), null); + diagnostics.add(diagnostic); + } + String asyncAPIFileContent = null; + try { + asyncAPIFileContent = Files.readString(contractPath); + } catch (IOException e) { + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTOR_102; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), error.getDescription(), + null, e.toString()); + diagnostics.add(diagnostic); + } + YAMLFactory factory1 = YAMLFactory.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(factory1); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + AsyncApi25Document yamldoc; + try { + ObjectNode yamlNodes = (ObjectNode) mapper.readTree(asyncAPIFileContent); + yamldoc = (AsyncApi25Document) Library.readDocument(yamlNodes); + } catch (IOException e) { + throw new RuntimeException(e); + } + List yamlprob = Library.validate(yamldoc, null); + + if (!yamlprob.isEmpty()) { + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTOR_105; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), error.getDescription(), + null); + diagnostics.add(diagnostic); + return new AsyncApiResult(null, diagnostics); + } + AsyncApi25Document api = yamldoc; + return new AsyncApiResult(api, diagnostics); + } + + public static String normalizeTitle(String serviceName) { + if (serviceName == null) { + return null; + } + String[] urlPaths = (serviceName.replaceFirst(Constants.SLASH, "")).split(SPECIAL_CHAR_REGEX); + StringBuilder stringBuilder = new StringBuilder(); + String title = serviceName; + if (urlPaths.length > 1) { + for (String path : urlPaths) { + if (path.isBlank()) { + continue; + } + stringBuilder.append(path.substring(0, 1).toUpperCase(Locale.ENGLISH)); + stringBuilder.append(path.substring(1)); + stringBuilder.append(" "); + } + title = stringBuilder.toString().trim(); + } else if (urlPaths.length == 1 && !urlPaths[0].isBlank()) { + stringBuilder.append(urlPaths[0].substring(0, 1).toUpperCase(Locale.ENGLISH)); + stringBuilder.append(urlPaths[0].substring(1)); + title = stringBuilder.toString().trim(); + } + return title; + } + + /** + * This util function is to check the given service is a websocket service. + * + * @param serviceNode Service node for analyse + * @param semanticModel Semantic model + * @return boolean output + */ + public static boolean isWebsocketService(ServiceDeclarationNode serviceNode, SemanticModel semanticModel) { + Optional serviceSymbol = semanticModel.symbol(serviceNode); + if (serviceSymbol.isEmpty()) { + return false; + } + ServiceDeclarationSymbol serviceNodeSymbol = (ServiceDeclarationSymbol) serviceSymbol.get(); + List listenerTypes = (serviceNodeSymbol).listenerTypes(); + for (TypeSymbol listenerType : listenerTypes) { + if (isWebsocketListener(listenerType)) { + return true; + } + } + return false; + } + + private static boolean isWebsocketListener(TypeSymbol listenerType) { + if (listenerType.typeKind() == TypeDescKind.UNION) { + return ((UnionTypeSymbol) listenerType).memberTypeDescriptors().stream() + .filter(typeDescriptor -> typeDescriptor instanceof TypeReferenceTypeSymbol) + .map(typeReferenceTypeSymbol -> (TypeReferenceTypeSymbol) typeReferenceTypeSymbol) + .anyMatch(typeReferenceTypeSymbol -> isWebsocketModule(typeReferenceTypeSymbol.getModule().get())); + } + if (listenerType.typeKind() == TypeDescKind.TYPE_REFERENCE) { + return isWebsocketModule(((TypeReferenceTypeSymbol) listenerType).typeDescriptor().getModule().get()); + } + return false; + } + + private static boolean isWebsocketModule(ModuleSymbol moduleSymbol) { + if (moduleSymbol.getName().isPresent()) { + return WEBSOCKET.equals(moduleSymbol.getName().get()) && BALLERINA.equals(moduleSymbol.id().orgName()); + + } else { + return false; + } + } + + /** + * Generate file name with service basePath. + */ + public static String getAsyncApiFileName(String servicePath, String serviceName, boolean isJson) { + String asyncAPIFileName; + if (serviceName.isBlank() || serviceName.equals(SLASH) || serviceName.startsWith(SLASH + HYPHEN)) { + String[] fileName = serviceName.split(SLASH); + // This condition is to handle `service on ep1 {} ` multiple scenarios + if (fileName.length > 0 && !serviceName.isBlank()) { + asyncAPIFileName = FilenameUtils.removeExtension(servicePath) + fileName[1]; + } else { + asyncAPIFileName = FilenameUtils.removeExtension(servicePath); + } + } else if (serviceName.startsWith(HYPHEN)) { + // serviceName -> service on ep1 {} has multiple service ex: "-33456" + asyncAPIFileName = FilenameUtils.removeExtension(servicePath) + serviceName; + } else { + // Remove starting path separate if exists + if (serviceName.startsWith(SLASH)) { + serviceName = serviceName.substring(1); + } + // Replace rest of the path separators with underscore + asyncAPIFileName = serviceName.replaceAll(SLASH, "_"); + } + return getNormalizedFileName(asyncAPIFileName) + Constants.ASYNC_API_SUFFIX + + (isJson ? JSON_EXTENSION : YAML_EXTENSION); + } + + /** + * Remove special characters from the given file name. + */ + public static String getNormalizedFileName(String asyncAPIFileName) { + String[] splitNames = asyncAPIFileName.split("[^a-zA-Z0-9]"); + if (splitNames.length > 0) { + return Arrays.stream(splitNames) + .filter(namePart -> !namePart.isBlank()) + .collect(Collectors.joining(UNDERSCORE)); + } + return asyncAPIFileName; + } + + public static boolean containErrors(List diagnostics) { + return diagnostics != null && diagnostics.stream().anyMatch(diagnostic -> + diagnostic.diagnosticInfo().severity() == DiagnosticSeverity.ERROR); + } + + public static String unescapeIdentifier(String parameterName) { + String unescapedParamName = IdentifierUtils.unescapeBallerina(parameterName); + return unescapedParamName.trim().replaceAll("\\\\", "").replaceAll("'", ""); + } + + public static ObjectNode createObjectNode() { + return new ObjectNode(JsonNodeFactory.instance); + } + + public static ObjectMapper callObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); + return objectMapper; + } + + /** + * This {@code NullLocation} represents the null location allocation for scenarios which has not location. + */ + public static class NullLocation implements Location { + + @Override + public LineRange lineRange() { + LinePosition from = LinePosition.from(0, 0); + return LineRange.from("", from, from); + } + + @Override + public TextRange textRange() { + return TextRange.from(0, 0); + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/ServiceToAsyncApiConverterUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/ServiceToAsyncApiConverterUtils.java new file mode 100644 index 000000000..195257539 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/asyncspec/utils/ServiceToAsyncApiConverterUtils.java @@ -0,0 +1,504 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils; + +import io.apicurio.datamodels.Library; +import io.apicurio.datamodels.models.Info; +import io.apicurio.datamodels.models.ModelType; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25Document; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.validation.ValidationProblem; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.DiagnosticMessages; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.ExceptionDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.AsyncApiInfo; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.AsyncApiResult; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.service.AsyncApiEndpointMapper; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.service.AsyncApiServiceMapper; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.api.symbols.ModuleSymbol; +import io.ballerina.compiler.api.symbols.ServiceDeclarationSymbol; +import io.ballerina.compiler.api.symbols.Symbol; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ClassDefinitionNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.ListenerDeclarationNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.ModulePartNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.ServiceDeclarationNode; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.tools.diagnostics.Location; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ASYNCAPI_ANNOTATION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ASYNC_API_VERSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.CONTRACT; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.HYPHEN; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SLASH; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.SPECIAL_CHAR_REGEX; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.TITLE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.VERSION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.containErrors; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.getAsyncApiFileName; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.isWebsocketService; + +/** + * The ServiceToAsyncAPIConverterUtils provide API for convert ballerina service into asyncAPI specification. + * + */ +public class ServiceToAsyncApiConverterUtils { + + /** + * This method will generate asyncapi definition Map lists with ballerina code. + * + * @param syntaxTree - Syntax tree the related to ballerina service + * @param semanticModel - Semantic model related to ballerina module + * @param serviceName - Service name that need to generate the asyncAPI specification + * @param needJson - Flag for enabling the generated file format with json or YAML + * @param inputPath - Input file path for resolve the annotation details + * @return - {@link Map} with asyncAPI definitions for service nodes + */ + public static List generateAsyncAPISpecDefinition(SyntaxTree syntaxTree, + SemanticModel semanticModel, String serviceName, + Boolean needJson, Path inputPath) { + List endpoints = new ArrayList<>(); + Map servicesToGenerate = new LinkedHashMap<>(); + List availableService = new ArrayList<>(); + List diagnostics = new ArrayList<>(); + List outputs = new ArrayList<>(); + List classDefinitionNodes = new ArrayList<>(); + if (containErrors(semanticModel.diagnostics())) { + DiagnosticMessages messages = DiagnosticMessages.AAS_CONVERTOR_100; + ExceptionDiagnostic error = new ExceptionDiagnostic(messages.getCode(), messages.getDescription(), null); + diagnostics.add(error); + } else { + ModulePartNode modulePartNode = syntaxTree.rootNode(); + extractListenersAndServiceNodes(serviceName, availableService, servicesToGenerate, + classDefinitionNodes, modulePartNode, endpoints, semanticModel); + // If there are no META-INF.services found for a given service name. + if (serviceName != null && servicesToGenerate.isEmpty()) { + DiagnosticMessages messages = DiagnosticMessages.AAS_CONVERTOR_101; + ExceptionDiagnostic error = new ExceptionDiagnostic(messages.getCode(), + messages.getDescription(), null, serviceName, availableService.toString().trim()); + diagnostics.add(error); + } + // Generating asyncapi specification for selected META-INF.services + for (Map.Entry serviceNode : servicesToGenerate.entrySet()) { + String asyncApiName = getAsyncApiFileName(syntaxTree.filePath(), serviceNode.getKey(), needJson); + AsyncApiResult asyncAPIDefinition = generateAsyncApiSpec(serviceNode.getValue(), + endpoints, classDefinitionNodes, semanticModel, asyncApiName, inputPath); + asyncAPIDefinition.setServiceName(asyncApiName); + outputs.add(asyncAPIDefinition); + } + } + if (!diagnostics.isEmpty()) { + AsyncApiResult exceptions = new AsyncApiResult(null, diagnostics); + outputs.add(exceptions); + } + return outputs; + } + + /** + * Filter all the end points and service nodes. + */ + private static void extractListenersAndServiceNodes(String serviceName, List availableService, + Map servicesToGenerate, + List classDefinitionNodes, + ModulePartNode modulePartNode, + List endpoints, + SemanticModel semanticModel) { + for (Node node : modulePartNode.members()) { + SyntaxKind syntaxKind = node.kind(); + // Load a listen_declaration for the server part in the yaml spec + if (syntaxKind.equals(SyntaxKind.LISTENER_DECLARATION)) { + ListenerDeclarationNode listener = (ListenerDeclarationNode) node; + endpoints.add(listener); + } else if (syntaxKind.equals(SyntaxKind.SERVICE_DECLARATION)) { + ServiceDeclarationNode serviceNode = (ServiceDeclarationNode) node; + if (isWebsocketService(serviceNode, semanticModel)) { + // Here check the service is related to the http + // module by checking listener type that attached to service endpoints. + Optional serviceSymbol = semanticModel.symbol(serviceNode); + if (serviceSymbol.isPresent() && serviceSymbol.get() instanceof ServiceDeclarationSymbol) { + String service = AsyncApiEndpointMapper.ENDPOINT_MAPPER.getServiceBasePath(serviceNode); + String updateServiceName = service; + //`String updateServiceName` used to track the service + // name for service file contains multiple service node. + + // Using absolute path we generate file name, therefore having same name may overwrite + // the file, due to this suppose to use hashcode as identity factor for the file name. + // Generated file name for above example -> hello_asyncapi.yaml, hello_45673_asyncapi + //.yaml + if (servicesToGenerate.containsKey(service)) { + updateServiceName = service + HYPHEN + serviceSymbol.get().hashCode(); + } + if (serviceName != null) { + // Filtering by service name + availableService.add(service); + if (serviceName.equals(service)) { + servicesToGenerate.put(updateServiceName, serviceNode); + } + } else { + // To generate for all META-INF.services + servicesToGenerate.put(updateServiceName, serviceNode); + } + } + } + } else if (syntaxKind.equals(SyntaxKind.CLASS_DEFINITION)) { + ClassDefinitionNode serviceNode = (ClassDefinitionNode) node; + classDefinitionNodes.add(serviceNode); + } + } + } + + /** + * Provides an instance of {@code AsyncAPIResult}, which contains the generated contract as well as + * all the diagnostics information. + * + * @param serviceDefinition Service Node related to ballerina service + * @param endpoints Listener endpoints that bind to service + * @param semanticModel Semantic model for given ballerina file + * @param asyncApiFileName AsyncAPI file name + * @param ballerinaFilePath Input ballerina file Path + * @return {@code AsyncAPIResult} + */ + public static AsyncApiResult generateAsyncApiSpec(ServiceDeclarationNode serviceDefinition, + List endpoints, + List classDefinitionNodes, + SemanticModel semanticModel, String asyncApiFileName, + Path ballerinaFilePath) { + // 01.Fill the asyncAPI info section + AsyncApiResult asyncApiResult = fillAsyncAPIInfoSection(serviceDefinition, semanticModel, + asyncApiFileName, ballerinaFilePath); + if (asyncApiResult.getAsyncAPI().isPresent() && asyncApiResult.getDiagnostics().isEmpty()) { + AsyncApi25DocumentImpl asyncapi = (AsyncApi25DocumentImpl) asyncApiResult.getAsyncAPI().get(); + if (asyncapi.getChannels() == null) { + // Take base path of service + AsyncApiServiceMapper asyncAPIServiceMapper = new AsyncApiServiceMapper(semanticModel, asyncapi); + // 02. Filter and set the ServerURLs according to endpoints. Complete the server section in AsyncAPISpec + asyncapi = AsyncApiEndpointMapper.ENDPOINT_MAPPER.getServers(asyncapi, endpoints, serviceDefinition); + // 03. Filter path and component sections in AsyncAPISpec. + // Generate asyncApi string for the mentioned service name. + asyncapi = asyncAPIServiceMapper.convertServiceToAsyncAPI(serviceDefinition, + classDefinitionNodes, asyncapi); + List modelProblems = Library.validate(asyncapi, null); + if (!(modelProblems.isEmpty())) { + List diagnostics = new ArrayList<>(); + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTER_107; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), + error.getDescription(), null); + diagnostics.add(diagnostic); + return new AsyncApiResult(null, diagnostics); + } else { + return new AsyncApiResult(asyncapi, null); + } + } else { + return new AsyncApiResult(asyncapi, asyncApiResult.getDiagnostics()); + } + } else { + return asyncApiResult; + } + } + + /** + * This function is for completing the AsyncAPI info section with package details and annotation details. + *

+ * First check the given service node has metadata with annotation details with `asyncapi:serviceInfo`, + * if it is there, then {@link #parseServiceInfoAnnotationAttachmentDetails(List, AnnotationNode, Path)} + * function extracts the annotation details and store details in {@code AsyncAPIInfo} model using + * {@link #updateAsyncAPIInfoModel(SeparatedNodeList)} function. If the annotation contains the valid contract + * path then we complete given AsyncAPI specification using annotation details. if not we create new AsyncAPI + * specification and fill asyncAPI info sections. + * If the annotation is not in the given service, then we filled the AsyncAPI specification info section using + * package details and title with service base path. + * After completing these two process we normalized the AsyncAPI specification by checking all the info + * details are completed, if in case not completed, we complete empty fields with default values. + * + * @param serviceNode Service node for relevant service. + * @param semanticModel Semantic model for relevant project. + * @param asyncApiFileName AsyncAPI generated file name. + * @param ballerinaFilePath Ballerina file path. + * @return {@code AsyncAPIResult} + */ + private static AsyncApiResult fillAsyncAPIInfoSection(ServiceDeclarationNode serviceNode, + SemanticModel semanticModel, String asyncApiFileName, + Path ballerinaFilePath) { + Optional metadata = serviceNode.metadata(); + List diagnostics = new ArrayList<>(); + AsyncApi25Document asyncAPI = (AsyncApi25Document) Library.createDocument(ModelType.ASYNCAPI25); + asyncAPI.setAsyncapi(ASYNC_API_VERSION); + String currentServiceName = AsyncApiEndpointMapper.ENDPOINT_MAPPER.getServiceBasePath(serviceNode); + // 01. Set asyncAPI inFo section with package details + String version = getContractVersion(serviceNode, semanticModel); + if (metadata.isPresent() && !metadata.get().annotations().isEmpty()) { + MetadataNode metadataNode = metadata.get(); + NodeList annotations = metadataNode.annotations(); + for (AnnotationNode annotation : annotations) { + if (annotation.annotReference().kind() == SyntaxKind.QUALIFIED_NAME_REFERENCE) { + QualifiedNameReferenceNode ref = (QualifiedNameReferenceNode) annotation.annotReference(); + String annotationName = ref.modulePrefix().text() + ":" + ref.identifier().text(); + //TODO : This asyncApi annotation part not yet implemented + // Create annotation and push it to ballerina central + if (annotationName.equals(ASYNCAPI_ANNOTATION)) { + AsyncApiResult asyncApiResult = parseServiceInfoAnnotationAttachmentDetails(diagnostics, + annotation, ballerinaFilePath); + return normalizeInfoSection(asyncApiFileName, currentServiceName, version, asyncApiResult); + } else { + Info info = asyncAPI.createInfo(); + info.setVersion(version); + info.setTitle(normalizeTitle(currentServiceName)); + asyncAPI.setInfo(info); + } + } + } + } else if (currentServiceName.equals(SLASH) || currentServiceName.isBlank()) { + Info info = asyncAPI.createInfo(); + info.setVersion(version); + info.setTitle(normalizeTitle(asyncApiFileName)); + asyncAPI.setInfo(info); + } else { + Info info = asyncAPI.createInfo(); + info.setVersion(version); + info.setTitle(normalizeTitle(currentServiceName)); + asyncAPI.setInfo(info); + } + return new AsyncApiResult(asyncAPI, diagnostics); + } + + // Finalize the asyncAPI info section + private static AsyncApiResult normalizeInfoSection(String asyncApiFileName, String currentServiceName, + String version, AsyncApiResult asyncApiResult) { + if (asyncApiResult.getAsyncAPI().isPresent()) { + AsyncApi25Document asyncAPI = asyncApiResult.getAsyncAPI().get(); + if (asyncAPI.getInfo() == null) { + String title = normalizeTitle(currentServiceName); + if (currentServiceName.equals(SLASH)) { + title = normalizeTitle(asyncApiFileName); + } + Info info = asyncAPI.createInfo(); + info.setVersion(version); + info.setTitle(title); + asyncAPI.setInfo(info); + } else { + if (asyncAPI.getInfo().getTitle() == null) { + asyncAPI.getInfo().setTitle(normalizeTitle(currentServiceName)); + } else if (asyncAPI.getInfo().getTitle() != null && asyncAPI.getInfo().getTitle().equals(SLASH)) { + asyncAPI.getInfo().setTitle(normalizeTitle(asyncApiFileName)); + } else if (asyncAPI.getInfo().getTitle().isBlank()) { + asyncAPI.getInfo().setTitle(normalizeTitle(currentServiceName)); + } else if (asyncAPI.getInfo().getTitle() == null && currentServiceName.equals(SLASH)) { + asyncAPI.getInfo().setTitle(normalizeTitle(asyncApiFileName)); + } + if (asyncAPI.getInfo().getVersion() == null || asyncAPI.getInfo().getVersion().isBlank()) { + asyncAPI.getInfo().setVersion(version); + } + } + return new AsyncApiResult(asyncAPI, asyncApiResult.getDiagnostics()); + } else { + return asyncApiResult; + } + } + + // Set contract version by default using package version. + private static String getContractVersion(ServiceDeclarationNode serviceDefinition, SemanticModel semanticModel) { + Optional symbol = semanticModel.symbol(serviceDefinition); + String version = "1.0.0"; + if (symbol.isPresent()) { + Symbol serviceSymbol = symbol.get(); + Optional module = serviceSymbol.getModule(); + if (module.isPresent()) { + version = module.get().id().version(); + } + } + return version; + } + + private static String normalizeTitle(String title) { + if (title != null) { + String[] splits = (title.replaceFirst(SLASH, "")).split(SPECIAL_CHAR_REGEX); + StringBuilder stringBuilder = new StringBuilder(); + if (splits.length > 1) { + for (String piece : splits) { + if (piece.isBlank()) { + continue; + } + stringBuilder.append(piece.substring(0, 1).toUpperCase(Locale.ENGLISH)). + append(piece.substring(1)); + stringBuilder.append(" "); + } + title = stringBuilder.toString().trim(); + } else if (splits.length == 1 && !splits[0].isBlank()) { + stringBuilder.append(splits[0].substring(0, 1).toUpperCase(Locale.ENGLISH)). + append(splits[0].substring(1)); + title = stringBuilder.toString().trim(); + } + return title; + } + return null; + } + + // Set annotation details for info section. + private static AsyncApiResult parseServiceInfoAnnotationAttachmentDetails( + List diagnostics, AnnotationNode annotation, Path ballerinaFilePath) { + Location location = annotation.location(); + AsyncApi25Document asyncAPI = (AsyncApi25Document) Library.createDocument(ModelType.ASYNCAPI25); + asyncAPI.setAsyncapi(ASYNC_API_VERSION); + Optional content = annotation.annotValue(); + // If contract path there + if (content.isPresent()) { + SeparatedNodeList fields = content.get().fields(); + if (!fields.isEmpty()) { + AsyncApiInfo asyncAPIInfo = updateAsyncAPIInfoModel(fields); + // If in case ballerina file path is getting null, then asyncAPI specification will be generated for + // given META-INF.services. + if (asyncAPIInfo.getContractPath().isPresent() && ballerinaFilePath != null) { + return updateExistingContractAsyncAPI(diagnostics, location, asyncAPIInfo, ballerinaFilePath); + } else if (asyncAPIInfo.getTitle().isPresent() && asyncAPIInfo.getVersion().isPresent()) { + Info info = asyncAPI.createInfo(); + info.setVersion(asyncAPIInfo.getVersion().get()); + info.setTitle(normalizeTitle(asyncAPIInfo.getTitle().get())); + asyncAPI.setInfo(info); + } else if (asyncAPIInfo.getVersion().isPresent()) { + Info info = asyncAPI.createInfo(); + info.setVersion(asyncAPIInfo.getVersion().get()); + asyncAPI.setInfo(info); + } else if (asyncAPIInfo.getTitle().isPresent()) { + Info info = asyncAPI.createInfo(); + info.setTitle(normalizeTitle(asyncAPIInfo.getTitle().get())); + asyncAPI.setInfo(info); + } + } + } + return new AsyncApiResult(asyncAPI, diagnostics); + } + + private static AsyncApiResult updateExistingContractAsyncAPI(List diagnostics, + Location location, AsyncApiInfo asyncAPIInfo, + Path ballerinaFilePath) { + AsyncApiResult asyncAPIResult = resolveContractPath(diagnostics, location, asyncAPIInfo, ballerinaFilePath); + Optional contract = asyncAPIResult.getAsyncAPI(); + if (contract.isEmpty()) { + return asyncAPIResult; + } + AsyncApi25Document asyncApi = contract.get(); + if (asyncAPIInfo.getVersion().isPresent() && asyncAPIInfo.getTitle().isPresent()) { + // read the asyncapi + asyncApi.getInfo().setVersion(asyncAPIInfo.getVersion().get()); + asyncApi.getInfo().setTitle(asyncAPIInfo.getTitle().get()); + diagnostics.addAll(asyncAPIResult.getDiagnostics()); + return new AsyncApiResult(asyncApi, asyncAPIResult.getDiagnostics()); + } else if (asyncAPIInfo.getTitle().isPresent()) { + asyncApi.getInfo().setTitle(asyncAPIInfo.getTitle().get()); + return new AsyncApiResult(asyncApi, asyncAPIResult.getDiagnostics()); + } else if (asyncAPIInfo.getVersion().isPresent()) { + asyncApi.getInfo().setVersion(asyncAPIInfo.getVersion().get()); + return new AsyncApiResult(asyncApi, asyncAPIResult.getDiagnostics()); + } else { + return asyncAPIResult; + } + } + + private static AsyncApiInfo updateAsyncAPIInfoModel(SeparatedNodeList fields) { + AsyncApiInfo.AsyncAPIInfoBuilder infoBuilder = new AsyncApiInfo.AsyncAPIInfoBuilder(); + for (MappingFieldNode field : fields) { + String fieldName = ((SpecificFieldNode) field).fieldName().toString().trim(); + Optional value = ((SpecificFieldNode) field).valueExpr(); + String fieldValue; + if (value.isPresent()) { + ExpressionNode expressionNode = value.get(); + if (!expressionNode.toString().trim().isBlank()) { + fieldValue = expressionNode.toString().trim().replaceAll("\"", ""); + if (!fieldValue.isBlank()) { + switch (fieldName) { + case CONTRACT: + infoBuilder.contractPath(fieldValue); + break; + case TITLE: + infoBuilder.title(fieldValue); + break; + case VERSION: + infoBuilder.version(fieldValue); + break; + default: + break; + } + } + } + } + } + return infoBuilder.build(); + } + + private static AsyncApiResult resolveContractPath(List diagnostics, Location location, + AsyncApiInfo asyncAPIInfo, Path ballerinaFilePath) { + AsyncApiResult asyncApiResult; + AsyncApi25Document asyncApi = null; + Path asyncApiPath = Paths.get(asyncAPIInfo.getContractPath().get(). + replaceAll("\"", "").trim()); + Path relativePath = null; + if (asyncApiPath.toString().trim().isBlank()) { + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTOR_103; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), error.getDescription(), location); + diagnostics.add(diagnostic); + } else { + Path path = Paths.get(asyncApiPath.toString()); + if (path.isAbsolute()) { + relativePath = path; + } else { + File file = new File(ballerinaFilePath.toString()); + File parentFolder = new File(file.getParent()); + File asyncApiContract = new File(parentFolder, asyncApiPath.toString()); + try { + relativePath = Paths.get(asyncApiContract.getCanonicalPath()); + } catch (IOException e) { + DiagnosticMessages error = DiagnosticMessages.AAS_CONVERTOR_102; + ExceptionDiagnostic diagnostic = new ExceptionDiagnostic(error.getCode(), + error.getDescription(), location, e.toString()); + diagnostics.add(diagnostic); + } + } + } + if (relativePath != null && Files.exists(relativePath)) { + asyncApiResult = ConverterCommonUtils.parseAsyncAPIFile(relativePath.toString()); + if (asyncApiResult.getAsyncAPI().isPresent()) { + asyncApi = asyncApiResult.getAsyncAPI().get(); + } + diagnostics.addAll(asyncApiResult.getDiagnostics()); + } + return new AsyncApiResult(asyncApi, diagnostics); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/BallerinaAuthConfigGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/BallerinaAuthConfigGenerator.java new file mode 100644 index 000000000..c2661e765 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/BallerinaAuthConfigGenerator.java @@ -0,0 +1,1577 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.apicurio.datamodels.models.SecurityScheme; +import io.apicurio.datamodels.models.asyncapi.AsyncApiChannelItem; +import io.apicurio.datamodels.models.asyncapi.AsyncApiParameter; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25BindingImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ChannelBindingsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ParametersImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SecuritySchemeImpl; +import io.apicurio.datamodels.models.union.BooleanUnionValueImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.model.BalAsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils; +import io.ballerina.asyncapi.websocketscore.generators.document.DocCommentsGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ArrayDimensionNode; +import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; +import io.ballerina.compiler.syntax.tree.BasicLiteralNode; +import io.ballerina.compiler.syntax.tree.BlockStatementNode; +import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; +import io.ballerina.compiler.syntax.tree.CheckExpressionNode; +import io.ballerina.compiler.syntax.tree.DefaultableParameterNode; +import io.ballerina.compiler.syntax.tree.ElseBlockNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionArgumentNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.IfElseStatementNode; +import io.ballerina.compiler.syntax.tree.ImplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.MapTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; +import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.ObjectFieldNode; +import io.ballerina.compiler.syntax.tree.ParenthesizedArgList; +import io.ballerina.compiler.syntax.tree.PositionalArgumentNode; +import io.ballerina.compiler.syntax.tree.RecordFieldNode; +import io.ballerina.compiler.syntax.tree.RecordFieldWithDefaultValueNode; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.RequiredExpressionNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.TypeParameterNode; +import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; +import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.API_KEY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.API_KEYS_CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.API_KEY_CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.AUTH; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.AuthConfigTypes; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BASIC; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BEARER; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BOOLEAN; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLIENT_CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLIENT_CRED; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONNECTION_CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CUSTOM_HEADERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.HTTP; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.HTTP_API_KEY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OAUTH2; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PASSWORD; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PING_PONG_SERVICE_FIELD; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.QUERY_PARAMS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.REFRESH_TOKEN; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SECURE_SOCKET_FIELD; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SELF; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.USER_PASSWORD; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.VALIDATION; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.escapeIdentifier; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.getValidName; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createArrayTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createAssignmentStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBasicLiteralNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBinaryExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBlockStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCaptureBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCheckExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createDefaultableParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createElseBlockNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldAccessExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIfElseStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createImplicitNewExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIncludedRecordParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIntersectionTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMapTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMappingConstructorExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMethodCallExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createObjectFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createParenthesizedArgList; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createPositionalArgumentNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRecordFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRecordFieldWithDefaultValueNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSpecificFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeReferenceTypeDescNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypedBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createVariableDeclarationNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ASTERISK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BITWISE_AND_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BOOLEAN_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CHECK_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.DECIMAL_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.DOT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ELSE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FINAL_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.GT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.IF_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.INT_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.IS_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.LT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.MAP_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.NEW_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.READONLY_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RECORD_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_LITERAL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TRUE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_KEYWORD; + +/** + * This class is used to generate authentication related nodes of the ballerina connector client syntax tree. + * + */ +public class BallerinaAuthConfigGenerator { + + private final Map headerApiKeyNameList = new HashMap<>(); + private final Map queryApiKeyNameList = new HashMap<>(); + private final List apiKeysConfigRecordFields = new ArrayList<>(); + private final Set authTypes = new LinkedHashSet<>(); + private final BallerinaTypesGenerator ballerinaSchemaGenerator; + private boolean httpApiKey; + private boolean isPathParam = false; + private boolean isQueryParam = false; + private boolean isHeaderParam = false; + private boolean httpOROAuth; + private String clientCredGrantTokenUrl; + private String passwordGrantTokenUrl; + private String refreshTokenUrl; + private List authRelatedTypeDefinitionNodes = new ArrayList<>(); + + public BallerinaAuthConfigGenerator(boolean isAPIKey, boolean isHttpOROAuth, + BallerinaTypesGenerator ballerinaSchemaGenerator) { + this.httpApiKey = isAPIKey; + this.httpOROAuth = isHttpOROAuth; + this.ballerinaSchemaGenerator = ballerinaSchemaGenerator; + } + + public boolean isPathParam() { + return isPathParam; + } + + public boolean isQueryParam() { + return isQueryParam; + } + + public boolean isHeaderParam() { + return isHeaderParam; + } + + /** + * Returns `true` if authentication mechanism is API key. + * + * @return {@link boolean} values of the flag isAPIKey + */ + public boolean isHttpApiKey() { + return httpApiKey; + } + + /** + * Returns `true` if HTTP or OAuth authentication is supported. + * + * @return {@link boolean} + */ + public boolean isHttpOrOAuth() { + return httpOROAuth; + } + + /** + * Returns API key names which need to send in the query string. + * + * @return {@link List} API key name list + */ + public Map getQueryApiKeyNameList() { + return queryApiKeyNameList; + } + + /** + * Returns API key names which need to send as request headers. + * + * @return {@link List} API key name list + */ + public Map getHeaderApiKeyNameList() { + return headerApiKeyNameList; + } + + /** + * Returns auth type to generate test file. + * + * @return {@link Set} + */ + public Set getAuthType() { + return authTypes; + } + + public List getAuthRelatedTypeDefinitionNodes() { + return authRelatedTypeDefinitionNodes; + } + + /** + * Add authentication related records. + * + * @param asyncAPI AsyncAPI object received from apicurio parser + * @throws BallerinaAsyncApiExceptionWs When function fails + */ + public void addAuthRelatedRecords(AsyncApi25DocumentImpl asyncAPI) throws + BallerinaAsyncApiExceptionWs { + List nodes = new ArrayList<>(); + if (asyncAPI.getComponents() != null) { + // set auth types + if (asyncAPI.getComponents().getSecuritySchemes() != null) { + Map securitySchemeMap = asyncAPI.getComponents().getSecuritySchemes(); + setAuthTypes(securitySchemeMap); + } + + // generate related records +// TypeDefinitionNode connectionConfigRecord = generateConnectionConfigRecord(); +// nodes.add(connectionConfigRecord); + +// TypeDefinitionNode clientHttp1SettingsRecord = getClientHttp1SettingsRecord(); +// TypeDefinitionNode customProxyConfigRecord = getCustomProxyRecord(); +// nodes.addAll(Arrays.asList(connectionConfigRecord, clientHttp1SettingsRecord, customProxyConfigRecord)); + + + if (isHttpApiKey()) { + nodes.add(generateApiKeysConfig()); + } + + // Add custom `OAuth2ClientCredentialsGrantConfig` record with default tokenUrl if `tokenUrl` is available + if (clientCredGrantTokenUrl != null) { + nodes.add(getOAuth2ClientCredsGrantConfigRecord()); + } + + // Add custom `OAuth2PasswordGrantConfig` record with default tokenUrl if `tokenUrl` is available + if (passwordGrantTokenUrl != null) { + nodes.add(getOAuth2PasswordGrantConfigRecord()); + } + + // Add custom `OAuth2RefreshTokenGrantConfig` record with default refreshUrl if `refreshUrl` is available + if (refreshTokenUrl != null) { + nodes.add(getOAuth2RefreshTokenGrantConfigRecord()); + } + } + this.authRelatedTypeDefinitionNodes = nodes; + } + + /** + * Generate the Config record for the relevant authentication type. + * -- ex: Config record for Http and OAuth 2.0 Authentication mechanisms. + *

+     * # Provides a set of configurations for controlling the behaviours when communicating with a remote WEBSOCKET
+     * service endpoint.
+     * public type ConnectionConfig record {|
+     *          # Configurations related to client authentication
+     *          websocket:BearerTokenConfig|websocket:OAuth2RefreshTokenGrantConfig auth;
+     *          # Negotiable sub protocols of the client
+     *          string[] subProtocols = [];
+     *          # Custom headers, which should be sent to the server
+     *          map customHeaders = {};
+     *          # Read timeout (in seconds) of the client
+     *          decimal readTimeout = -1;
+     *          # Write timeout (in seconds) of the client
+     *          decimal writeTimeout = -1;
+     *          # SSL/TLS-related options
+     *          websocket:ClientSecureSocket? secureSocket = ();
+     *          # The maximum payload size of a WebSocket frame in bytes
+     *          int maxFrameSize = 65536;
+     *          # Enable support for compression in the WebSocket
+     *          boolean webSocketCompressionEnabled = true;
+     *          # Time (in seconds) that a connection waits to get the response of the WebSocket handshake.
+     *          decimal handShakeTimeout = 300;
+     *          # An Array of http:Cookie
+     *          http:Cookie[] cookies?;
+     *          # A service to handle the ping/pong frames.
+     *          PingPongService pingPongHandler?;
+     *          # Configurations associated with retrying
+     *          websocket:WebSocketRetryConfig retryConfig? = ();
+     *          Enable/disable constraint validation
+     *          boolean validation = true;Z
+     * |};
+     * 
+ * Scenario 1 : For asyncapi contracts with no authentication mechanism given, auth field will not be generated + * Scenario 2 : For asyncapi contracts with authentication mechanism, auth field in relevant types will be generated + * Scenario 3 : For asyncapi contracts with only apikey authentication mechanism, auth field will not be generated + * Scenario 4 : For asyncapi contracts with both http and apikey authentication mechanisms given, + * auth field in relevant types will be generated + * + * @return {@link TypeDefinitionNode} Syntax tree node of config record + */ + public TypeDefinitionNode generateConnectionConfigRecord() { + +// AnnotationNode annotationNode = getDisplayAnnotationForRecord("Connection Config"); +// MetadataNode configRecordMetadataNode = getMetadataNode( +// "Provides a set of configurations for controlling the behaviours when communicating " + +// "with a remote HTTP endpoint.", Collections.singletonList(annotationNode)); + Token typeName = AbstractNodeFactory.createIdentifierToken(CONNECTION_CONFIG); + NodeList recordFieldList = createNodeList(getClientConfigRecordFields()); + + RecordTypeDescriptorNode recordTypeDescriptorNode = + NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); +// TypeDefinitionNode node = NodeFactory.createTypeDefinitionNode(configRecordMetadataNode, +// createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, +// recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + TypeDefinitionNode node = NodeFactory.createTypeDefinitionNode(null, + createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, + recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + return node; + + } + + /** + * Generate the ApiKeysConfig record when the http-api-key auth type is given. + *
+     *  # Provides API key configurations needed when communicating with a remote WEBSOCKET service endpoint.
+     *  public type ApiKeysConfig record {|
+     *     # Represents API Key `Authorization`
+     *     string authorization;
+     *     # Represents API Key `apikey`
+     *     string apikey;
+     *  |};
+     * 
+ * + * @return {@link TypeDefinitionNode} Syntax tree node of config record + */ + public TypeDefinitionNode generateApiKeysConfig() { + MetadataNode configRecordMetadataNode = getMetadataNode( + "Provides API key configurations needed when communicating " + + "with a remote WEBSOCKET service endpoint."); + Token typeName = AbstractNodeFactory.createIdentifierToken(API_KEYS_CONFIG); + NodeList recordFieldList = createNodeList(apiKeysConfigRecordFields); + RecordTypeDescriptorNode recordTypeDescriptorNode = + NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); + return NodeFactory.createTypeDefinitionNode(configRecordMetadataNode, + createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, + recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * Create `OAuth2ClientCredentialsGrantConfig` record with default tokenUrl. + * + *
+     *      # OAuth2 Client Credentials Grant Configs
+     *      public type OAuth2ClientCredentialsGrantConfig record {|
+     *          *websocket:OAuth2ClientCredentialsGrantConfig;
+     *          # Token URL
+     *          string tokenUrl = "https://zoom.us/oauth/token";
+     *      |};
+     * 
+ * + * @return {@link TypeDefinitionNode} Custom `OAuth2ClientCredentialsGrantConfig` record with default tokenUrl + */ + private TypeDefinitionNode getOAuth2ClientCredsGrantConfigRecord() { + Token typeName = AbstractNodeFactory.createIdentifierToken(AuthConfigTypes.CUSTOM_CLIENT_CREDENTIAL.getValue()); + NodeList recordFieldList = createNodeList(getClientCredsGrantConfigFields()); + MetadataNode configRecordMetadataNode = getMetadataNode("OAuth2 Client Credentials Grant Configs"); + RecordTypeDescriptorNode recordTypeDescriptorNode = + NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); + return NodeFactory.createTypeDefinitionNode(configRecordMetadataNode, + createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, + recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * Generates fields of `OAuth2ClientCredentialsGrantConfig` record with default tokenUrl. + * + *
+     *      *websocket:OAuth2ClientCredentialsGrantConfig;
+     *      # Token URL
+     *      string tokenUrl = "https://zoom.us/oauth/token";
+     * 
+ * + * @return {@link List} + */ + private List getClientCredsGrantConfigFields() { + List recordFieldNodes = new ArrayList<>(); + Token semicolonToken = createToken(SEMICOLON_TOKEN); + Token equalToken = createToken(EQUAL_TOKEN); + + recordFieldNodes.add(createIncludedRecordParameterNode(createEmptyNodeList(), + createToken(ASTERISK_TOKEN), + createIdentifierToken("websocket:OAuth2ClientCredentialsGrantConfig;"), null)); + + MetadataNode metadataNode = getMetadataNode("Token URL"); + TypeDescriptorNode stringType = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + IdentifierToken fieldNameTokenUrl = createIdentifierToken("tokenUrl"); + ExpressionNode defaultValue = createRequiredExpressionNode(createIdentifierToken("\"" + + clientCredGrantTokenUrl + "\"")); + RecordFieldWithDefaultValueNode fieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + metadataNode, null, stringType, fieldNameTokenUrl, equalToken, defaultValue, + semicolonToken); + recordFieldNodes.add(fieldNode); + return recordFieldNodes; + } + + /** + * Create `OAuth2PasswordGrantConfig` record with default tokenUrl. + * + *
+     *      # OAuth2 Password Grant Configs
+     *      public type OAuth2PasswordGrantConfig record {|
+     *          *websocket:OAuth2PasswordGrantConfig;
+     *          # Token URL
+     *          string tokenUrl = "https://zoom.us/oauth/token";
+     *      |};
+     * 
+ * + * @return {@link TypeDefinitionNode} Custom `OAuth2PasswordGrantConfig` record with default tokenUrl + */ + private TypeDefinitionNode getOAuth2PasswordGrantConfigRecord() { + Token typeName = AbstractNodeFactory.createIdentifierToken(AuthConfigTypes.CUSTOM_PASSWORD.getValue()); + NodeList recordFieldList = createNodeList(getPasswordGrantConfigFields()); + MetadataNode configRecordMetadataNode = getMetadataNode("OAuth2 Password Grant Configs"); + RecordTypeDescriptorNode recordTypeDescriptorNode = + NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); + return NodeFactory.createTypeDefinitionNode(configRecordMetadataNode, + createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, + recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * Generates fields of `OAuth2PasswordGrantConfig` record with default tokenUrl. + * + *
+     *      *websocket:OAuth2PasswordGrantConfig;
+     *      # Token URL
+     *      string tokenUrl = "https://zoom.us/oauth/token";
+     * 
+ * + * @return {@link List} + */ + private List getPasswordGrantConfigFields() { + + List recordFieldNodes = new ArrayList<>(); + Token semicolonToken = createToken(SEMICOLON_TOKEN); + Token equalToken = createToken(EQUAL_TOKEN); + + recordFieldNodes.add(createIncludedRecordParameterNode(createEmptyNodeList(), + createToken(ASTERISK_TOKEN), + createIdentifierToken("websocket:OAuth2PasswordGrantConfig;"), null)); + + MetadataNode metadataNode = getMetadataNode("Token URL"); + TypeDescriptorNode stringType = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + IdentifierToken fieldNameTokenUrl = createIdentifierToken("tokenUrl"); + ExpressionNode defaultValue = createRequiredExpressionNode(createIdentifierToken("\"" + + passwordGrantTokenUrl + "\"")); + RecordFieldWithDefaultValueNode fieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + metadataNode, null, stringType, fieldNameTokenUrl, equalToken, defaultValue, + semicolonToken); + recordFieldNodes.add(fieldNode); + return recordFieldNodes; + } + + /** + * Create `OAuth2RefreshTokenGrantConfig` record with default refreshUrl. + * + *
+     *      # OAuth2 Refresh Token Grant Configs
+     *      public type OAuth2RefreshTokenGrantConfig record {|
+     *          *websocket:OAuth2RefreshTokenGrantConfig;
+     *          # Refresh URL
+     *          string refreshUrl = "https://zoom.us/oauth/token";
+     *      |};
+     * 
+ * + * @return {@link TypeDefinitionNode} Custom `OAuth2RefreshTokenGrantConfig` record with default refreshUrl + */ + private TypeDefinitionNode getOAuth2RefreshTokenGrantConfigRecord() { + Token typeName = AbstractNodeFactory.createIdentifierToken(AuthConfigTypes.CUSTOM_REFRESH_TOKEN.getValue()); + NodeList recordFieldList = createNodeList(getRefreshTokenGrantConfigFields()); + MetadataNode configRecordMetadataNode = getMetadataNode("OAuth2 Refresh Token Grant Configs"); + RecordTypeDescriptorNode recordTypeDescriptorNode = + NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + createToken(OPEN_BRACE_PIPE_TOKEN), recordFieldList, null, + createToken(CLOSE_BRACE_PIPE_TOKEN)); + return NodeFactory.createTypeDefinitionNode(configRecordMetadataNode, + createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), typeName, + recordTypeDescriptorNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * Generates fields of `OAuth2RefreshTokenGrantConfig` record with default refreshUrl. + * + *
+     *      *websocket:OAuth2RefreshTokenGrantConfig;
+     *      # Refresh URL
+     *      string refreshUrl = "https://zoom.us/oauth/token";
+     * 
+ * + * @return {@link List} + */ + private List getRefreshTokenGrantConfigFields() { + + List recordFieldNodes = new ArrayList<>(); + Token semicolonToken = createToken(SEMICOLON_TOKEN); + Token equalToken = createToken(EQUAL_TOKEN); + + recordFieldNodes.add(createIncludedRecordParameterNode(createEmptyNodeList(), + createToken(ASTERISK_TOKEN), + createIdentifierToken("websocket:OAuth2RefreshTokenGrantConfig;"), null)); + + MetadataNode metadataNode = getMetadataNode("Refresh URL"); + TypeDescriptorNode stringType = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + IdentifierToken fieldNameTokenUrl = createIdentifierToken("refreshUrl"); + ExpressionNode defaultValue = createRequiredExpressionNode(createIdentifierToken("\"" + + refreshTokenUrl + "\"")); + RecordFieldWithDefaultValueNode fieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + metadataNode, null, stringType, fieldNameTokenUrl, equalToken, defaultValue, + semicolonToken); + recordFieldNodes.add(fieldNode); + return recordFieldNodes; + } + + + /** + * Generate Class variable for api key map {@code final readonly & ApiKeysConfig apiKeyConfig;}. + * + * @return {@link List} syntax tree object field node list + */ + public ObjectFieldNode getApiKeyMapClassVariable() { // return ObjectFieldNode + if (httpApiKey) { + NodeList qualifierList = createNodeList(createToken(FINAL_KEYWORD)); + TypeDescriptorNode readOnlyNode = createTypeReferenceTypeDescNode(createSimpleNameReferenceNode + (createToken(READONLY_KEYWORD))); + TypeDescriptorNode apiKeyMapNode = createSimpleNameReferenceNode(createIdentifierToken(API_KEYS_CONFIG)); + if (httpOROAuth) { + apiKeyMapNode = createOptionalTypeDescriptorNode(apiKeyMapNode, createToken(QUESTION_MARK_TOKEN)); + } + TypeDescriptorNode intersectionTypeDescriptorNode = createIntersectionTypeDescriptorNode(readOnlyNode, + createToken(BITWISE_AND_TOKEN), apiKeyMapNode); + IdentifierToken fieldName = createIdentifierToken(API_KEY_CONFIG); + MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); + return createObjectFieldNode(metadataNode, null, + qualifierList, intersectionTypeDescriptorNode, fieldName, null, null, + createToken(SEMICOLON_TOKEN)); + } + return null; + } + + /** + * Generate the config parameters of the client class init method. + * -- ex: Config param for Http and OAuth 2.0 Authentication mechanisms. + * {@code ClientConfig clientConfig, string serviceUrl = "https://asyncapi.com:443/v2" } + * -- ex: Config param for API Key Authentication mechanism. + * {@code ApiKeysConfig apiKeyConfig, http:ClientConfiguration clientConfig = {}, + * string serviceUrl = "https://asyncapi.com:443/v2" } + * Config param for API Key Authentication mechanism with no server URL given + * {@code ApiKeysConfig apiKeyConfig, string serviceUrl; http:ClientConfiguration clientConfig = {}} + * -- ex: Config param when no authentication mechanism given. + * {@code http:ClientConfiguration clientConfig = {}, + * string serviceUrl = "https://asyncapi.com:443/v2" } + * Config param when no authentication mechanism given with no server URL + * {@code string serviceUrl, http:ClientConfiguration clientConfig = {}} + * -- ex: Config param for combination of API Key and Http or OAuth 2.0 Authentication mechanisms. + * {@code AuthConfig authConfig,ConnectionConfig config = {}, + * string serviceUrl = "https://asyncapi.com:443/v2" } + */ + public void getConfigParamForClassInit(String serviceUrl, List parameters) { + + NodeList annotationNodes = createEmptyNodeList(); + Node serviceURLNode = getServiceURLNode(serviceUrl); + + + IdentifierToken equalToken = createIdentifierToken(GeneratorConstants.EQUAL); + if (httpOROAuth) { + BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(CONNECTION_CONFIG)); + IdentifierToken paramName = createIdentifierToken(CLIENT_CONFIG); + RequiredParameterNode authConfig = createRequiredParameterNode(annotationNodes, typeName, paramName); + parameters.add(authConfig); + parameters.add(createToken(COMMA_TOKEN)); + parameters.add(serviceURLNode); + } else { + if (httpApiKey) { + BuiltinSimpleNameReferenceNode apiKeyConfigTypeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(API_KEYS_CONFIG)); + IdentifierToken apiKeyConfigParamName = createIdentifierToken(API_KEY_CONFIG); + RequiredParameterNode apiKeyConfigParamNode = createRequiredParameterNode(annotationNodes, + apiKeyConfigTypeName, apiKeyConfigParamName); + parameters.add(apiKeyConfigParamNode); + parameters.add(createToken(COMMA_TOKEN)); + } + + BuiltinSimpleNameReferenceNode websocketClientConfigTypeName = createBuiltinSimpleNameReferenceNode( + null, createIdentifierToken(CONNECTION_CONFIG)); + IdentifierToken httpClientConfig = createIdentifierToken(CLIENT_CONFIG); + BasicLiteralNode emptyExpression = createBasicLiteralNode(null, createIdentifierToken(" {}")); + DefaultableParameterNode defaultConnectionConfig = createDefaultableParameterNode(annotationNodes, + websocketClientConfigTypeName, + httpClientConfig, equalToken, emptyExpression); + if (serviceURLNode instanceof RequiredParameterNode) { + parameters.add(serviceURLNode); + parameters.add(createToken(COMMA_TOKEN)); + parameters.add(defaultConnectionConfig); + } else { + parameters.add(defaultConnectionConfig); + parameters.add(createToken(COMMA_TOKEN)); + parameters.add(serviceURLNode); + } + } + + } + + + /** + * Generate function parameters. + */ + public void setFunctionParameters(AsyncApiChannelItem channelItem, List parameterList, Token comma, + AsyncApi25SchemaImpl querySchema, AsyncApi25SchemaImpl headerSchema) + throws BallerinaAsyncApiExceptionWs { + + AsyncApi25ParametersImpl parameters = (AsyncApi25ParametersImpl) channelItem.getParameters(); + AsyncApi25ChannelBindingsImpl bindings = (AsyncApi25ChannelBindingsImpl) channelItem.getBindings(); + if (bindings != null && bindings.getWs() == null) { + throw new BallerinaAsyncApiExceptionWs("This tool support only for websocket protocol,use ws bindings"); + } + + //Go through path Parameters + if (parameters != null) { + AsyncApi25SchemaImpl pathSchema = new AsyncApi25SchemaImpl(); + pathSchema.setType("object"); + pathSchema.setAdditionalProperties(new BooleanUnionValueImpl(false)); + List pathRequiredFields = new ArrayList<>(); + + List schemaDocs = new ArrayList<>(); + + String pathParamDescription = "Path parameters as a record"; + schemaDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc(pathParamDescription, true)); + for (String parameterName : parameters.getItemNames()) { + AsyncApiParameter parameter = parameters.getItem(parameterName); + String type = ((AsyncApi25SchemaImpl) parameter.getSchema()).getType(); + if (type != null && type.equals("array")) { + throw new BallerinaAsyncApiExceptionWs("Ballerina doesn't support array type path parameters"); + } + if (type != null && type.equals("object")) { + throw new BallerinaAsyncApiExceptionWs("Ballerina doesn't support record type path parameters"); + } + if (parameter.getDescription() != null && !parameter. + getDescription().isBlank()) { + MarkdownParameterDocumentationLineNode paramAPIDoc = + DocCommentsGenerator.createAPIParamDoc(getValidName( + parameterName, false), parameter.getDescription()); + schemaDocs.add(paramAPIDoc); + } + + pathSchema.addProperty(parameterName, parameter.getSchema()); + pathRequiredFields.add(parameterName); + } + pathSchema.setRequired(pathRequiredFields); + authRelatedTypeDefinitionNodes.add(ballerinaSchemaGenerator.getTypeDefinitionNode(pathSchema, + "PathParams", schemaDocs)); + BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken("PathParams")); + RequiredParameterNode pathParamNode = createRequiredParameterNode(createNodeList(), typeName, + createIdentifierToken("pathParams")); + isPathParam = true; +// utilGenerator.setPathParametersFound(true); + + parameterList.add(pathParamNode); + parameterList.add(comma); + } + + //Go through header parameters + if (bindings != null) { + AsyncApi25BindingImpl wsBindings = (AsyncApi25BindingImpl) bindings.getWs(); + if (wsBindings.getItem("headers") != null) { + JsonNode headers = wsBindings.getItem("headers"); + ObjectMapper objMapper = ConverterCommonUtils.callObjectMapper(); + + if (headers.get("properties") != null) { + Iterator> properties = headers.get("properties").fields(); + + headerSchema.setType("object"); + headerSchema.setAdditionalProperties(new BooleanUnionValueImpl(false)); + List headerRequiredFields = new ArrayList<>(); + List schemaDocs = new ArrayList<>(); + String headerParamDescription = "Header parameters as a record"; + schemaDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + headerParamDescription, true)); + for (Iterator> it = properties; it.hasNext(); ) { + Map.Entry field = it.next(); + String headerName = field.getKey(); + try { + BalAsyncApi25SchemaImpl schema = objMapper.treeToValue(field.getValue(), + BalAsyncApi25SchemaImpl.class); + String type = schema.getType(); + if (type != null && type.equals("array")) { + throw new BallerinaAsyncApiExceptionWs( + "Ballerina doesn't support array type header parameters"); + } + if (type != null && type.equals("object")) { + throw new BallerinaAsyncApiExceptionWs( + "Ballerina doesn't support record type header parameters"); + } +// if (schema.getDescription() != null && !schema. +// getDescription().isBlank()) { +// MarkdownParameterDocumentationLineNode paramAPIDoc = +// DocCommentsGenerator.createAPIParamDoc(getValidName( +// headerName, false), schema.getDescription()); +// schemaDocs.add(paramAPIDoc); +// } + + headerSchema.addProperty(headerName, schema); + headerRequiredFields.add(headerName); + + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + headerSchema.setRequired(headerRequiredFields); + authRelatedTypeDefinitionNodes.add(ballerinaSchemaGenerator.getTypeDefinitionNode(headerSchema, + "HeaderParams", schemaDocs)); + BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken("HeaderParams")); + RequiredParameterNode headerParamNode = createRequiredParameterNode(createNodeList(), typeName, + createIdentifierToken("headerParams")); + parameterList.add(headerParamNode); + parameterList.add(comma); + isHeaderParam = true; +// utilGenerator.setHeadersFound(true); + } + + + } + //Go through query parameters + if (wsBindings.getItem("query") != null) { + + ObjectNode query = (ObjectNode) wsBindings.getItem("query"); + ObjectMapper objMapper = ConverterCommonUtils.callObjectMapper(); + if (query.get("properties") != null) { + Iterator> properties = query.get("properties").fields(); + + querySchema.setType("object"); + querySchema.setAdditionalProperties(new BooleanUnionValueImpl(false)); + List queryRequiredFields = new ArrayList<>(); + List schemaDocs = new ArrayList<>(); + String queryParamDescription = "Query parameters as a record"; + schemaDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + queryParamDescription, true)); + for (Iterator> it = properties; it.hasNext(); ) { + Map.Entry field = it.next(); + String queryName = field.getKey(); + try { + BalAsyncApi25SchemaImpl schema = objMapper.treeToValue(field.getValue(), + BalAsyncApi25SchemaImpl.class); + String type = schema.getType(); + if (type != null && type.equals("array")) { + throw new BallerinaAsyncApiExceptionWs( + "Ballerina doesn't support array type query parameters"); + } + if (type != null && type.equals("object")) { + throw new BallerinaAsyncApiExceptionWs( + "Ballerina doesn't support record type query parameters"); + } +// if (schema.getDescription() != null && !schema. +// getDescription().isBlank()) { +// MarkdownParameterDocumentationLineNode paramAPIDoc = +// DocCommentsGenerator.createAPIParamDoc(getValidName( +// queryName, false), schema.getDescription()); +// schemaDocs.add(paramAPIDoc); +// } + querySchema.addProperty(queryName, schema); + queryRequiredFields.add(queryName); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + querySchema.setRequired(queryRequiredFields); + authRelatedTypeDefinitionNodes.add(ballerinaSchemaGenerator.getTypeDefinitionNode(querySchema, + "QueryParams", schemaDocs)); + BuiltinSimpleNameReferenceNode typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken("QueryParams")); + RequiredParameterNode queryParamNode = createRequiredParameterNode(createNodeList(), typeName, + createIdentifierToken(QUERY_PARAMS)); + + parameterList.add(queryParamNode); + parameterList.add(comma); + isQueryParam = true; +// utilGenerator.setQueryParamsFound(true); + + } + + } + } + } + + + /** + * Generate the serviceUrl parameters of the client class init method. + * + * @param serviceUrl service Url given in the AsyncAPI file + * @return {@link DefaultableParameterNode} when server URl is given in the AsyncAPI file + * {@link RequiredParameterNode} when server URL is not given in the AsyncAPI file + */ + private Node getServiceURLNode(String serviceUrl) { + Node serviceURLNode; + NodeList annotationNodes = createEmptyNodeList(); + BuiltinSimpleNameReferenceNode serviceURLType = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(STRING)); + IdentifierToken serviceURLVarName = createIdentifierToken(GeneratorConstants.SERVICE_URL); + + if (serviceUrl.equals("/")) { + serviceURLNode = createRequiredParameterNode(annotationNodes, serviceURLType, serviceURLVarName); + } else { + BasicLiteralNode expression = createBasicLiteralNode(STRING_LITERAL, + createIdentifierToken('"' + serviceUrl + '"')); + serviceURLNode = createDefaultableParameterNode(annotationNodes, serviceURLType, + serviceURLVarName, createIdentifierToken("="), expression); + } + return serviceURLNode; + } + + //TODO: Use this if want to use this in Choreo + + /** + * Generate `websocketClientConfig` variable. + *
+     *        websocket:ClientConfiguration websocketClientConfig = {
+     *             subProtocols: config.subProtocols,
+     *             customHeaders: config.customHeaders,
+     *             readTimeout: config.readTimeout,
+     *             writeTimeout: config.writeTimeout,
+     *             maxFrameSize: config.maxFrameSize,
+     *             webSocketCompressionEnabled: config.webSocketCompressionEnabled,
+     *             handShakeTimeout: config.handShakeTimeout,
+     *             validation: config.validation
+     *         };
+     * 
+ * + * @return + */ + public VariableDeclarationNode getWebsocketClientConfigVariableNode() { + Token comma = createToken(COMMA_TOKEN); + NodeList annotationNodes = createEmptyNodeList(); + // websocket:ClientConfiguration variable declaration + SimpleNameReferenceNode typeBindingPattern = createSimpleNameReferenceNode( + createIdentifierToken("websocket:ClientConfiguration")); + CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( + createIdentifierToken(CLIENT_CONFIG)); + TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, + bindingPattern); + + List argumentsList = new ArrayList<>(); + + if (isHttpOrOAuth() && !isHttpApiKey()) { + ExpressionNode authValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(AUTH))); + SpecificFieldNode authField = createSpecificFieldNode(null, + createIdentifierToken(AUTH), + createToken(COLON_TOKEN), authValExp); + argumentsList.add(authField); + argumentsList.add(comma); + } + + // create subProtocols field + ExpressionNode subProtocolsValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("subProtocols"))); + SpecificFieldNode subProtocolsField = createSpecificFieldNode(null, + createIdentifierToken("subProtocols"), + createToken(COLON_TOKEN), subProtocolsValExp); + argumentsList.add(subProtocolsField); + argumentsList.add(comma); + // create customHeaders field + ExpressionNode customHeadersValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken(CUSTOM_HEADERS))); + SpecificFieldNode customHeadersField = createSpecificFieldNode(null, + createIdentifierToken(CUSTOM_HEADERS), + createToken(COLON_TOKEN), customHeadersValExp); + argumentsList.add(customHeadersField); + argumentsList.add(comma); + + // create readTimeout field + ExpressionNode readTimeoutValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("readTimeout"))); + SpecificFieldNode readTimeoutField = createSpecificFieldNode(null, + createIdentifierToken("readTimeout"), + createToken(COLON_TOKEN), readTimeoutValExp); + argumentsList.add(readTimeoutField); + argumentsList.add(comma); + + // create writeTimeout field + ExpressionNode writeTimeoutValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("writeTimeout"))); + SpecificFieldNode writeTimeoutField = createSpecificFieldNode(null, + createIdentifierToken("writeTimeout"), + createToken(COLON_TOKEN), writeTimeoutValExp); + argumentsList.add(writeTimeoutField); + argumentsList.add(comma); + + // create maxFrameSize field + ExpressionNode maxFrameSizeValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("maxFrameSize"))); + SpecificFieldNode maxFrameSizeField = createSpecificFieldNode(null, + createIdentifierToken("maxFrameSize"), + createToken(COLON_TOKEN), maxFrameSizeValExp); + argumentsList.add(maxFrameSizeField); + argumentsList.add(comma); + + // create webSocketCompressionEnabled field + ExpressionNode webSocketCompressionEnabledValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken( + "webSocketCompressionEnabled"))); + SpecificFieldNode webSocketCompressionEnabledField = createSpecificFieldNode(null, + createIdentifierToken("webSocketCompressionEnabled"), + createToken(COLON_TOKEN), webSocketCompressionEnabledValExp); + argumentsList.add(webSocketCompressionEnabledField); + argumentsList.add(comma); + + // create handleShakeTimeout field + ExpressionNode handleShakeTimeoutValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("handleShakeTimeout"))); + SpecificFieldNode handleShakeTimeoutField = createSpecificFieldNode(null, + createIdentifierToken("handleShakeTimeout"), + createToken(COLON_TOKEN), handleShakeTimeoutValExp); + argumentsList.add(handleShakeTimeoutField); + argumentsList.add(comma); + + // create validation field + ExpressionNode validationValExp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("validation"))); + SpecificFieldNode validationField = createSpecificFieldNode(null, + createIdentifierToken("validation"), + createToken(COLON_TOKEN), validationValExp); + argumentsList.add(validationField); + + SeparatedNodeList arguments = createSeparatedNodeList(argumentsList); + MappingConstructorExpressionNode mappingConstructorExpressionNode = + createMappingConstructorExpressionNode(createToken(OPEN_BRACE_TOKEN), + arguments, createToken(CLOSE_BRACE_TOKEN)); + return createVariableDeclarationNode(annotationNodes, null, typedBindingPatternNode, + createToken(EQUAL_TOKEN), mappingConstructorExpressionNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * Generate http:client initialization node. + *
+     *     websocket:Client websocketEp = check new (serviceUrl, clientConfig);
+     * 
+ * + * @return {@link VariableDeclarationNode} Syntax tree node of client initialization + */ + public VariableDeclarationNode getClientInitializationNode(String url) { + + NodeList annotationNodes = createEmptyNodeList(); + // http:Client variable declaration + BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken("websocket:Client")); + CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( + createIdentifierToken("websocketEp")); + TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, + bindingPattern); + + // Expression node + List argumentsList = new ArrayList<>(); + PositionalArgumentNode positionalArgumentNode01 = createPositionalArgumentNode(createSimpleNameReferenceNode( + createIdentifierToken(url))); + argumentsList.add(positionalArgumentNode01); + Token comma1 = createIdentifierToken(","); + + PositionalArgumentNode positionalArgumentNode02 = createPositionalArgumentNode(createSimpleNameReferenceNode( + createIdentifierToken(CLIENT_CONFIG))); + argumentsList.add(comma1); + argumentsList.add(positionalArgumentNode02); + + SeparatedNodeList arguments = createSeparatedNodeList(argumentsList); + Token closeParenArg = createToken(CLOSE_PAREN_TOKEN); + ParenthesizedArgList parenthesizedArgList = createParenthesizedArgList(createToken(OPEN_PAREN_TOKEN), arguments, + closeParenArg); + ImplicitNewExpressionNode expressionNode = createImplicitNewExpressionNode(createToken(NEW_KEYWORD), + parenthesizedArgList); + CheckExpressionNode initializer = createCheckExpressionNode(null, createToken(CHECK_KEYWORD), + expressionNode); + return createVariableDeclarationNode(annotationNodes, + null, typedBindingPatternNode, createToken(EQUAL_TOKEN), initializer, + createToken(SEMICOLON_TOKEN)); + } + + /** + * Generate assignment nodes for api key map assignment {@code self.apiKeyConfig=apiKeyConfig.cloneReadOnly();}. + * + * @return {@link AssignmentStatementNode} syntax tree assignment statement node. + */ + public AssignmentStatementNode getApiKeyAssignmentNode() { + + if (httpApiKey) { + FieldAccessExpressionNode varRefApiKey = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG))); + ExpressionNode fieldAccessExpressionNode = createRequiredExpressionNode( + createIdentifierToken(API_KEY_CONFIG)); + ExpressionNode methodCallExpressionNode = createMethodCallExpressionNode( + fieldAccessExpressionNode, createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken("cloneReadOnly")), + createToken(OPEN_PAREN_TOKEN), createSeparatedNodeList(), createToken(CLOSE_PAREN_TOKEN)); + return createAssignmentStatementNode(varRefApiKey, + createToken(EQUAL_TOKEN), methodCallExpressionNode, createToken(SEMICOLON_TOKEN)); + } + return null; + } + + /** + * Returns fields in ClientConfig record. + * # Configurations related to client authentication + * websocket:BearerTokenConfig|websocket:OAuth2RefreshTokenGrantConfig auth; + * # Negotiable sub protocols of the client + * string[] subProtocols = []; + * # Custom headers, which should be sent to the server + * map customHeaders = {}; + * # Read timeout (in seconds) of the client + * decimal readTimeout = -1; + * # Write timeout (in seconds) of the client + * decimal writeTimeout = -1; + * # SSL/TLS-related options + * websocket:ClientSecureSocket? secureSocket = (); + * # The maximum payload size of a WebSocket frame in bytes + * int maxFrameSize = 65536; + * # Enable support for compression in the WebSocket + * boolean webSocketCompressionEnabled = true; + * # Time (in seconds) that a connection waits to get the response of the WebSocket handshake. + * decimal handShakeTimeout = 300; + * # An Array of http:Cookie + * http:Cookie[] cookies?; + * # A service to handle the ping/pong frames. + * PingPongService pingPongHandler?; + * # Configurations associated with retrying + * websocket:WebSocketRetryConfig retryConfig? = (); + * Enable/disable constraint validation + * boolean validation = true; + */ + private List getClientConfigRecordFields() { + + List recordFieldNodes = new ArrayList<>(); + Token semicolonToken = createToken(SEMICOLON_TOKEN); + Token equalToken = createToken(EQUAL_TOKEN); + Token questionMarkToken = createToken(QUESTION_MARK_TOKEN); + + // add auth field + if (isHttpOrOAuth() && !isHttpApiKey()) { + MetadataNode authMetadataNode = getMetadataNode("Configurations related to client authentication"); + IdentifierToken authFieldName = AbstractNodeFactory.createIdentifierToken(escapeIdentifier( + AUTH)); + TypeDescriptorNode authFieldTypeNode = + createSimpleNameReferenceNode(createIdentifierToken(getAuthFieldTypeName())); + RecordFieldNode authFieldNode = NodeFactory.createRecordFieldNode(authMetadataNode, null, + authFieldTypeNode, authFieldName, null, semicolonToken); + recordFieldNodes.add(authFieldNode); + } else if (isHttpOrOAuth() && isHttpApiKey()) { + MetadataNode authMetadataNode = getMetadataNode( + "Provides Auth configurations needed when communicating with a remote Websocket " + + "service endpoint."); + IdentifierToken authFieldName = AbstractNodeFactory.createIdentifierToken(escapeIdentifier( + AUTH)); + TypeDescriptorNode unionTypeDescriptor = createUnionTypeDescriptorNode( + createSimpleNameReferenceNode(createIdentifierToken(getAuthFieldTypeName())), + createToken(PIPE_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(API_KEYS_CONFIG))); + RecordFieldNode authFieldNode = NodeFactory.createRecordFieldNode(authMetadataNode, null, + unionTypeDescriptor, authFieldName, null, semicolonToken); + recordFieldNodes.add(authFieldNode); + } + + // add subProtocols field + MetadataNode subProtocolsMetadata = getMetadataNode("Negotiable sub protocols of the client"); + IdentifierToken subProtocolsFieldName = createIdentifierToken("subProtocols"); + NodeList arrayDimensions = NodeFactory.createEmptyNodeList(); + ArrayDimensionNode arrayDimension = NodeFactory.createArrayDimensionNode( + createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + arrayDimensions = arrayDimensions.add(arrayDimension); + TypeDescriptorNode subProtocolsMemberType = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + ArrayTypeDescriptorNode subProtocolsFieldType = createArrayTypeDescriptorNode(subProtocolsMemberType + , arrayDimensions); + RequiredExpressionNode subProtocolsExpression = + createRequiredExpressionNode(createIdentifierToken("[]")); + RecordFieldWithDefaultValueNode subProtocolsFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + subProtocolsMetadata, null, subProtocolsFieldType, subProtocolsFieldName, + equalToken, subProtocolsExpression, semicolonToken); + recordFieldNodes.add(subProtocolsFieldNode); + + // add customHeaders field + TypeDescriptorNode customHeadersMapParamType = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + TypeParameterNode customHeadersTypeParamsNode = createTypeParameterNode(createToken(LT_TOKEN), + customHeadersMapParamType, createToken(GT_TOKEN)); + MapTypeDescriptorNode customHeadersFieldType = createMapTypeDescriptorNode(createToken(MAP_KEYWORD), + customHeadersTypeParamsNode); + MetadataNode customHeadersMetadata = getMetadataNode("Custom headers, " + + "which should be sent to the server"); + IdentifierToken customHeadersFieldName = createIdentifierToken("customHeaders"); + RequiredExpressionNode customHeadersExpression = + createRequiredExpressionNode(createIdentifierToken("{}")); + RecordFieldWithDefaultValueNode customHeadersFieldNode = createRecordFieldWithDefaultValueNode( + customHeadersMetadata, null, customHeadersFieldType, customHeadersFieldName, + equalToken, customHeadersExpression, semicolonToken); + recordFieldNodes.add(customHeadersFieldNode); + + // add readTimeout field + MetadataNode readTimeOutMetadata = getMetadataNode("Read timeout (in seconds) of the client"); + TypeDescriptorNode readTimeOutFieldType = + createSimpleNameReferenceNode(createToken(DECIMAL_KEYWORD)); + IdentifierToken readTimeoutFieldName = createIdentifierToken("readTimeout"); + ExpressionNode readTimeOutDecimalLiteralNode = createRequiredExpressionNode(createIdentifierToken("-1")); + RecordFieldWithDefaultValueNode readTimeoutFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + readTimeOutMetadata, null, readTimeOutFieldType, readTimeoutFieldName, + equalToken, readTimeOutDecimalLiteralNode, semicolonToken); + recordFieldNodes.add(readTimeoutFieldNode); + + // add writeTimeout field + MetadataNode writeTimeOutMetadata = getMetadataNode("Write timeout (in seconds) of the client"); + TypeDescriptorNode writeTimeOutFieldType = + createSimpleNameReferenceNode(createToken(DECIMAL_KEYWORD)); + IdentifierToken writeTimeoutFieldName = createIdentifierToken("writeTimeout"); + ExpressionNode writeTimeOutDecimalLiteralNode = createRequiredExpressionNode(createIdentifierToken("-1")); + RecordFieldWithDefaultValueNode writeTimeoutFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + writeTimeOutMetadata, null, writeTimeOutFieldType, writeTimeoutFieldName, + equalToken, writeTimeOutDecimalLiteralNode, semicolonToken); + recordFieldNodes.add(writeTimeoutFieldNode); + + + // add secureSocket field + MetadataNode secureSocketMetadata = getMetadataNode("SSL/TLS-related options"); + IdentifierToken secureSocketFieldName = AbstractNodeFactory.createIdentifierToken(SECURE_SOCKET_FIELD); + TypeDescriptorNode secureSocketfieldType = createOptionalTypeDescriptorNode(createIdentifierToken( + "websocket:ClientSecureSocket"), questionMarkToken); + RecordFieldWithDefaultValueNode secureSocketFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + secureSocketMetadata, null, secureSocketfieldType, secureSocketFieldName, + equalToken, createRequiredExpressionNode(createIdentifierToken("()")), semicolonToken); + recordFieldNodes.add(secureSocketFieldNode); + + + // add maxFrameSize field + MetadataNode maxFrameSizeMetadata = getMetadataNode(" The maximum payload size of a WebSocket" + + " frame in bytes"); + TypeDescriptorNode maxFrameSizeFieldType = + createSimpleNameReferenceNode(createToken(INT_KEYWORD)); + IdentifierToken maxFrameSizeFieldName = createIdentifierToken("maxFrameSize"); + ExpressionNode maxFrameSizeDecimalLiteralNode = createRequiredExpressionNode( + createIdentifierToken("65536")); + RecordFieldWithDefaultValueNode maxFrameSizeFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + maxFrameSizeMetadata, null, maxFrameSizeFieldType, maxFrameSizeFieldName, + equalToken, maxFrameSizeDecimalLiteralNode, semicolonToken); + recordFieldNodes.add(maxFrameSizeFieldNode); + + // add webSocketCompressionEnabled field + MetadataNode webSocketCompressionEnabledMetadata = getMetadataNode("Enable support for compression in" + + " the WebSocket"); + TypeDescriptorNode webSocketCompressionEnabledFieldType = + createSimpleNameReferenceNode(createToken(BOOLEAN_KEYWORD)); + IdentifierToken webSocketCompressionEnabledFieldName = createIdentifierToken( + "webSocketCompressionEnabled"); + RecordFieldWithDefaultValueNode webSocketCompressionEnabledFieldNode = NodeFactory. + createRecordFieldWithDefaultValueNode( + webSocketCompressionEnabledMetadata, null, webSocketCompressionEnabledFieldType, + webSocketCompressionEnabledFieldName, + equalToken, createRequiredExpressionNode( + createToken(TRUE_KEYWORD)), semicolonToken); + recordFieldNodes.add(webSocketCompressionEnabledFieldNode); + + + // add handShakeTimeout field + MetadataNode handShakeTimeoutMetadata = getMetadataNode("Time (in seconds) that a connection waits to " + + "get the response of the WebSocket handshake"); + TypeDescriptorNode handShakeTimeoutFieldType = + createSimpleNameReferenceNode(createToken(DECIMAL_KEYWORD)); + IdentifierToken handShakeTimeoutFieldName = createIdentifierToken("handShakeTimeout"); + ExpressionNode handShakeTimeoutDecimalLiteralNode = createRequiredExpressionNode( + createIdentifierToken("300")); + RecordFieldWithDefaultValueNode handShakeTimeoutFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + handShakeTimeoutMetadata, null, handShakeTimeoutFieldType, handShakeTimeoutFieldName, + equalToken, handShakeTimeoutDecimalLiteralNode, semicolonToken); + recordFieldNodes.add(handShakeTimeoutFieldNode); + + + // add cookies field + MetadataNode cookiesMetadata = getMetadataNode("An Array of http:Cookie"); + IdentifierToken cookiesFieldName = createIdentifierToken("cookies"); + NodeList cookiesArrayDimensions = NodeFactory.createEmptyNodeList(); + ArrayDimensionNode cookiesArrayDimension = NodeFactory.createArrayDimensionNode( + createToken(SyntaxKind.OPEN_BRACKET_TOKEN), null, + createToken(SyntaxKind.CLOSE_BRACKET_TOKEN)); + cookiesArrayDimensions = cookiesArrayDimensions.add(cookiesArrayDimension); + TypeDescriptorNode cookiesArrayMemberType = createSimpleNameReferenceNode(createIdentifierToken + ("http:Cookie")); + ArrayTypeDescriptorNode cookiesFieldType = createArrayTypeDescriptorNode(cookiesArrayMemberType + , cookiesArrayDimensions); +// RequiredExpressionNode cookiesExpression = +// createRequiredExpressionNode(createIdentifierToken("[]")); + RecordFieldNode cookiesFieldNode = NodeFactory.createRecordFieldNode( + cookiesMetadata, null, cookiesFieldType, cookiesFieldName, + questionMarkToken, semicolonToken); + recordFieldNodes.add(cookiesFieldNode); + + + // add pingPongHandler field + MetadataNode pingPongHandlerMetadata = getMetadataNode("A service to handle the ping/pong frames"); + IdentifierToken pingPongHandlerFieldName = AbstractNodeFactory.createIdentifierToken(PING_PONG_SERVICE_FIELD); + TypeDescriptorNode pingPongHandlerFieldType = createSimpleNameReferenceNode( + createIdentifierToken("websocket:PingPongService")); + RecordFieldNode pingPongHandlerFieldNode = NodeFactory.createRecordFieldNode( + pingPongHandlerMetadata, null, pingPongHandlerFieldType, pingPongHandlerFieldName, + questionMarkToken, semicolonToken); + recordFieldNodes.add(pingPongHandlerFieldNode); + + // add retryConfig field + MetadataNode retryConfigMetadata = getMetadataNode("Configurations associated with retrying"); + IdentifierToken retryConfigFieldName = AbstractNodeFactory.createIdentifierToken("retryConfig"); + TypeDescriptorNode returConfigFieldType = createOptionalTypeDescriptorNode( + createIdentifierToken("websocket:WebSocketRetryConfig"), questionMarkToken); + RecordFieldWithDefaultValueNode retryConfigFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + retryConfigMetadata, null, returConfigFieldType, retryConfigFieldName, + equalToken, createRequiredExpressionNode(createIdentifierToken("()")), semicolonToken); + recordFieldNodes.add(retryConfigFieldNode); + + + // add validation field + MetadataNode validationMetadata = getMetadataNode("Enable/disable constraint validation"); + IdentifierToken validationFieldName = AbstractNodeFactory.createIdentifierToken(VALIDATION); + TypeDescriptorNode validationFieldType = createSimpleNameReferenceNode(createIdentifierToken(BOOLEAN)); + RecordFieldWithDefaultValueNode validateFieldNode = NodeFactory.createRecordFieldWithDefaultValueNode( + validationMetadata, null, validationFieldType, validationFieldName, + equalToken, createRequiredExpressionNode(createToken(TRUE_KEYWORD)), semicolonToken); + recordFieldNodes.add(validateFieldNode); + + return recordFieldNodes; + } + + /** + * Generate statements for init function when combination of ApiKeys and HTTP/OAuth authentication is used. + * + *
+     *     if config.auth is ApiKeysConfig {
+     *         self.apiKeyConfig = (config.auth).cloneReadOnly();
+     *     } else {
+     *         config.auth = config.auth;
+     *         self.apiKeyConfig = ();
+     *     }
+     * 
+ */ + public IfElseStatementNode handleInitForMixOfApiKeyAndHTTPOrOAuth() { + List apiKeyConfigAssignmentNodes = new ArrayList<>(); + + // `self.apiKeyConfig = (config.auth).cloneReadOnly();` + FieldAccessExpressionNode apiKeyConfigRef = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG))); + SimpleNameReferenceNode apiKeyConfigExpr = createSimpleNameReferenceNode(createIdentifierToken( + "(config.auth).cloneReadOnly()")); + AssignmentStatementNode apiKeyConfigAssignmentStatementNode = createAssignmentStatementNode(apiKeyConfigRef, + createToken(EQUAL_TOKEN), apiKeyConfigExpr, createToken(SEMICOLON_TOKEN)); + apiKeyConfigAssignmentNodes.add(apiKeyConfigAssignmentStatementNode); + NodeList statementList = createNodeList(apiKeyConfigAssignmentNodes); + BlockStatementNode ifBody = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), statementList, + createToken(CLOSE_BRACE_TOKEN)); + + List clientConfigAssignmentNodes = new ArrayList<>(); + + // config.auth = config.auth; + FieldAccessExpressionNode clientConfigAuthRef = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_CONFIG)), createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(AUTH))); + SimpleNameReferenceNode clientConfigExpr = createSimpleNameReferenceNode( + createIdentifierToken("<" + getAuthFieldTypeName() + + ">" + CLIENT_CONFIG + DOT_TOKEN.stringValue() + AUTH)); + AssignmentStatementNode httpClientAuthConfigAssignment = createAssignmentStatementNode(clientConfigAuthRef, + createToken(EQUAL_TOKEN), clientConfigExpr, createToken(SEMICOLON_TOKEN)); + clientConfigAssignmentNodes.add(httpClientAuthConfigAssignment); + + // `self.apiKeyConfig = ();` + FieldAccessExpressionNode apiKeyConfigNilRef = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), createToken(DOT_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(API_KEY_CONFIG))); + SimpleNameReferenceNode apiKeyConfigNilExpr = createSimpleNameReferenceNode( + createIdentifierToken("()")); + AssignmentStatementNode apiKeyConfigNilAssignment = createAssignmentStatementNode(apiKeyConfigNilRef, + createToken(EQUAL_TOKEN), apiKeyConfigNilExpr, createToken(SEMICOLON_TOKEN)); + clientConfigAssignmentNodes.add(apiKeyConfigNilAssignment); + + NodeList elseBodyNodeList = createNodeList(clientConfigAssignmentNodes); + StatementNode elseBodyStatement = createBlockStatementNode(createToken(OPEN_BRACE_TOKEN), elseBodyNodeList, + createToken(CLOSE_BRACE_TOKEN)); + ElseBlockNode elseBody = createElseBlockNode(createToken(ELSE_KEYWORD), elseBodyStatement); + + ExpressionNode condition = createBinaryExpressionNode(null, + createIdentifierToken(CLIENT_CONFIG + DOT_TOKEN.stringValue() + AUTH), + createToken(IS_KEYWORD), + createIdentifierToken(API_KEYS_CONFIG) + ); + return createIfElseStatementNode(createToken(IF_KEYWORD), condition, + ifBody, elseBody); + } + + + private MetadataNode getMetadataNode(String comment) { + + List docs = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc(comment, false)); + MarkdownDocumentationNode authDocumentationNode = createMarkdownDocumentationNode( + createNodeList(docs)); + return createMetadataNode(authDocumentationNode, createEmptyNodeList()); + } + + + /** + * Travers through the security schemas of the given async api spec. + * Store api key names which needs to send in the query string and as a request header separately. + * + * @param securitySchemeMap Map of security schemas of the given async api spec + */ + public void setAuthTypes(Map securitySchemeMap) throws + BallerinaAsyncApiExceptionWs { + + for (Map.Entry securitySchemeEntry : securitySchemeMap.entrySet()) { + AsyncApi25SecuritySchemeImpl securitySchemaValue = (AsyncApi25SecuritySchemeImpl) + securitySchemeEntry.getValue(); + if (securitySchemaValue != null && securitySchemaValue.getType() != null) { + String schemaType = securitySchemaValue.getType().toLowerCase(Locale.getDefault()); + + //TODO: Here apiKey and userPassword have to be map + switch (schemaType) { + case HTTP: + httpOROAuth = true; + String scheme = securitySchemaValue.getScheme(); + if (scheme.equals(BASIC)) { + authTypes.add(BASIC); + } else if (scheme.equals(BEARER)) { + authTypes.add(BEARER); + } + break; + case OAUTH2: + httpOROAuth = true; + if (securitySchemaValue.getFlows().getClientCredentials() != null) { + if (securitySchemaValue.getFlows().getClientCredentials().getTokenUrl() != null) { + clientCredGrantTokenUrl = securitySchemaValue.getFlows().getClientCredentials(). + getTokenUrl(); + } + authTypes.add(CLIENT_CRED); + } + if (securitySchemaValue.getFlows().getPassword() != null) { + if (securitySchemaValue.getFlows().getPassword().getTokenUrl() != null) { + + passwordGrantTokenUrl = securitySchemaValue.getFlows().getPassword().getTokenUrl(); + } + authTypes.add(PASSWORD); + } + if (securitySchemaValue.getFlows().getAuthorizationCode() != null) { + if (securitySchemaValue.getFlows().getAuthorizationCode().getTokenUrl() != null) { + refreshTokenUrl = securitySchemaValue.getFlows().getAuthorizationCode().getTokenUrl(); + } + authTypes.addAll(Arrays.asList(BEARER, REFRESH_TOKEN)); + } + if (securitySchemaValue.getFlows().getImplicit() != null) { + authTypes.add(BEARER); + } + break; + case HTTP_API_KEY: + httpApiKey = true; + String apiKeyType = securitySchemaValue.getIn().toLowerCase(Locale.getDefault()); + authTypes.add(HTTP_API_KEY); + setApiKeysConfigRecordFields(securitySchemaValue); + switch (apiKeyType) { + case "query": + queryApiKeyNameList.put(securitySchemeEntry.getKey(), securitySchemaValue.getName()); + break; + case "header": + headerApiKeyNameList.put(securitySchemeEntry.getKey(), securitySchemaValue.getName()); + break; + default: + break; + } + break; + + case USER_PASSWORD: + throw new BallerinaAsyncApiExceptionWs("userPassword type security schema doesn't support yet"); + case API_KEY: + throw new BallerinaAsyncApiExceptionWs("apiKey type security schema doesn't support yet"); + + + } + } + } + if (!(httpApiKey || httpOROAuth)) { + throw new BallerinaAsyncApiExceptionWs("Ballerina unsupported type of security schema"); + } + } + + /** + * Returns fields in ApiKeysConfig record. + *
+     *     # API key related to connector authentication
+     *     string apiKey;
+     * 
+ */ + private void setApiKeysConfigRecordFields(AsyncApi25SecuritySchemeImpl securityScheme) { + + MetadataNode metadataNode = null; + if (securityScheme.getDescription() != null) { +// List annotationNodes = Collections.singletonList(getDisplayAnnotationForPasswordField()); +// metadataNode = getMetadataNode(securityScheme.getDescription(), annotationNodes); + metadataNode = getMetadataNode(securityScheme.getDescription()); + + } + TypeDescriptorNode stringTypeDesc = createSimpleNameReferenceNode(createToken(STRING_KEYWORD)); + IdentifierToken apiKeyName = createIdentifierToken(getValidName(securityScheme.getName(), false)); + apiKeysConfigRecordFields.add(createRecordFieldNode(metadataNode, null, stringTypeDesc, + apiKeyName, null, createToken(SEMICOLON_TOKEN))); + } + + /** + * Travers through the authTypes and generate the field type name of auth field in ClientConfig record. + * + * @return {@link String} Field type name of auth field + * Ex: {@code http:BearerTokenConfig|http:OAuth2RefreshTokenGrantConfig} + */ + private String getAuthFieldTypeName() { + Set httpFieldTypeNames = new HashSet<>(); + for (String authType : authTypes) { + switch (authType) { + case BEARER: + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.BEARER.getValue()); + break; + case BASIC: + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.BASIC.getValue()); + break; + case CLIENT_CRED: + // Previous version of swagger parser returns null value, when it has an + // empty string as a value (ex: tokenURL: ""). Latest version `2.0.30` version + // returns empty string as it is. Therefore, we have to check both null check and empty string + // check. + if (clientCredGrantTokenUrl != null && !clientCredGrantTokenUrl.isBlank()) { + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CUSTOM_CLIENT_CREDENTIAL.getValue()); + } else { + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CLIENT_CREDENTIAL.getValue()); + } + break; + case PASSWORD: + if (passwordGrantTokenUrl != null && !passwordGrantTokenUrl.isBlank()) { + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CUSTOM_PASSWORD.getValue()); + } else { + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.PASSWORD.getValue()); + } + break; + case REFRESH_TOKEN: + if (refreshTokenUrl != null && !refreshTokenUrl.isBlank()) { + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.CUSTOM_REFRESH_TOKEN.getValue()); + } else { + httpFieldTypeNames.add(GeneratorConstants.AuthConfigTypes.REFRESH_TOKEN.getValue()); + } + break; + default: + break; + } + } + return buildConfigRecordFieldTypes(httpFieldTypeNames).toString(); + } + + /** + * This method is used concat the config record authConfig field type. + * + * @param fieldtypes Type name set from {@link #setAuthTypes(Map)} method. + * @return {@link String} Pipe concatenated list of type names + */ + private StringBuilder buildConfigRecordFieldTypes(Set fieldtypes) { + StringBuilder httpAuthFieldTypes = new StringBuilder(); + if (!fieldtypes.isEmpty()) { + for (String fieldType : fieldtypes) { + if (httpAuthFieldTypes.length() != 0) { + httpAuthFieldTypes.append("|").append(fieldType); + } else { + httpAuthFieldTypes.append(fieldType); + } + } + } + return httpAuthFieldTypes; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/CommonFunctionUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/CommonFunctionUtils.java new file mode 100644 index 000000000..e55a4f47d --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/CommonFunctionUtils.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; + +import java.util.List; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DISPATCHER_KEY_AND_DISPATCHER_STREAM_ID_MUST_BE_INSIDE_REQUIRED_PROPERTY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DISPATCHER_KEY_AND_DISPATCHER_STREAM_ID_MUST_BE_STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.INVALID_RESPONSE_SCHEMA; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.RESPONSE_TYPE_MUST_BE_A_RECORD; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SCHEMA_MUST_BE_A_RECORD; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_KEY; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.extractReferenceType; + +/** + * Common function utils for request and response. + * + */ +public class CommonFunctionUtils { + + private final AsyncApi25DocumentImpl asyncAPI; + + public CommonFunctionUtils(AsyncApi25DocumentImpl asyncAPI) { + this.asyncAPI = asyncAPI; + } + + /** + * Get return data type by traversing AsyncAPI schemas. + */ + public boolean isDispatcherPresent(String schemaName, AsyncApi25SchemaImpl schema, String dispatcherVal, + boolean isParent) throws BallerinaAsyncApiExceptionWs { + if (schema != null) { + if (schema.getProperties() != null) { +// type = getValidName(schemaName, true); + if (schema.getProperties().containsKey(dispatcherVal)) { + if (!((AsyncApi25SchemaImpl) schema.getProperties().get(dispatcherVal)).getType().equals(STRING)) { + throw new BallerinaAsyncApiExceptionWs(DISPATCHER_KEY_AND_DISPATCHER_STREAM_ID_MUST_BE_STRING); + } + if (schema.getRequired() == null || (!schema.getRequired().contains(dispatcherVal))) { + throw new BallerinaAsyncApiExceptionWs( + DISPATCHER_KEY_AND_DISPATCHER_STREAM_ID_MUST_BE_INSIDE_REQUIRED_PROPERTY); + } + return true; + } + } else if (schema.getOneOf() != null) { + List oneOfSchemas = schema.getOneOf(); + for (AsyncApiSchema oneOfSchema : oneOfSchemas) { + AsyncApi25SchemaImpl oneOf25Schema = (AsyncApi25SchemaImpl) oneOfSchema; + boolean oneOfContainProperties; + if (oneOf25Schema.get$ref() != null) { + String refSchemaName = extractReferenceType(oneOf25Schema.get$ref()); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) asyncAPI.getComponents(). + getSchemas().get( + refSchemaName); + oneOfContainProperties = isDispatcherPresent(refSchemaName, refSchema, dispatcherVal, false); + } else { + oneOfContainProperties = isDispatcherPresent("", oneOf25Schema, dispatcherVal, false); + } + if (!oneOfContainProperties && isParent) { + TextNode textNode = (TextNode) asyncAPI.getExtensions().get(X_DISPATCHER_KEY); + String dispatcherKey = textNode.asText(); + if (dispatcherVal.equals(dispatcherKey)) { + throw new BallerinaAsyncApiExceptionWs(String.format( + SCHEMA_MUST_BE_A_RECORD, schemaName)); + } + } + } + return true; + } else if (schema.getAllOf() != null) { + List allOfSchemas = schema.getAllOf(); + boolean allOfContainProperties; + for (Schema allOfSchema : allOfSchemas) { + AsyncApi25SchemaImpl allOf25Schema = (AsyncApi25SchemaImpl) allOfSchema; + if (allOf25Schema.get$ref() != null) { + String refSchemaName = extractReferenceType(allOf25Schema.get$ref()); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) asyncAPI.getComponents(). + getSchemas().get( + schemaName); + allOfContainProperties = isDispatcherPresent(refSchemaName, refSchema, dispatcherVal, + false); + } else { + allOfContainProperties = isDispatcherPresent("", allOf25Schema, + dispatcherVal, false); + } + if (allOfContainProperties) { + return true; + + } + } + TextNode textNode = (TextNode) asyncAPI.getExtensions().get(X_DISPATCHER_KEY); + String dispatcherKey = textNode.asText(); + if (dispatcherVal.equals(dispatcherKey)) { + throw new BallerinaAsyncApiExceptionWs(String.format( + SCHEMA_MUST_BE_A_RECORD, schemaName)); + } + } else if (!schema.getType().equals(GeneratorConstants.OBJECT)) { + throw new BallerinaAsyncApiExceptionWs(String.format( + RESPONSE_TYPE_MUST_BE_A_RECORD, + schema.getType(), schemaName)); + } else { + return false; + } + } else { + throw new BallerinaAsyncApiExceptionWs(INVALID_RESPONSE_SCHEMA); + } + return false; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/IntermediateClientGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/IntermediateClientGenerator.java new file mode 100644 index 000000000..ef913a6d8 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/IntermediateClientGenerator.java @@ -0,0 +1,1605 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.ServerVariable; +import io.apicurio.datamodels.models.asyncapi.AsyncApiChannelItem; +import io.apicurio.datamodels.models.asyncapi.AsyncApiMessage; +import io.apicurio.datamodels.models.asyncapi.AsyncApiOperation; +import io.apicurio.datamodels.models.asyncapi.AsyncApiServer; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25InfoImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25MessageImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ServerImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ServersImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.websocketscore.generators.document.DocCommentsGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; +import io.ballerina.compiler.syntax.tree.BinaryExpressionNode; +import io.ballerina.compiler.syntax.tree.BlockStatementNode; +import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; +import io.ballerina.compiler.syntax.tree.CheckExpressionNode; +import io.ballerina.compiler.syntax.tree.ClassDefinitionNode; +import io.ballerina.compiler.syntax.tree.ExpressionStatementNode; +import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionArgumentNode; +import io.ballerina.compiler.syntax.tree.FunctionBodyNode; +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.IfElseStatementNode; +import io.ballerina.compiler.syntax.tree.ImplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.LockStatementNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; +import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.MethodCallExpressionNode; +import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; +import io.ballerina.compiler.syntax.tree.ModulePartNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.ObjectFieldNode; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.ParenthesizedArgList; +import io.ballerina.compiler.syntax.tree.QualifiedNameReferenceNode; +import io.ballerina.compiler.syntax.tree.ReturnStatementNode; +import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.SpecificFieldNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TemplateExpressionNode; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; +import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; +import io.ballerina.tools.text.TextDocument; +import io.ballerina.tools.text.TextDocuments; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.API_KEY_CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ATTEMPT_CON_CLOSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ATTEMPT_TO_CLOSE_CONNECTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BALLERINA_WEBSOCKET_DOESNT_SUPPORT_FOR_MULTIPLE_CHANNELS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CAPITAL_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CHECK_PATH_FOR_QUERY_PARAM; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLIENT_CLASS_NAME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLIENT_CONFIG_CUSTOM_HEADERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLIENT_EP; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLOSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.COLON; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONFIG_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONNECTION_CLOSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONNECTION_CLOSE_STATEMENT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONNECTION_ERR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONSUME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CUSTOM_HEADERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DEFAULT_API_KEY_DESC; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DEFAULT_PIPE_TIME_OUT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DEFAULT_URL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DOT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DOT_TO_STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DOUBLE_QUOTE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.EQUAL_SPACE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.FAIL_TO_READ_ENDPOINT_DETAILS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.GET_COMBINE_HEADERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.HEADER_PARAM; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.HEADER_PARAMETERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.HEADER_PARAMS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.IMMEDIATE_CLOSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.INIT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.IS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.IS_ACTIVE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.LOG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.LOG_PRINT_ERR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MAP_ANY_DATA; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MAP_STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE_WITH_ID_VAR_CLONE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE_VAR_NAME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE_WITH_ID; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE_WITH_ID_VAR_NAME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MODIFIED_URL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.NOT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OBJECT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OPTIONAL_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OP_TIMEOUT_EXPR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PATH_PARAMETERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PATH_PARAMS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPES; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_COLON_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ERR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ERROR_NODE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_VAR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PLUS_SPACE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PRODUCE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.QUERY_PARAM; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.QUERY_PARAMETERS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.QUERY_PARAMS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.QUEUE_DEFAULT_SIZE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.READ_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.READ_MESSAGE_CLIENT_READ_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.READ_MESSAGE_PIPE_PRODUCE_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.READ_ONLY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.REF; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.REMOTE_METHOD_NAME_PREFIX; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.REMOVE_PIPES; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.REMOVE_STREAM_GENERATORS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.RETURN; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.RETURN_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SELF; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SELF_PIPES_GET_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SEMICOLON; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SERVICE_URL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SERVICE_URL_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SIMPLE_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SIMPLE_RPC; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SPACE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.START_MESSAGE_READING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.START_MESSAGE_READING_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.START_MESSAGE_WRITING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.START_MESSAGE_WRITING_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_GENERATORS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.S_DOT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.UUID; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WEBSOCKET; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WEBSOCKET_EP; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WRITE_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WRITE_MESSAGE_CLIENT_WRITE_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WRITE_MESSAGE_PIPE_CONSUME_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WRITE_MESSAGE_QUEUE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WSS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WS_ERR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WS_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WS_ERROR_OPTIONAL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.XLIBB_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_BALLERINA_INIT_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_BALLERINA_MESSAGE_READ_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_BALLERINA_MESSAGE_WRITE_DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_KEY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_KEY_CANNOT_BE_EMPTY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_KEY_MUST_INCLUDE_IN_THE_SPECIFICATION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_STREAM_ID; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_STREAM_ID_CANNOT_BE_EMPTY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_RESPONSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_RESPONSE_TYPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.escapeIdentifier; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.getValidName; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyMinutiaeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createLiteralValueToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createAssignmentStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBasicLiteralNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBinaryExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBlockStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBreakStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCaptureBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCheckExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createClassDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createContinueStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createElseBlockNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createExpressionStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldAccessExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldBindingPatternVarnameNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionBodyBlockNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionSignatureNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIfElseStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createImplicitNewExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createLockStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMappingConstructorExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationLineNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMethodCallExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createModulePartNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createNamedWorkerDeclarationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createObjectFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createParenthesizedArgList; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createPositionalArgumentNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createQualifiedNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSpecificFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTemplateExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypedBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createVariableDeclarationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createWhileStatementNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BACKTICK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BINARY_EXPRESSION; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BREAK_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CHECK_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLASS_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLIENT_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CONTINUE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.DOT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.DOUBLE_EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ELSE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EOF_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ERROR_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FALSE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FINAL_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_CALL; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_DEFINITION; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.IF_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ISOLATED_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.LOCK_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.NEW_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PLUS_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PRIVATE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.REMOTE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURNS_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURN_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RIGHT_ARROW_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.STRING_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TRUE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.VAR_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.WHILE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.WORKER_KEYWORD; + +/** + * This class is used to generate ballerina client file according to given yaml file. + * + */ +public class IntermediateClientGenerator { + + private final AsyncApi25DocumentImpl asyncApi; + private final List remoteFunctionNameList; + private final BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator; + private final List imports; + private final BallerinaTypesGenerator ballerinaSchemaGenerator; + private final RemoteFunctionReturnTypeGenerator functionReturnType; + private UtilGenerator utilGenerator; + private List typeDefinitionNodeList; + private List apiKeyNameList = new ArrayList<>(); + private String serverURL; + private String clientName = null; + private String dispatcherKey; + private String dispatcherStreamId; + + private static final Token openParenToken = createToken(OPEN_PAREN_TOKEN); + private static final Token closeParenToken = createToken(CLOSE_PAREN_TOKEN); + private static final Token openBraceToken = createToken(OPEN_BRACE_TOKEN); + private static final Token closeBraceToken = createToken(CLOSE_BRACE_TOKEN); + private static final Token semicolonToken = createToken(SEMICOLON_TOKEN); + private static final Token equalToken = createToken(EQUAL_TOKEN); + private static final Token dotToken = createToken(DOT_TOKEN); + private static final Token rightArrowToken = createToken(RIGHT_ARROW_TOKEN); + private static final Token colonToken = createToken(COLON_TOKEN); + private static final Token eofToken = createToken(EOF_TOKEN); + + public IntermediateClientGenerator(AasClientConfig asyncAPIClientConfig) { + + this.imports = new ArrayList<>(); + this.typeDefinitionNodeList = new ArrayList<>(); + this.asyncApi = asyncAPIClientConfig.getAsyncAPI(); + this.utilGenerator = null; + this.remoteFunctionNameList = new ArrayList<>(); + this.ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncApi, new LinkedList<>()); + this.serverURL = "/"; + this.ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator(false, false, ballerinaSchemaGenerator); + this.functionReturnType = new RemoteFunctionReturnTypeGenerator(this.asyncApi); + } + + private static ObjectFieldNode getObjectFieldNode(NodeList qualifiers, Node typeNode, + String fieldIdentifier) { + IdentifierToken fieldName = createIdentifierToken(fieldIdentifier); + MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); + return createObjectFieldNode(metadataNode, null, qualifiers, typeNode, fieldName, null, null, semicolonToken); + } + + public void setUtilGenerator(UtilGenerator utilGenerator) { + this.utilGenerator = utilGenerator; + } + + /** + * Returns a list of type definition nodes. + */ + public List getTypeDefinitionNodeList() { + return typeDefinitionNodeList; + } + + /** + * Returns ballerinaAuthConfigGenerator. + */ + public BallerinaAuthConfigGenerator getBallerinaAuthConfigGenerator() { + return ballerinaAuthConfigGenerator; + } + + //Get remote function name list to generate testing functions + public List getRemoteFunctionNameList() { + return remoteFunctionNameList; + } + + //Get clientName to generate testings + public String getClientName() { + return this.clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + /** + * Returns server URL. + * + * @return {@link String} + */ + public String getServerUrl() { + return serverURL; + } + + /** + * This method for generate the client syntax tree. + * + * @return return Syntax tree for the ballerina code. + * @throws BallerinaAsyncApiExceptionWs When function fail in process. + */ + public SyntaxTree generateSyntaxTree() throws BallerinaAsyncApiExceptionWs { + + // Create `ballerina/websocket` import declaration node, "ballerina/uuid will be imported only for streaming" + ImportDeclarationNode importForWebsocket = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA + , WEBSOCKET); + ImportDeclarationNode importForXlibbPipe = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.XLIBB + , XLIBB_PIPE); + ImportDeclarationNode importForLog = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA + , LOG); + + imports.add(importForLog); + imports.add(importForWebsocket); + imports.add(importForXlibbPipe); + + //TODO: This has to improve + // Add authentication related records + ballerinaAuthConfigGenerator.addAuthRelatedRecords(asyncApi); + + List nodes = new ArrayList<>(); + // Add class definition node to module member nodes + nodes.add(getClassDefinitionNode()); + + NodeList importsList = createNodeList(imports); + + + ModulePartNode modulePartNode = createModulePartNode(importsList, createNodeList(nodes), eofToken); + TextDocument textDocument = TextDocuments.from(""); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); + return syntaxTree.modifyWith(modulePartNode); + } + + public UtilGenerator getBallerinaUtilGenerator() { + return utilGenerator; + } + + + /** + * Generate Class definition Nodes. + */ + private ClassDefinitionNode getClassDefinitionNode() throws BallerinaAsyncApiExceptionWs { + + //Get dispatcherKey + Map extensions = asyncApi.getExtensions(); + + if (extensions == null || extensions.get(X_DISPATCHER_KEY) == null) { + throw new BallerinaAsyncApiExceptionWs(X_DISPATCHER_KEY_MUST_INCLUDE_IN_THE_SPECIFICATION); + } + TextNode dispatcherKeyNode = (TextNode) extensions.get(X_DISPATCHER_KEY); + + this.dispatcherKey = dispatcherKeyNode.asText(); + if (this.dispatcherKey.isEmpty()) { + throw new BallerinaAsyncApiExceptionWs(X_DISPATCHER_KEY_CANNOT_BE_EMPTY); + } + + //Get dispatcherStreamId + if (extensions.get(X_DISPATCHER_STREAM_ID) != null) { + TextNode dispatcherStreamIdNode = (TextNode) extensions.get(X_DISPATCHER_STREAM_ID); + if (dispatcherStreamIdNode != null) { + this.dispatcherStreamId = extensions.get(X_DISPATCHER_STREAM_ID).asText(); + if (this.dispatcherStreamId.isEmpty()) { + throw new BallerinaAsyncApiExceptionWs(X_DISPATCHER_STREAM_ID_CANNOT_BE_EMPTY); + } + } + } + + // Add Message and MessageWithId types to typeDefinitionNodeList + AsyncApi25SchemaImpl responseMessageSchema = createResponseMessage(this.dispatcherKey); + TypeDefinitionNode responseMessageTypeDefinitionNode = ballerinaSchemaGenerator.getTypeDefinitionNode + (responseMessageSchema, MESSAGE, new ArrayList<>()); + GeneratorUtils.updateTypeDefNodeList(MESSAGE, responseMessageTypeDefinitionNode, typeDefinitionNodeList); + + if (!Objects.isNull(this.dispatcherStreamId)) { + AsyncApi25SchemaImpl responseMessageWithIdSchema = createResponseMessageWithIDRecord( + this.dispatcherKey, this.dispatcherStreamId); + TypeDefinitionNode typeDefinitionNode = ballerinaSchemaGenerator.getTypeDefinitionNode + (responseMessageWithIdSchema, MESSAGE_WITH_ID, new ArrayList<>()); + GeneratorUtils.updateTypeDefNodeList(MESSAGE_WITH_ID, typeDefinitionNode, typeDefinitionNodeList); + } + + List pipeIdMethods = new ArrayList<>(); + ArrayList streamReturns = new ArrayList<>(); + List remoteFunctionNodes = createRemoteFunctions(streamReturns, pipeIdMethods); + + boolean isStreamPresent = !streamReturns.isEmpty(); + + List memberNodeList = new ArrayList<>(createClassInstanceVariables(isStreamPresent)); + + memberNodeList.add(createInitFunction(isStreamPresent)); + memberNodeList.add(createStartMessageWriting()); + memberNodeList.add(createStartMessageReading()); + memberNodeList.addAll(remoteFunctionNodes); + MetadataNode metadataNode = getClassMetadataNode(); + String titleName = asyncApi.getInfo().getTitle().trim().replaceAll("\\s", ""); + String channelName = GeneratorUtils.removeNonAlphanumeric(asyncApi.getChannels().getItemNames().get(0).trim()); + String stringClassName = titleName + channelName + CLIENT_CLASS_NAME; + + setClientName(stringClassName); + IdentifierToken className = createIdentifierToken(stringClassName); + NodeList classTypeQualifiers = createNodeList(createToken(CLIENT_KEYWORD), + createToken(ISOLATED_KEYWORD)); + + return createClassDefinitionNode(metadataNode, createToken(PUBLIC_KEYWORD), classTypeQualifiers, + createToken(CLASS_KEYWORD), className, openBraceToken, createNodeList(memberNodeList), + closeBraceToken, null); + } + + private Node createStartMessageReading() { + + //Create function signature node with metadata documentation + FunctionSignatureNode functionSignatureNode = getStartMessageReadingFunctionSignatureNode(); + + //Create function body node + FunctionBodyNode functionBodyNode = getStartMessageReadingFunctionBodyNode(); + + //Create function name + NodeList qualifierList = createNodeList(createToken(PRIVATE_KEYWORD), createToken(ISOLATED_KEYWORD)); + IdentifierToken functionName = createIdentifierToken(START_MESSAGE_READING); + + //Return function + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, + getDocCommentsForWorker(X_BALLERINA_MESSAGE_READ_DESCRIPTION, START_MESSAGE_READING_DESCRIPTION), + qualifierList, createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), + functionSignatureNode, functionBodyNode); + } + + private FunctionBodyNode getStartMessageReadingFunctionBodyNode() { + + List whileStatements = new ArrayList<>(); + whileStatements.add(getIsActiveCheck()); + + // Message|websocket:Error message = self.clientEp->readMessage(); + FieldAccessExpressionNode clientEp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_EP))); + MethodCallExpressionNode responseMessageExpressionNode = createMethodCallExpressionNode(clientEp, + rightArrowToken, createSimpleNameReferenceNode(createIdentifierToken(READ_MESSAGE)), openParenToken, + createSeparatedNodeList(createIdentifierToken(MESSAGE)), closeParenToken); + VariableDeclarationNode responseMessage = createVariableDeclarationNode(createEmptyNodeList(), + null, createTypedBindingPatternNode( + createUnionTypeDescriptorNode(createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(MESSAGE)), createToken(PIPE_TOKEN), WS_ERROR), + createFieldBindingPatternVarnameNode(createSimpleNameReferenceNode(createIdentifierToken( + MESSAGE_VAR_NAME)))), equalToken, responseMessageExpressionNode, semicolonToken); + + whileStatements.add(responseMessage); + whileStatements.add(getIsWsError(READ_MESSAGE_CLIENT_READ_ERROR, MESSAGE_VAR_NAME)); + + // pipe:Pipe pipe = self.pipes.getPipe(message.event); + String messageEventAccessor = String.format(SELF_PIPES_GET_PIPE, MESSAGE_VAR_NAME + DOT + + escapeIdentifier(this.dispatcherKey)); + if (Objects.isNull(this.dispatcherStreamId)) { + VariableDeclarationNode pipesVar = createVariableDeclarationNode(createEmptyNodeList(), null, + createTypedBindingPatternNode(NodeParser.parseTypeDescriptor(PIPE_COLON_PIPE), + createFieldBindingPatternVarnameNode(createSimpleNameReferenceNode( + createIdentifierToken(SIMPLE_PIPE)))), equalToken, + NodeParser.parseExpression(messageEventAccessor), semicolonToken); + whileStatements.add(pipesVar); + } else { + whileStatements.add(NodeParser.parseStatement(PIPE_VAR + SEMICOLON)); + whileStatements.add(NodeParser.parseStatement(MESSAGE_WITH_ID_VAR_CLONE)); + IfElseStatementNode pipeConditional = createIfElseStatementNode(createToken(IF_KEYWORD), + NodeParser.parseExpression(MESSAGE_WITH_ID_VAR_NAME + IS + MESSAGE_WITH_ID), + createBlockStatementNode(openBraceToken, createNodeList(NodeParser.parseStatement( + SIMPLE_PIPE + EQUAL_SPACE + String.format(SELF_PIPES_GET_PIPE, + MESSAGE_WITH_ID_VAR_NAME + DOT + escapeIdentifier(this.dispatcherStreamId)) + + SEMICOLON)), closeBraceToken), + createElseBlockNode(createToken(ELSE_KEYWORD), createBlockStatementNode(openBraceToken, + createNodeList(NodeParser.parseStatement(SIMPLE_PIPE + EQUAL_SPACE + + messageEventAccessor + SEMICOLON)), closeBraceToken))); + whileStatements.add(pipeConditional); + } + + // pipe:Error? pipeErr = pipe.produce(message, 5); + MethodCallExpressionNode produceExpression = createMethodCallExpressionNode(createBasicLiteralNode(VAR_KEYWORD, + createIdentifierToken(SIMPLE_PIPE)), dotToken, createSimpleNameReferenceNode( + createIdentifierToken(PRODUCE)), openParenToken, createSeparatedNodeList( + createPositionalArgumentNode(createRequiredExpressionNode(createIdentifierToken( + MESSAGE_VAR_NAME))), createToken(COMMA_TOKEN), + createPositionalArgumentNode(createRequiredExpressionNode(createIdentifierToken( + DEFAULT_PIPE_TIME_OUT)))), closeParenToken); + VariableDeclarationNode pipeErrVar = createVariableDeclarationNode(createEmptyNodeList(), null, + createTypedBindingPatternNode(createOptionalTypeDescriptorNode(PIPE_ERROR_NODE, + createToken(QUESTION_MARK_TOKEN)), createFieldBindingPatternVarnameNode( + createSimpleNameReferenceNode(createIdentifierToken(PIPE_ERR)))), + equalToken, produceExpression, semicolonToken); + + whileStatements.add(pipeErrVar); + whileStatements.add(getIsPipeError(PIPE_ERR, READ_MESSAGE_PIPE_PRODUCE_ERROR, false)); + + BlockStatementNode whileBody = createBlockStatementNode(openBraceToken, createNodeList(whileStatements), + closeBraceToken); + NodeList workerStatements = createNodeList(createWhileStatementNode(createToken(WHILE_KEYWORD), + createBasicLiteralNode(SyntaxKind.BOOLEAN_LITERAL, createToken(SyntaxKind.TRUE_KEYWORD)), whileBody, + null)); + + NodeList workerDeclarationNodes = createNodeList(createNamedWorkerDeclarationNode(createEmptyNodeList(), + null, createToken(WORKER_KEYWORD), createIdentifierToken(READ_MESSAGE), + null, createBlockStatementNode(openBraceToken, workerStatements, closeBraceToken), null)); + + return createFunctionBodyBlockNode(openBraceToken, null, workerDeclarationNodes, closeBraceToken, + null); + } + + private FunctionSignatureNode getStartMessageReadingFunctionSignatureNode() { + SeparatedNodeList parameterList = createSeparatedNodeList(new ArrayList<>()); + return createFunctionSignatureNode(openParenToken, parameterList, closeParenToken, null); + } + + private AsyncApi25SchemaImpl createResponseMessageWithIDRecord(String dispatcherKey, String dispatcherStreamId) { + //create MessageWithID record + AsyncApi25SchemaImpl responseMessageWithId = new AsyncApi25SchemaImpl(); + responseMessageWithId.setType(OBJECT); + AsyncApi25SchemaImpl stringEventSchema = new AsyncApi25SchemaImpl(); + AsyncApi25SchemaImpl stringIdSchema = new AsyncApi25SchemaImpl(); + stringEventSchema.setType(STRING); + stringIdSchema.setType(STRING); + List requiredFields = new ArrayList<>(); + requiredFields.add(dispatcherKey); + requiredFields.add(dispatcherStreamId); + responseMessageWithId.setRequired(requiredFields); + responseMessageWithId.addProperty(dispatcherKey, stringEventSchema); + responseMessageWithId.addProperty(dispatcherStreamId, stringIdSchema); + responseMessageWithId.addExtension(READ_ONLY, BooleanNode.TRUE); + return responseMessageWithId; + } + + private AsyncApi25SchemaImpl createResponseMessage(String dispatcherKey) { + //create Message record + AsyncApi25SchemaImpl message = new AsyncApi25SchemaImpl(); + message.setType(OBJECT); + AsyncApi25SchemaImpl stringEventSchema = new AsyncApi25SchemaImpl(); + AsyncApi25SchemaImpl stringIdSchema = new AsyncApi25SchemaImpl(); + stringEventSchema.setType(STRING); + stringIdSchema.setType(STRING); + List requiredFields = new ArrayList<>(); + requiredFields.add(dispatcherKey); + message.setRequired(requiredFields); + message.addProperty(dispatcherKey, stringEventSchema); + message.addExtension(READ_ONLY, BooleanNode.TRUE); + return message; + } + + private Node createStartMessageWriting() { + FunctionSignatureNode functionSignatureNode = getStartMessageWritingFunctionSignatureNode(); + FunctionBodyNode functionBodyNode = getStartMessageWritingFunctionBodyNode(); + NodeList qualifierList = createNodeList(createToken(PRIVATE_KEYWORD), createToken(ISOLATED_KEYWORD)); + IdentifierToken functionName = createIdentifierToken(START_MESSAGE_WRITING); + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, + getDocCommentsForWorker(X_BALLERINA_MESSAGE_WRITE_DESCRIPTION, START_MESSAGE_WRITING_DESCRIPTION), + qualifierList, createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), + functionSignatureNode, functionBodyNode); + } + + private FunctionBodyNode getStartMessageWritingFunctionBodyNode() { + NodeList annotations = createEmptyNodeList(); + + // anydata|pipe:Error requestMessage = self.writeMessageQueue.consume(5); + FieldAccessExpressionNode globalQueue = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(WRITE_MESSAGE_QUEUE))); + MethodCallExpressionNode consumeExpression = createMethodCallExpressionNode(globalQueue, dotToken, + createSimpleNameReferenceNode(createIdentifierToken(CONSUME)), openParenToken, + createSeparatedNodeList(createPositionalArgumentNode(createRequiredExpressionNode( + createIdentifierToken(DEFAULT_PIPE_TIME_OUT)))), closeParenToken); + VariableDeclarationNode queueData = createVariableDeclarationNode(createEmptyNodeList(), null, + createTypedBindingPatternNode(createUnionTypeDescriptorNode(createSimpleNameReferenceNode( + createIdentifierToken(MESSAGE)), createToken(PIPE_TOKEN), PIPE_ERROR_NODE), + createFieldBindingPatternVarnameNode(createSimpleNameReferenceNode(createIdentifierToken( + MESSAGE_VAR_NAME)))), equalToken, consumeExpression, semicolonToken); + + // self.clientEp->writeMessage(requestMessage); + FieldAccessExpressionNode clientEp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_EP))); + MethodCallExpressionNode writeMessageExpression = createMethodCallExpressionNode(clientEp, rightArrowToken, + createSimpleNameReferenceNode(createIdentifierToken(WRITE_MESSAGE)), openParenToken, + createSeparatedNodeList( + createPositionalArgumentNode(createRequiredExpressionNode( + createIdentifierToken(MESSAGE_VAR_NAME)))), closeParenToken); + VariableDeclarationNode writeMessage = createVariableDeclarationNode(createEmptyNodeList(), null, + createTypedBindingPatternNode(WS_ERROR_OPTIONAL, + createFieldBindingPatternVarnameNode(createSimpleNameReferenceNode( + createIdentifierToken(WS_ERR)))), equalToken, writeMessageExpression, semicolonToken); + + List whileStatements = new ArrayList<>(); + whileStatements.add(getIsActiveCheck()); + whileStatements.add(queueData); + whileStatements.add(getIsPipeError(MESSAGE_VAR_NAME, WRITE_MESSAGE_PIPE_CONSUME_ERROR, true)); + whileStatements.add(writeMessage); + whileStatements.add(getIsWsError(WRITE_MESSAGE_CLIENT_WRITE_ERROR, WS_ERR)); + + BlockStatementNode whileBody = createBlockStatementNode(openBraceToken, createNodeList(whileStatements), + closeBraceToken); + + NodeList workerStatements = createNodeList(createWhileStatementNode(createToken(WHILE_KEYWORD), + createBasicLiteralNode(SyntaxKind.BOOLEAN_LITERAL, createToken(SyntaxKind.TRUE_KEYWORD)), whileBody, + null)); + + NodeList workerDeclarationNodes = createNodeList(createNamedWorkerDeclarationNode( + annotations, null, createToken(WORKER_KEYWORD), createIdentifierToken(WRITE_MESSAGE), null, + createBlockStatementNode(openBraceToken, workerStatements, closeBraceToken), null)); + + return createFunctionBodyBlockNode(openBraceToken, null, workerDeclarationNodes, closeBraceToken, null); + } + + private static StatementNode getIsActiveCheck() { + // lock { + // if !self.isActive { + // break; + // } + // } + NodeList ifIsActiveNode = createNodeList(createIfElseStatementNode(createToken(IF_KEYWORD), + createSimpleNameReferenceNode(createIdentifierToken(NOT + SELF + DOT + IS_ACTIVE)), + createBlockStatementNode(openBraceToken, createNodeList(createBreakStatementNode( + createToken(BREAK_KEYWORD), semicolonToken)), closeBraceToken), null)); + return createLockStatementNode(createToken(LOCK_KEYWORD), + createBlockStatementNode(openBraceToken, ifIsActiveNode, closeBraceToken), null); + } + + private static IfElseStatementNode getIsPipeError(String errVar, String errorMessageTemplate, + boolean checkTimeout) { + // if requestMessage is pipe:Error { + // if (requestMessage.message() == "Operation has timed out") { + // continue; + // } + // log:printError("[writeMessage]PipeError: " + requestMessage.message()); + // self.attemptToCloseConnection(); + // return; + // } + ArrayList ifStatements = new ArrayList<>(); + if (checkTimeout) { + StatementNode continueStatementNode = createContinueStatementNode(createToken(CONTINUE_KEYWORD), + semicolonToken); + IfElseStatementNode ifTimeOutErrorNode = createIfElseStatementNode(createToken(IF_KEYWORD), + createBinaryExpressionNode(BINARY_EXPRESSION, createMethodCallExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(errVar)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(MESSAGE_VAR_NAME)), + openParenToken, createSeparatedNodeList(), closeParenToken), + createToken(DOUBLE_EQUAL_TOKEN), OP_TIMEOUT_EXPR), + createBlockStatementNode(openBraceToken, createNodeList(continueStatementNode), closeBraceToken), + null); + ifStatements.add(ifTimeOutErrorNode); + } + + StatementNode logPrintError = NodeParser.parseStatement(String.format(LOG_PRINT_ERR, + String.format(errorMessageTemplate, errVar))); + + ifStatements.add(logPrintError); + ifStatements.add(ATTEMPT_CON_CLOSE); + + ReturnStatementNode returnStatement = createReturnStatementNode(createToken(RETURN_KEYWORD), null, + semicolonToken); + + ifStatements.add(returnStatement); + return createIfElseStatementNode(createToken(IF_KEYWORD), + createSimpleNameReferenceNode(createIdentifierToken(errVar + IS + PIPE_ERROR_NODE)), + createBlockStatementNode(openBraceToken, createNodeList(ifStatements), closeBraceToken), null); + } + + private static IfElseStatementNode getIsWsError(String errMessageTemplate, String errVar) { + // if err is websocket:Error { + // log:printError("[writeMessage]WsError: " + err.message()); + // self.attemptToCloseConnection(); + // return; + // } + ArrayList ifStatements = new ArrayList<>(); + + StatementNode logPrintError = NodeParser.parseStatement(String.format(LOG_PRINT_ERR, + String.format(errMessageTemplate, errVar))); + + ifStatements.add(logPrintError); + + ifStatements.add(ATTEMPT_CON_CLOSE); + + ReturnStatementNode returnStatement = createReturnStatementNode(createToken(RETURN_KEYWORD), null, + semicolonToken); + + ifStatements.add(returnStatement); + + return createIfElseStatementNode(createToken(IF_KEYWORD), + createSimpleNameReferenceNode(createIdentifierToken(errVar + IS + WS_ERROR)), + createBlockStatementNode(openBraceToken, createNodeList(ifStatements), closeBraceToken), null); + } + + //TODO: Add metdata for the function + private FunctionSignatureNode getStartMessageWritingFunctionSignatureNode() { + SeparatedNodeList parameterList = createSeparatedNodeList(new ArrayList<>()); + return createFunctionSignatureNode(openParenToken, parameterList, closeParenToken, null); + } + + /** + * Generate metadata node of the class including documentation. Content of the documentation + * will be taken from the `description` section inside the `info` section in AsyncAPI definition. + * + * @return {@link MetadataNode} Metadata node of the client class + */ + private MetadataNode getClassMetadataNode() { + + List classLevelAnnotationNodes = new ArrayList<>(); + + // Generate api doc + List documentationLines = new ArrayList<>(); + if (asyncApi.getInfo().getDescription() != null && !asyncApi.getInfo().getDescription().isBlank()) { + documentationLines.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + asyncApi.getInfo().getDescription(), false)); + } + MarkdownDocumentationNode apiDoc = createMarkdownDocumentationNode(createNodeList(documentationLines)); + return createMetadataNode(apiDoc, createNodeList(classLevelAnnotationNodes)); + } + + + private FunctionDefinitionNode createInitFunction(boolean isStreamPresent) + throws BallerinaAsyncApiExceptionWs { + AsyncApi25SchemaImpl headerSchema = new AsyncApi25SchemaImpl(); + AsyncApi25SchemaImpl querySchema = new AsyncApi25SchemaImpl(); + FunctionSignatureNode functionSignatureNode = getInitFunctionSignatureNode(querySchema, headerSchema); + FunctionBodyNode functionBodyNode = getInitFunctionBodyNode(querySchema, headerSchema, isStreamPresent); + NodeList qualifierList = createNodeList(createToken(PUBLIC_KEYWORD), createToken(ISOLATED_KEYWORD)); + IdentifierToken functionName = createIdentifierToken(INIT); + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, getInitDocComment(), qualifierList, + createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), functionSignatureNode, + functionBodyNode); + } + + /** + * Create function body node of client init function. + * + * @return {@link FunctionBodyNode} + */ + private FunctionBodyNode getInitFunctionBodyNode(AsyncApi25SchemaImpl querySchema, + AsyncApi25SchemaImpl headerSchema, + boolean isStreamPresent) throws BallerinaAsyncApiExceptionWs { + List assignmentNodes = new ArrayList<>(); + + //TODO: Attempt to map auth configurations + // If both apiKey and httpOrOAuth is supported + // todo : After revamping + if (ballerinaAuthConfigGenerator.isHttpApiKey() && ballerinaAuthConfigGenerator.isHttpOrOAuth()) { + assignmentNodes.add(ballerinaAuthConfigGenerator.handleInitForMixOfApiKeyAndHTTPOrOAuth()); + } + + // self.pipes =new (); + List pipesArgumentsList = new ArrayList<>(); + SeparatedNodeList pipesArguments = createSeparatedNodeList(pipesArgumentsList); + ParenthesizedArgList pipesParenthesizedArgList = createParenthesizedArgList(openParenToken, pipesArguments, + closeParenToken); + ImplicitNewExpressionNode pipesExpressionNode = createImplicitNewExpressionNode(createToken(NEW_KEYWORD), + pipesParenthesizedArgList); + + FieldAccessExpressionNode selfPipes = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, createSimpleNameReferenceNode( + createIdentifierToken(PIPES))); + AssignmentStatementNode selfPipesAssignmentStatementNode = createAssignmentStatementNode(selfPipes, equalToken, + pipesExpressionNode, semicolonToken); + assignmentNodes.add(selfPipesAssignmentStatementNode); + + //TODO: use this as conditionally checking + // create {@code self.streamGenerators =new ();} assignment node + if (isStreamPresent) { + List streamGeneratorsArgumentsList = new ArrayList<>(); + SeparatedNodeList streamGeneratorsArguments = + createSeparatedNodeList(streamGeneratorsArgumentsList); + ParenthesizedArgList streamGeneratorsParenthesizedArgList = createParenthesizedArgList(openParenToken, + streamGeneratorsArguments, closeParenToken); + ImplicitNewExpressionNode streamGeneratorsExpressionNode = + createImplicitNewExpressionNode(createToken(NEW_KEYWORD), streamGeneratorsParenthesizedArgList); + + FieldAccessExpressionNode selfStreamGenerators = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(STREAM_GENERATORS))); + AssignmentStatementNode selfStreamGeneratorsAssignmentStatementNode = createAssignmentStatementNode( + selfStreamGenerators, equalToken, streamGeneratorsExpressionNode, semicolonToken); + assignmentNodes.add(selfStreamGeneratorsAssignmentStatementNode); + } + + // self.writeMessageQueue = new (1000); + List argumentsList = new ArrayList<>(); + FieldAccessExpressionNode selfWriteMessageQueues = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(WRITE_MESSAGE_QUEUE))); + argumentsList.add(createIdentifierToken(QUEUE_DEFAULT_SIZE)); + SeparatedNodeList arguments = createSeparatedNodeList(argumentsList); + ParenthesizedArgList parenthesizedArgList = createParenthesizedArgList(openParenToken, arguments, + closeParenToken); + ImplicitNewExpressionNode expressionNode = createImplicitNewExpressionNode(createToken(NEW_KEYWORD), + parenthesizedArgList); + + AssignmentStatementNode selfWriteQueueAssignmentStatementNode = createAssignmentStatementNode( + selfWriteMessageQueues, equalToken, expressionNode, semicolonToken); + assignmentNodes.add(selfWriteQueueAssignmentStatementNode); + + List channelList = asyncApi.getChannels().getItemNames(); + if (channelList.size() != 1) { + throw new BallerinaAsyncApiExceptionWs(BALLERINA_WEBSOCKET_DOESNT_SUPPORT_FOR_MULTIPLE_CHANNELS); + } + String path = channelList.get(0); + + if (!path.equals("/") || querySchema.getProperties() != null) { + if (!path.equals("/")) { + VariableDeclarationNode pathInt = getPathStatement(path); + assignmentNodes.add(pathInt); + handleParameterSchemaInOperation(querySchema, headerSchema, assignmentNodes, false); + } else { + handleParameterSchemaInOperation(querySchema, headerSchema, assignmentNodes, true); + } + assignmentNodes.add(ballerinaAuthConfigGenerator.getClientInitializationNode(MODIFIED_URL)); + } else { + assignmentNodes.add(ballerinaAuthConfigGenerator.getClientInitializationNode(SERVICE_URL)); + } + + // self.clientEp = websocketEp + FieldAccessExpressionNode selfClientEp = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(CLIENT_EP))); + SimpleNameReferenceNode selfClientEpValue = createSimpleNameReferenceNode(createIdentifierToken(WEBSOCKET_EP)); + AssignmentStatementNode selfWebsocketClientAssignmentStatementNode = createAssignmentStatementNode( + selfClientEp, equalToken, selfClientEpValue, semicolonToken); + assignmentNodes.add(selfWebsocketClientAssignmentStatementNode); + + //self.isActive = true; + ArrayList whileLoopBreakVariables = new ArrayList<>(); + whileLoopBreakVariables.add(IS_ACTIVE); + + for (String whileLoopBreakVariable : whileLoopBreakVariables) { + addInitsOfWhileLoopBreaksNodes(whileLoopBreakVariable, assignmentNodes, TRUE_KEYWORD.stringValue()); + } + + ArrayList workers = new ArrayList<>(); + workers.add(START_MESSAGE_WRITING); + workers.add(START_MESSAGE_READING); + + List workersArgumentsList = new ArrayList<>(); + SeparatedNodeList workersArguments = createSeparatedNodeList(workersArgumentsList); + for (String worker : workers) { + ExpressionStatementNode workerNode = createExpressionStatementNode(FUNCTION_CALL, + createMethodCallExpressionNode(createSimpleNameReferenceNode(createIdentifierToken(SELF)), + dotToken, createSimpleNameReferenceNode(createIdentifierToken(worker)), openParenToken, + workersArguments, closeParenToken), semicolonToken); + assignmentNodes.add(workerNode); + + } + + // Get API key assignment node if authentication mechanism type is only `apiKey` + if (ballerinaAuthConfigGenerator.isHttpApiKey() && !ballerinaAuthConfigGenerator.isHttpOrOAuth()) { + assignmentNodes.add(ballerinaAuthConfigGenerator.getApiKeyAssignmentNode()); + } + if (ballerinaAuthConfigGenerator.isHttpApiKey()) { + List apiKeyNames = new ArrayList<>(); + apiKeyNames.addAll(ballerinaAuthConfigGenerator.getHeaderApiKeyNameList().values()); + apiKeyNames.addAll(ballerinaAuthConfigGenerator.getQueryApiKeyNameList().values()); + setApiKeyNameList(apiKeyNames); + } + ReturnStatementNode returnStatementNode = createReturnStatementNode(createToken(RETURN_KEYWORD), null, + semicolonToken); + assignmentNodes.add(returnStatementNode); + NodeList statementList = createNodeList(assignmentNodes); + return createFunctionBodyBlockNode(openBraceToken, null, statementList, closeBraceToken, null); + } + + private void addInitsOfWhileLoopBreaksNodes(String initName, List assignmentNodes, + String booleanValue) { + SimpleNameReferenceNode selfIsMessageWritingValue = createSimpleNameReferenceNode(createIdentifierToken( + booleanValue)); + FieldAccessExpressionNode selfIsMessageWriting = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(initName))); + AssignmentStatementNode selfIsMessageWritingAssignmentStatementNode = + createAssignmentStatementNode(selfIsMessageWriting, equalToken, selfIsMessageWritingValue, + semicolonToken); + assignmentNodes.add(selfIsMessageWritingAssignmentStatementNode); + } + + /** + * Generate statements for query parameters and headers. + */ + private void handleParameterSchemaInOperation(AsyncApi25SchemaImpl querySchema, AsyncApi25SchemaImpl headerSchema, + List statementsList, boolean initalized) { + handleQueryParamsAndHeaders(querySchema, headerSchema, statementsList, initalized); + } + + /** + * Handle query parameters and headers within a remote function. + */ + public void handleQueryParamsAndHeaders(AsyncApi25SchemaImpl querySchema, AsyncApi25SchemaImpl headerSchema, + List statementsList, boolean initalized) { + if (querySchema.getProperties() != null) { + utilGenerator.setQueryParamsFound(true); + statementsList.add(getMapForParameters(querySchema, MAP_ANY_DATA, QUERY_PARAM)); + ExpressionStatementNode updatedPath; + if (initalized) { + updatedPath = GeneratorUtils.getSimpleExpressionStatementNode(STRING + SPACE + MODIFIED_URL + + EQUAL_SPACE + SERVICE_URL + PLUS_SPACE + CHECK_PATH_FOR_QUERY_PARAM); + } else { + updatedPath = GeneratorUtils.getSimpleExpressionStatementNode( + MODIFIED_URL + EQUAL_SPACE + MODIFIED_URL + PLUS_SPACE + CHECK_PATH_FOR_QUERY_PARAM); + } + statementsList.add(updatedPath); + } + if (headerSchema.getProperties() != null) { + statementsList.add(getMapForParameters(headerSchema, MAP_STRING, HEADER_PARAM)); + statementsList.add(GeneratorUtils.getSimpleExpressionStatementNode( + MAP_STRING + SPACE + CUSTOM_HEADERS + EQUAL_SPACE + GET_COMBINE_HEADERS)); + statementsList.add(GeneratorUtils.getSimpleExpressionStatementNode(CLIENT_CONFIG_CUSTOM_HEADERS + + EQUAL_SPACE + CUSTOM_HEADERS)); + utilGenerator.setHeadersFound(true); + } + } + + /** + * Generate map variable for query parameters and headers. + */ + private VariableDeclarationNode getMapForParameters(AsyncApi25SchemaImpl parameters, String mapDataType, + String mapName) { + List filedOfMap = new ArrayList<>(); + BuiltinSimpleNameReferenceNode mapType = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(mapDataType)); + CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode(createIdentifierToken(mapName)); + TypedBindingPatternNode bindingPatternNode = createTypedBindingPatternNode(mapType, bindingPattern); + Map properties = parameters.getProperties(); + for (Map.Entry entry : properties.entrySet()) { + // Initializer + IdentifierToken fieldName = createIdentifierToken(DOUBLE_QUOTE + (entry.getKey().trim()) + DOUBLE_QUOTE); + SimpleNameReferenceNode valueExpr = null; + if (((AsyncApi25SchemaImpl) entry.getValue()).getType().equals(STRING) || mapName.equals(QUERY_PARAM)) { + valueExpr = createSimpleNameReferenceNode( + createIdentifierToken(mapName + S_DOT + getValidName(entry.getKey().trim(), false))); + } else if (!((AsyncApi25SchemaImpl) entry.getValue()).getType().equals(STRING) && + mapName.equals(HEADER_PARAM)) { + valueExpr = createSimpleNameReferenceNode( + createIdentifierToken(mapName + S_DOT + getValidName(entry.getKey().trim(), false) + + DOT_TO_STRING)); + } + + SpecificFieldNode specificFieldNode = createSpecificFieldNode(null, + fieldName, colonToken, valueExpr); + filedOfMap.add(specificFieldNode); + filedOfMap.add(createToken(COMMA_TOKEN)); + } + + filedOfMap.remove(filedOfMap.size() - 1); + MappingConstructorExpressionNode initialize = createMappingConstructorExpressionNode(openBraceToken, + createSeparatedNodeList(filedOfMap), closeBraceToken); + return createVariableDeclarationNode(createEmptyNodeList(), null, bindingPatternNode, equalToken, + initialize, semicolonToken); + } + + /** + * This method use to generate Path statement inside the function body node. + * + * @param path - Given path + * @return - VariableDeclarationNode for path statement. + */ + private VariableDeclarationNode getPathStatement(String path) { + + TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(createSimpleNameReferenceNode( + createToken(STRING_KEYWORD)), createCaptureBindingPatternNode( + createIdentifierToken(MODIFIED_URL))); + // Create initializer + // Content should decide with /pet and /pet/{pet} by adding getEncodedUri + path = generatePathWithPathParameter(path); + //String path generator + NodeList content = createNodeList(createLiteralValueToken(null, path, createEmptyMinutiaeList(), + createEmptyMinutiaeList())); + SimpleNameReferenceNode lhsExpr = createSimpleNameReferenceNode(createIdentifierToken(SERVICE_URL)); + TemplateExpressionNode rhsExpr = createTemplateExpressionNode(null, createToken(STRING_KEYWORD), + createToken(BACKTICK_TOKEN), content, createToken(BACKTICK_TOKEN)); + BinaryExpressionNode initializer = createBinaryExpressionNode(null, lhsExpr, createToken(PLUS_TOKEN), + rhsExpr); + return createVariableDeclarationNode(createEmptyNodeList(), null, typedBindingPatternNode, equalToken, + initializer, semicolonToken); + } + + /** + * This method is to used for generating path when it has path parameters. + * + * @param path - yaml contract path + * @return string of path + */ + public String generatePathWithPathParameter(String path) { + if (path.contains("{")) { + String refinedPath = path; + Pattern p = Pattern.compile("\\{[^}]*}"); + Matcher m = p.matcher(path); + while (m.find()) { + String pathVariable = path.substring(m.start(), m.end()); + if (pathVariable.startsWith("{") && pathVariable.endsWith("}")) { + String d = pathVariable.replace("{", "").replace("}", ""); + String replaceVariable = "{getEncodedUri(" + "pathParams." + + GeneratorUtils.escapeIdentifier(d.trim()) + ")}"; + refinedPath = refinedPath.replace(pathVariable, replaceVariable); + } + } + path = refinedPath.replaceAll("[{]", "\\${"); + utilGenerator.setPathParametersFound(true); + } + return path; + } + + /** + * Create function signature node of client init function. + * + * @return {@link FunctionSignatureNode} + * @throws BallerinaAsyncApiExceptionWs When invalid server URL is provided + */ + private FunctionSignatureNode getInitFunctionSignatureNode( + AsyncApi25SchemaImpl querySchema, + AsyncApi25SchemaImpl headerSchema) + throws BallerinaAsyncApiExceptionWs { + //string serviceUrl = "ws://localhost:9090/payloadV" + serverURL = getServerURL((AsyncApi25ServersImpl) asyncApi.getServers()); + List parameters = new ArrayList<>(); + AsyncApiChannelItem channelItem = asyncApi.getChannels().getItems().get(0); + + //set pathParams,queryParams,headerParams + ballerinaAuthConfigGenerator.setFunctionParameters(channelItem, parameters, createToken(COMMA_TOKEN), + querySchema, headerSchema); + ballerinaAuthConfigGenerator.getConfigParamForClassInit(serverURL, parameters); + SeparatedNodeList parameterList = createSeparatedNodeList(parameters); + //error? + OptionalTypeDescriptorNode returnType = createOptionalTypeDescriptorNode(createToken(ERROR_KEYWORD), + createToken(QUESTION_MARK_TOKEN)); + //returns + ReturnTypeDescriptorNode returnTypeDescriptorNode = createReturnTypeDescriptorNode( + createToken(RETURNS_KEYWORD), createEmptyNodeList(), returnType); + return createFunctionSignatureNode(openParenToken, parameterList, closeParenToken, returnTypeDescriptorNode); + } + + /** + * Provide client class init function's documentation including function description and parameter descriptions. + * + * @return {@link MetadataNode} Metadata node containing entire function documentation comment. + */ + private MetadataNode getInitDocComment() { + List docs = new ArrayList<>(); + String clientInitDocComment = "Gets invoked to initialize the `connector`.\n"; + Map extensions = ((AsyncApi25InfoImpl) asyncApi.getInfo()).getExtensions(); + if (extensions != null && !extensions.isEmpty()) { + for (Map.Entry extension : extensions.entrySet()) { + if (extension.getKey().trim().equals(X_BALLERINA_INIT_DESCRIPTION)) { + clientInitDocComment = clientInitDocComment.concat(extension.getValue().toString()); + break; + } + } + } + + //todo: setInitDocComment() pass the references + + docs.addAll(DocCommentsGenerator.createAPIDescriptionDoc(clientInitDocComment, true)); + if (ballerinaAuthConfigGenerator.isHttpApiKey() && !ballerinaAuthConfigGenerator.isHttpOrOAuth()) { + MarkdownParameterDocumentationLineNode apiKeyConfig = DocCommentsGenerator.createAPIParamDoc( + API_KEY_CONFIG, DEFAULT_API_KEY_DESC); + docs.add(apiKeyConfig); + } + // Create method description + MarkdownParameterDocumentationLineNode clientConfig = DocCommentsGenerator.createAPIParamDoc(CONFIG, + CONFIG_DESCRIPTION); + docs.add(clientConfig); + MarkdownParameterDocumentationLineNode serviceUrlAPI = DocCommentsGenerator.createAPIParamDoc(SERVICE_URL, + SERVICE_URL_DESCRIPTION); + docs.add(serviceUrlAPI); + MarkdownParameterDocumentationLineNode returnDoc = DocCommentsGenerator.createAPIParamDoc(RETURN, + RETURN_DESCRIPTION); + docs.add(returnDoc); + + if (ballerinaAuthConfigGenerator.isPathParam()) { + MarkdownParameterDocumentationLineNode pathParamDocNode = DocCommentsGenerator.createAPIParamDoc( + PATH_PARAMS, PATH_PARAMETERS); + docs.add(pathParamDocNode); + } + if (ballerinaAuthConfigGenerator.isQueryParam()) { + MarkdownParameterDocumentationLineNode queryParamDocNode = DocCommentsGenerator.createAPIParamDoc( + QUERY_PARAMS, QUERY_PARAMETERS); + docs.add(queryParamDocNode); + } + if (ballerinaAuthConfigGenerator.isHeaderParam()) { + MarkdownParameterDocumentationLineNode headerParamDocNode = DocCommentsGenerator.createAPIParamDoc( + HEADER_PARAMS, HEADER_PARAMETERS); + docs.add(headerParamDocNode); + } + MarkdownDocumentationNode clientInitDoc = createMarkdownDocumentationNode(createNodeList(docs)); + return createMetadataNode(clientInitDoc, createEmptyNodeList()); + } + + /** + * Provide client class init function's documentation including function description and parameter descriptions. + * + * @return {@link MetadataNode} Metadata node containing entire function documentation comment. + */ + private MetadataNode getDocCommentsForWorker(String functionType, String comment) { + + List docs = new ArrayList<>(); + Map extensions = ((AsyncApi25InfoImpl) asyncApi.getInfo()).getExtensions(); + if (extensions != null && !extensions.isEmpty()) { + for (Map.Entry extension : extensions.entrySet()) { + if (extension.getKey().trim().equals(functionType)) { + comment = comment.concat(extension.getValue().toString()); + break; + } + } + } + //todo: setInitDocComment() pass the references + docs.addAll(DocCommentsGenerator.createAPIDescriptionDoc(comment, true)); + MarkdownDocumentationNode workerDoc = createMarkdownDocumentationNode(createNodeList(docs)); + return createMetadataNode(workerDoc, createEmptyNodeList()); + } + + /** + * Generate client class instance variables. + * + * @return {@link List} List of instance variables + */ + private List createClassInstanceVariables(boolean isStreamPresent) { + + List fieldNodeList = new ArrayList<>(); + Token privateKeywordToken = createToken(PRIVATE_KEYWORD); + Token finalKeywordToken = createToken(FINAL_KEYWORD); + ArrayList prefixTokensForPrivateAndFinal = new ArrayList<>(); + ArrayList prefixTokensForOnlyPrivate = new ArrayList<>(); + prefixTokensForPrivateAndFinal.add(privateKeywordToken); + prefixTokensForPrivateAndFinal.add(finalKeywordToken); + prefixTokensForOnlyPrivate.add(privateKeywordToken); + NodeList qualifiersWithPrivateAndFinal = createNodeList(prefixTokensForPrivateAndFinal); + NodeList qualifiersWithOnlyPrivate = createNodeList(prefixTokensForOnlyPrivate); + + //private final websocket:Client clientEp; + QualifiedNameReferenceNode websocketType = createQualifiedNameReferenceNode(createIdentifierToken(WEBSOCKET), + colonToken, createIdentifierToken(CLIENT_CLASS_NAME)); + + ObjectFieldNode websocketClientField = getObjectFieldNode(qualifiersWithPrivateAndFinal, websocketType, + CLIENT_EP); + + fieldNodeList.add(websocketClientField); + + QualifiedNameReferenceNode pipeType = createQualifiedNameReferenceNode(createIdentifierToken(SIMPLE_PIPE), + colonToken, createIdentifierToken(CAPITAL_PIPE)); + + //private final pipe:Pipe writeMessageQueue; + ObjectFieldNode writeMessageQueueClientField = getObjectFieldNode(qualifiersWithPrivateAndFinal, pipeType, + WRITE_MESSAGE_QUEUE); + fieldNodeList.add(writeMessageQueueClientField); + + //private final PipesMap pipes; + SimpleNameReferenceNode pipesType = createSimpleNameReferenceNode(createIdentifierToken( + GeneratorConstants.PIPES_MAP)); + ObjectFieldNode pipesField = getObjectFieldNode(qualifiersWithPrivateAndFinal, pipesType, PIPES); + fieldNodeList.add(pipesField); + + if (isStreamPresent) { + //private final StreamGeneratorsMap streamGenerators; + SimpleNameReferenceNode streamGeneratorsType = + createSimpleNameReferenceNode(createIdentifierToken(GeneratorConstants.STREAM_GENERATORS_MAP)); + ObjectFieldNode streamGeneratorsField = getObjectFieldNode(qualifiersWithPrivateAndFinal, + streamGeneratorsType, STREAM_GENERATORS); + fieldNodeList.add(streamGeneratorsField); + } + + SimpleNameReferenceNode booleanType = + createSimpleNameReferenceNode(createIdentifierToken(GeneratorConstants.BOOLEAN)); + //private boolean isActive; + ObjectFieldNode isActiveField = getObjectFieldNode(qualifiersWithOnlyPrivate, booleanType, IS_ACTIVE); + fieldNodeList.add(isActiveField); + + // add apiKey instance variable when API key security schema is given + ObjectFieldNode apiKeyFieldNode = ballerinaAuthConfigGenerator.getApiKeyMapClassVariable(); + if (apiKeyFieldNode != null) { + fieldNodeList.add(apiKeyFieldNode); + } + return fieldNodeList; + } + + /** + * Generate remote functions for AsyncAPI messages. + * + * @return FunctionDefinitionNodes list + * @throws BallerinaAsyncApiExceptionWs - throws when creating remote functions fails + */ + private List createRemoteFunctions(ArrayList streamReturns, + List pipeIdMethods) + throws BallerinaAsyncApiExceptionWs { + + Map messages = asyncApi.getComponents().getMessages(); + List functionDefinitionNodeList = new ArrayList<>(); + + // Create an array to store all request messages + ArrayList remainingResponseMessages = new ArrayList<>(); + + AsyncApiOperation publishOperation = asyncApi.getChannels().getItems().get(0).getPublish(); + + if (!Objects.isNull(publishOperation)) { + List publishMessages = getAsyncApiMessages(); + if (!publishMessages.isEmpty()) { + ListIterator requestMessages = publishMessages.listIterator(); + for (ListIterator it = requestMessages; it.hasNext();) { + AsyncApi25MessageImpl message = (AsyncApi25MessageImpl) it.next(); + String reference = message.get$ref(); + String messageName = GeneratorUtils.extractReferenceType(reference); + AsyncApi25MessageImpl componentMessage = (AsyncApi25MessageImpl) messages.get(messageName); + Map extensions = componentMessage.getExtensions(); + FunctionDefinitionNode functionDefinitionNode; + if (extensions != null && extensions.get(X_RESPONSE) != null) { + functionDefinitionNode = getRemoteFunctionDefinitionNode(messageName, componentMessage, + extensions, pipeIdMethods, remainingResponseMessages, false, streamReturns); + } else { + functionDefinitionNode = getRemoteFunctionDefinitionNode(messageName, componentMessage, null, + pipeIdMethods, null, false, null); + } + functionDefinitionNodeList.add(functionDefinitionNode); + } + } + } + //Set util generator with stream return classes + setUtilGenerator(new UtilGenerator(streamReturns)); + if (asyncApi.getChannels().getItems().get(0).getSubscribe() != null) { + List subscribeMessages = null; + if (asyncApi.getChannels().getItems().get(0).getSubscribe().getMessage().getOneOf() != null) { + subscribeMessages = asyncApi.getChannels().getItems().get(0).getSubscribe().getMessage().getOneOf(); + } else if (asyncApi.getChannels().getItems().get(0).getSubscribe().getMessage() != null) { + AsyncApiMessage asyncApiMessage = asyncApi.getChannels().getItems().get(0).getSubscribe().getMessage(); + List oneSubscribeMessage = new ArrayList<>(); + oneSubscribeMessage.add(asyncApiMessage); + subscribeMessages = oneSubscribeMessage; + } + if (subscribeMessages != null) { + ListIterator responseMessages = subscribeMessages.listIterator(); + for (ListIterator it = responseMessages; it.hasNext(); ) { + AsyncApi25MessageImpl message = (AsyncApi25MessageImpl) it.next(); + String reference = message.get$ref(); + String messageName = GeneratorUtils.extractReferenceType(reference); + if (!remainingResponseMessages.contains(messageName)) { + Map extensions = new LinkedHashMap<>(); + AsyncApi25MessageImpl newMessage = new AsyncApi25MessageImpl(); + ObjectNode objectNode = new ObjectNode(JsonNodeFactory.instance); + objectNode.put(REF, reference); + extensions.put(X_RESPONSE, objectNode); + newMessage.addExtension(X_RESPONSE, objectNode); + extensions.put(X_RESPONSE_TYPE, new TextNode(SIMPLE_RPC)); + newMessage.addExtension(X_RESPONSE_TYPE, new TextNode(SIMPLE_RPC)); + FunctionDefinitionNode functionDefinitionNode = getRemoteFunctionDefinitionNode(messageName, + newMessage, extensions, pipeIdMethods, null, true, streamReturns); + functionDefinitionNodeList.add(functionDefinitionNode); + } + } + } + } + functionDefinitionNodeList.add(createAttemptToCloseConnectionFunction()); + functionDefinitionNodeList.add(createConnectionCloseFunction(!streamReturns.isEmpty())); + return functionDefinitionNodeList; + } + + private List getAsyncApiMessages() { + List publishMessages = new ArrayList<>(); + if (asyncApi.getChannels().getItems().get(0).getPublish().getMessage().getOneOf() != null) { + publishMessages = asyncApi.getChannels().getItems().get(0).getPublish().getMessage().getOneOf(); + } else if (asyncApi.getChannels().getItems().get(0).getPublish().getMessage() != null) { + AsyncApiMessage asyncApiMessage = asyncApi.getChannels().getItems().get(0).getPublish().getMessage(); + List onePublishMessage = new ArrayList<>(); + onePublishMessage.add(asyncApiMessage); + publishMessages = onePublishMessage; + } + return publishMessages; + } + + private FunctionDefinitionNode createAttemptToCloseConnectionFunction() { + ArrayList statements = new ArrayList<>(); + + statements.add(NodeParser.parseStatement(CONNECTION_CLOSE_STATEMENT)); + statements.add(createIfElseStatementNode(createToken(IF_KEYWORD), + createSimpleNameReferenceNode(createIdentifierToken(CONNECTION_CLOSE + IS + ERROR)), + createBlockStatementNode(openBraceToken, createNodeList(NodeParser.parseStatement( + String.format(LOG_PRINT_ERR, CONNECTION_ERR))), closeBraceToken), null)); + + return createFunctionDefinitionNode(FUNCTION_DEFINITION, null, + createNodeList(createToken(ISOLATED_KEYWORD)), createToken(FUNCTION_KEYWORD), + createIdentifierToken(ATTEMPT_TO_CLOSE_CONNECTION), createEmptyNodeList(), + createFunctionSignatureNode(openParenToken, createSeparatedNodeList(), closeParenToken, + null), createFunctionBodyBlockNode(openBraceToken, null, + createNodeList(statements), closeBraceToken, null)); + } + + private FunctionDefinitionNode createConnectionCloseFunction(boolean streamsPresent) { + ArrayList lockStatements = new ArrayList<>(); + addInitsOfWhileLoopBreaksNodes(IS_ACTIVE, lockStatements, FALSE_KEYWORD.stringValue()); + + //check self.writeMessageQueue.immediateClose(); + ExpressionStatementNode writeMessageStatementNode = getCloseLockStatementNode(WRITE_MESSAGE_QUEUE, + IMMEDIATE_CLOSE, dotToken); + lockStatements.add(writeMessageStatementNode); + + //check self.pipes.removePipes(); + ExpressionStatementNode removePipesNode = getCloseLockStatementNode(PIPES, REMOVE_PIPES, dotToken); + lockStatements.add(removePipesNode); + + //TODO: conditionally check this one + if (streamsPresent) { + ExpressionStatementNode removeStreamGeneratorsNode = getCloseLockStatementNode(STREAM_GENERATORS, + REMOVE_STREAM_GENERATORS, dotToken); + lockStatements.add(removeStreamGeneratorsNode); + } + + ExpressionStatementNode clientCloseNode = getCloseLockStatementNode(CLIENT_EP, CLOSE, rightArrowToken); + lockStatements.add(clientCloseNode); + + LockStatementNode lockStatementNode = createLockStatementNode(createToken(LOCK_KEYWORD), + createBlockStatementNode(openBraceToken, createNodeList(lockStatements), closeBraceToken), null); + + IdentifierToken functionName = createIdentifierToken(CONNECTION_CLOSE); + return getAdditionalFunctionDefinitionNode(functionName, lockStatementNode); + + } + + private FunctionDefinitionNode getAdditionalFunctionDefinitionNode(IdentifierToken functionName, + LockStatementNode lockStatementNode) { + ReturnTypeDescriptorNode returnTypeDescriptorNode = createReturnTypeDescriptorNode(createToken(RETURNS_KEYWORD), + createNodeList(), createSimpleNameReferenceNode(createIdentifierToken(OPTIONAL_ERROR))); + FunctionSignatureNode functionSignatureNode = createFunctionSignatureNode(openParenToken, + createSeparatedNodeList(), closeParenToken, returnTypeDescriptorNode); + + FunctionBodyNode functionBodyNode = createFunctionBodyBlockNode(openBraceToken, null, + createNodeList(lockStatementNode), closeBraceToken, semicolonToken); + + MetadataNode metadataNode = createMetadataNode(null, createNodeList()); + NodeList qualifierList = createNodeList(createToken(REMOTE_KEYWORD), createToken(ISOLATED_KEYWORD)); + Token functionKeyWord = createToken(FUNCTION_KEYWORD); + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, + metadataNode, qualifierList, functionKeyWord, functionName, createEmptyNodeList(), + functionSignatureNode, functionBodyNode); + } + + private ExpressionStatementNode getCloseLockStatementNode(String messageQueue, String closeType, + Token divideToken) { + FieldAccessExpressionNode writeMessageQueue = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(messageQueue))); + CheckExpressionNode checkExpressionNode = createCheckExpressionNode(null, createToken(CHECK_KEYWORD), + createMethodCallExpressionNode(writeMessageQueue, divideToken, + createSimpleNameReferenceNode(createIdentifierToken(closeType)), openParenToken, + createSeparatedNodeList(), closeParenToken)); + return createExpressionStatementNode(null, checkExpressionNode, semicolonToken); + } + + /** + * Generate remote function definition node. + */ + private FunctionDefinitionNode getRemoteFunctionDefinitionNode(String messageName, + AsyncApi25MessageImpl messageValue, + Map extensions, + List pipeIdMethods, + ArrayList responseMessages, + boolean isSubscribe, List streamReturns) + throws BallerinaAsyncApiExceptionWs { + + String specDispatcherStreamId = this.dispatcherStreamId; + + Map schemas = asyncApi.getComponents().getSchemas(); + + // Create api doc for remote function + List remoteFunctionDocs = new ArrayList<>(); + + //Add documentation for remote function + if (messageValue.getSummary() != null) { + remoteFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc(messageValue.getSummary(), true)); + } else if (messageValue.getDescription() != null && !messageValue.getDescription().isBlank()) { + remoteFunctionDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + messageValue.getDescription(), true)); + } + + //Add remote function for test files + remoteFunctionNameList.add(messageName); + String responseType = null; + if (extensions != null) { + JsonNode xResponse = extensions.get(X_RESPONSE); + JsonNode xResponseType = extensions.get(X_RESPONSE_TYPE); + responseType = functionReturnType.getReturnType(xResponse, xResponseType, responseMessages); + } + + //Create remote function signature + RemoteFunctionSignatureGenerator remoteFunctionSignatureGenerator = new + RemoteFunctionSignatureGenerator(asyncApi, ballerinaSchemaGenerator, typeDefinitionNodeList); + + List remoteFunctionDocParameters = new ArrayList<>(); + FunctionSignatureNode functionSignatureNode = + remoteFunctionSignatureGenerator.getFunctionSignatureNode(messageValue.getPayload(), + remoteFunctionDocParameters, extensions, responseType, streamReturns); + if (!remoteFunctionDocParameters.isEmpty()) { + if (remoteFunctionDocs.isEmpty()) { + MarkdownDocumentationLineNode newLine = createMarkdownDocumentationLineNode(null, + createToken(SyntaxKind.HASH_TOKEN), createEmptyNodeList()); + remoteFunctionDocs.add(newLine); + } + remoteFunctionDocs.addAll(remoteFunctionDocParameters); + } + typeDefinitionNodeList = remoteFunctionSignatureGenerator.getTypeDefinitionNodeList(); + + // Create metadataNode add documentation string + MetadataNode metadataNode = createMetadataNode(createMarkdownDocumentationNode( + createNodeList(remoteFunctionDocs)), createNodeList()); + + // Create remote Function Body + String functionNameString = REMOTE_METHOD_NAME_PREFIX + getValidName(messageName, true); + RemoteFunctionBodyGenerator remoteFunctionBodyGenerator = new RemoteFunctionBodyGenerator(imports, + functionNameString); + boolean schemaDispatcherStreamIdContains = false; + if (messageValue.getPayload() != null) { + JsonNode jsonNode = messageValue.getPayload(); + TextNode textNode = (TextNode) jsonNode.get(REF); + String schemaName = GeneratorUtils.extractReferenceType(textNode.asText()); + AsyncApi25SchemaImpl schema = (AsyncApi25SchemaImpl) schemas.get(schemaName); + CommonFunctionUtils commonFunctionUtils = new CommonFunctionUtils(asyncApi); + schemaDispatcherStreamIdContains = commonFunctionUtils.isDispatcherPresent(schemaName, schema, + specDispatcherStreamId, true); + } + + //Check if the schema has dispatcherStreamId + if ((!Objects.isNull(specDispatcherStreamId) && !schemaDispatcherStreamIdContains)) { + //If no dispatcherStreamId found from the schema + specDispatcherStreamId = null; + //Check if the schema has dispatcherStreamId + } else if (!Objects.isNull(specDispatcherStreamId)) { + //If found at least one dispatcherStreamId then don't add uuid again and again + pipeIdMethods.add(messageName); + ImportDeclarationNode importForUUID = GeneratorUtils. + getImportDeclarationNode(GeneratorConstants.BALLERINA, UUID); + if (pipeIdMethods.size() == 1) { + // TODO: Add this after generated-stream-id flag implementation +// imports.add(importForUUID); + } + } + + String requestTypeCamelCaseName = Character.toLowerCase(messageName.charAt(0)) + messageName.substring(1); + FunctionBodyNode functionBodyNode = remoteFunctionBodyGenerator.getFunctionBodyNode(extensions, + requestTypeCamelCaseName, specDispatcherStreamId, isSubscribe, responseType); + + //Create remote function details + NodeList qualifierList = createNodeList(createToken(REMOTE_KEYWORD), createToken(ISOLATED_KEYWORD)); + Token functionKeyWord = createToken(FUNCTION_KEYWORD); + IdentifierToken functionName = createIdentifierToken(functionNameString); + + //Create whole remote function + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, metadataNode, qualifierList, + functionKeyWord, functionName, createEmptyNodeList(), functionSignatureNode, functionBodyNode); + } + + /** + * Generate serverUrl for client default value. + */ + private String getServerURL(AsyncApi25ServersImpl servers) throws BallerinaAsyncApiExceptionWs { + String serverURL; + if (!Objects.isNull(servers)) { + List serversList = servers.getItems(); + AsyncApi25ServerImpl selectedServer = (AsyncApi25ServerImpl) serversList.get(0); + if (!selectedServer.getUrl().startsWith(WSS + COLON) && servers.getItems().size() > 1) { + for (AsyncApiServer server : serversList) { + if (server.getUrl().startsWith(WSS + COLON)) { + selectedServer = (AsyncApi25ServerImpl) server; + break; + } + } + } + if (selectedServer.getUrl() == null) { + serverURL = DEFAULT_URL; + } else if (selectedServer.getVariables() != null) { + Map variables = selectedServer.getVariables(); + String resolvedUrl = GeneratorUtils.buildUrl(selectedServer.getUrl(), variables); + try { + new URI(resolvedUrl); + } catch (URISyntaxException e) { + throw new BallerinaAsyncApiExceptionWs(FAIL_TO_READ_ENDPOINT_DETAILS + selectedServer.getUrl(), e); + } + serverURL = resolvedUrl; + } else { + serverURL = selectedServer.getUrl(); + } + return serverURL; + } else { + serverURL = "/"; + return serverURL; + } + } + + /** + * Provide list of the field names in ApiKeysConfig record to generate the Config.toml file. + * + * @return {@link List} + */ + public List getApiKeyNameList() { + return apiKeyNameList; + } + + /** + * Set the `apiKeyNameList` by adding the Api Key names available under security schemas. + * + * @param apiKeyNameList {@link List} + */ + public void setApiKeyNameList(List apiKeyNameList) { + this.apiKeyNameList = Collections.unmodifiableList(apiKeyNameList); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionBodyGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionBodyGenerator.java new file mode 100644 index 000000000..1264ca129 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionBodyGenerator.java @@ -0,0 +1,467 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; +import io.ballerina.compiler.syntax.tree.ExpressionStatementNode; +import io.ballerina.compiler.syntax.tree.FieldAccessExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionBodyNode; +import io.ballerina.compiler.syntax.tree.ImplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.LockStatementNode; +import io.ballerina.compiler.syntax.tree.MethodCallExpressionNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.ReturnStatementNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.StreamTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.StreamTypeParamsNode; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.VariableDeclarationNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ATTEMPT_CON_CLOSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLONE_WITH_TYPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONNECTION_CLOSED_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONSUME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONSUMING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CREATE_UUID_STATEMENT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DATABINDING_ERR_TEMPLATE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DOT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ERROR_PIPE_CLOSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.IS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.IS_ACTIVE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.LOG_PRINT_DEBUG_TEMPLATE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE_VAR_NAME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.NOT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPES; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_CLOSE_STATEMENT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ERR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ERROR_NODE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ERR_CAPITAL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ERR_TEMPLATE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PRODUCE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PRODUCING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.RESPONSE_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.RETURN; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SELF; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SELF_PIPES_GET_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SERVER_STREAMING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_GENERATOR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_GENERATOR_CAPITAL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.TIMEOUT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WITHIN_PAREN_TEMPLATE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WRITE_MESSAGE_QUEUE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_RESPONSE_TYPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.escapeIdentifier; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createAssignmentStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBlockStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCaptureBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createErrorConstructorExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createExpressionStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldAccessExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFieldBindingPatternVarnameNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionBodyBlockNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIfElseStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createImplicitNewExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createLockStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMethodCallExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createParenthesizedArgList; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createPositionalArgumentNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createStreamTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createStreamTypeParamsNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypedBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createVariableDeclarationNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.DOT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ERROR_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.GT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.IF_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.LOCK_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.LT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.NEW_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURN_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.STREAM_KEYWORD; + +/** + * This Util class uses for generating remote function body {@link FunctionBodyNode}. + * + */ +public class RemoteFunctionBodyGenerator { + + private final List imports; + private final String functionName; + private static final Token openParenToken = createToken(OPEN_PAREN_TOKEN); + private static final Token closeParenToken = createToken(CLOSE_PAREN_TOKEN); + private static final Token openBraceToken = createToken(OPEN_BRACE_TOKEN); + private static final Token closeBraceToken = createToken(CLOSE_BRACE_TOKEN); + private static final Token semicolonToken = createToken(SEMICOLON_TOKEN); + private static final Token equalToken = createToken(EQUAL_TOKEN); + private static final Token dotToken = createToken(DOT_TOKEN); + + public RemoteFunctionBodyGenerator(List imports, String functionName) { + this.imports = Collections.unmodifiableList(imports); + this.functionName = functionName; + } + + private void addProduceStatementForWriteMessageQueue(List statementsList, String requestType, + boolean isSubscribe) { + if (!isSubscribe) { + SimpleNameReferenceNode requestTypeNameNode = + createSimpleNameReferenceNode(createIdentifierToken(requestType)); + VariableDeclarationNode messageVariableDeclarationNode = + createVariableDeclarationNode(createEmptyNodeList(), null, + createTypedBindingPatternNode(NodeParser.parseTypeDescriptor(MESSAGE + PIPE + ERROR), + createCaptureBindingPatternNode(createIdentifierToken(MESSAGE_VAR_NAME))), + equalToken, createMethodCallExpressionNode(requestTypeNameNode, dotToken, + createSimpleNameReferenceNode(createIdentifierToken(CLONE_WITH_TYPE)), + openParenToken, createSeparatedNodeList(), closeParenToken), semicolonToken); + // Message|error message = subscribe.cloneWithType(); + statementsList.add(messageVariableDeclarationNode); + statementsList.add(getCloningMessageError(MESSAGE_VAR_NAME)); + statementsList.addAll(getProduceToWriteMessageQueueVar()); + } + } + + private List getProduceToWriteMessageQueueVar() { + // pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + List statements = new ArrayList<>(); + List arguments = new ArrayList<>(); + arguments.add(createSimpleNameReferenceNode(createIdentifierToken(MESSAGE_VAR_NAME))); + arguments.add(createToken(COMMA_TOKEN)); + arguments.add(createPositionalArgumentNode(createRequiredExpressionNode(createIdentifierToken(TIMEOUT)))); + FieldAccessExpressionNode globalQueue = createFieldAccessExpressionNode( + createSimpleNameReferenceNode(createIdentifierToken(SELF)), dotToken, + createSimpleNameReferenceNode(createIdentifierToken(WRITE_MESSAGE_QUEUE))); + MethodCallExpressionNode callGlobalQueueProduce = + createMethodCallExpressionNode(globalQueue, dotToken, createSimpleNameReferenceNode( + createIdentifierToken(PRODUCE)), openParenToken, createSeparatedNodeList(arguments), + closeParenToken); + statements.add(createVariableDeclarationNode(createEmptyNodeList(), + null, createTypedBindingPatternNode(createOptionalTypeDescriptorNode(PIPE_ERROR_NODE, + createToken(QUESTION_MARK_TOKEN)), createFieldBindingPatternVarnameNode( + createSimpleNameReferenceNode(createIdentifierToken(PIPE_ERR)))), equalToken, + callGlobalQueueProduce, semicolonToken)); + statements.add(getPipeError(PIPE_ERR, PRODUCING)); + return statements; + } + + private StatementNode getCloningMessageError(String varName) { + return createIfElseStatementNode(createToken(IF_KEYWORD), + NodeParser.parseExpression(varName + IS + ERROR), + createBlockStatementNode(openBraceToken, + createNodeList(ATTEMPT_CON_CLOSE, createReturnStatementNode( + createToken(RETURN_KEYWORD), createErrorConstructorExpressionNode( + createToken(ERROR_KEYWORD), null, openParenToken, + createSeparatedNodeList(createIdentifierToken(String.format( + DATABINDING_ERR_TEMPLATE)), createToken(COMMA_TOKEN), + createIdentifierToken(varName)), + closeParenToken), semicolonToken)), closeBraceToken), null); + } + + private StatementNode getPipeError(String errVar, String activity) { + return createIfElseStatementNode(createToken(IF_KEYWORD), + NodeParser.parseExpression(errVar + IS + PIPE_ERROR_NODE), + createBlockStatementNode(openBraceToken, + createNodeList(ATTEMPT_CON_CLOSE, createReturnStatementNode(createToken(RETURN_KEYWORD), + createErrorConstructorExpressionNode(createToken(ERROR_KEYWORD), null, + openParenToken, createSeparatedNodeList(createIdentifierToken(String.format( + PIPE_ERR_TEMPLATE, activity)), createToken(COMMA_TOKEN), + createIdentifierToken(errVar)), + closeParenToken), semicolonToken)), closeBraceToken), null); + } + + public List getImports() { + return imports; + } + + /** + * Generate function body node for the remote function. + *

+ * // * @param path - remote function path + * // * @param operation - asyncapi operation + * + * @return - {@link FunctionBodyNode} + */ + public FunctionBodyNode getFunctionBodyNode(Map extensions, String requestType, + String specDispatcherStreamId, boolean isSubscribe, + String responseType) { + // Create statements + List statementsList = new ArrayList<>(); + // This return type for target data type binding. + if (extensions != null) { + JsonNode xResponseType = extensions.get(X_RESPONSE_TYPE); + if (xResponseType != null && xResponseType.equals(new TextNode(SERVER_STREAMING))) { + //TODO: Include an if condition to check this only one time + createStreamFunctionBodyStatements(statementsList, requestType, responseType, specDispatcherStreamId, + isSubscribe); + } else { + createSimpleRPCFunctionBodyStatements(statementsList, requestType, responseType, specDispatcherStreamId, + isSubscribe); + } + } else { + createNoResponseFunctionBodyStatement(statementsList, requestType); + } + //Create statements + NodeList statements = createNodeList(statementsList); + return createFunctionBodyBlockNode(openBraceToken, null, statements, closeBraceToken, null); + } + + private void createStreamFunctionBodyStatements(List statementsList, + String requestType, String responseType, String dispatcherStreamId, + boolean isSubscribe) { + String pipeId = String.format("\"%s\"", requestType); + + if (!isSubscribe) { + statementsList.add(getConnectionActiveCheck()); + } + + if (!Objects.isNull(dispatcherStreamId)) { + // TODO: Add this after generated-stream-id flag implementation +// statementsList.add(getStatementToGenerateUuid(requestType, dispatcherStreamId)); + pipeId = requestType + DOT + escapeIdentifier(dispatcherStreamId); + } + + // self.pipes.addPipe(id, subscribeMessagePipe); + // Message message = check subscribeMessage.cloneWithType(); + // check self.writeMessageQueue.produce(message, timeout); + addProduceStatementForWriteMessageQueue(statementsList, requestType, isSubscribe); + + SimpleNameReferenceNode responseNameNode = createSimpleNameReferenceNode(createIdentifierToken( + responseType + ",error?")); + SimpleNameReferenceNode streamMessageNode = createSimpleNameReferenceNode(createIdentifierToken( + "streamMessages")); + +// stream streamMessages; + StreamTypeParamsNode streamTypeParamsNode = createStreamTypeParamsNode(createToken(LT_TOKEN), + responseNameNode, null, null, createToken(GT_TOKEN)); + StreamTypeDescriptorNode streamTypeDescriptorNode = createStreamTypeDescriptorNode(createToken(STREAM_KEYWORD), + streamTypeParamsNode); + + VariableDeclarationNode streamMessages = createVariableDeclarationNode(createEmptyNodeList(), null, + createTypedBindingPatternNode(streamTypeDescriptorNode, createFieldBindingPatternVarnameNode( + streamMessageNode)), //TODO: Findout [] node + null, null, semicolonToken); + + statementsList.add(streamMessages); + + // lock { + // StreamGenerator streamGenerator = check new (subscribeMessagePipe, timeout); + // self.streamGenerators.addStreamGenerator(streamGenerator); + // streamMessages = new (streamGenerator); + // } + ArrayList streamStatementList = new ArrayList<>(); + String streamGenName = GeneratorUtils.getStreamGeneratorName(responseType); + + ArrayList streamGeneratorArguments = new ArrayList<>(); + streamGeneratorArguments.add(createPositionalArgumentNode(NodeParser.parseExpression(SELF + DOT + PIPES))); + streamGeneratorArguments.add(createToken(COMMA_TOKEN)); + streamGeneratorArguments.add(createPositionalArgumentNode(NodeParser.parseExpression(pipeId))); + streamGeneratorArguments.add(createToken(COMMA_TOKEN)); + streamGeneratorArguments.add(createPositionalArgumentNode(createSimpleNameReferenceNode(createIdentifierToken( + TIMEOUT)))); + ImplicitNewExpressionNode newExpressionNode = createImplicitNewExpressionNode(createToken(NEW_KEYWORD), + createParenthesizedArgList(openParenToken, createSeparatedNodeList(streamGeneratorArguments), + closeParenToken)); + SimpleNameReferenceNode streamGeneratorNode = createSimpleNameReferenceNode(createIdentifierToken( + STREAM_GENERATOR)); + VariableDeclarationNode streamGenerator = createVariableDeclarationNode(createEmptyNodeList(), + null, createTypedBindingPatternNode(createSimpleNameReferenceNode(createIdentifierToken( + streamGenName + STREAM_GENERATOR_CAPITAL)), + createFieldBindingPatternVarnameNode(streamGeneratorNode)), equalToken, newExpressionNode, + semicolonToken); + streamStatementList.add(streamGenerator); + + MethodCallExpressionNode streamGeneratorMethodCallNode = createMethodCallExpressionNode( + createFieldAccessExpressionNode(createSimpleNameReferenceNode(createIdentifierToken(SELF)), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken( + "streamGenerators"))), + createToken(DOT_TOKEN), createSimpleNameReferenceNode(createIdentifierToken("addStreamGenerator")), + openParenToken, createSeparatedNodeList(streamGeneratorNode), closeParenToken); + ExpressionStatementNode streamGeneratorExpressionNode = createExpressionStatementNode( + null, streamGeneratorMethodCallNode, semicolonToken); + + streamStatementList.add(streamGeneratorExpressionNode); + + AssignmentStatementNode streamMessagesAssignmentStatementNode = createAssignmentStatementNode(streamMessageNode, + equalToken, createImplicitNewExpressionNode(createToken(NEW_KEYWORD), + createParenthesizedArgList(openParenToken, createSeparatedNodeList( + createPositionalArgumentNode(streamGeneratorNode)), closeParenToken)), semicolonToken); + + streamStatementList.add(streamMessagesAssignmentStatementNode); + + LockStatementNode streamLockStatementNode = createLockStatementNode(createToken(LOCK_KEYWORD), + createBlockStatementNode(openBraceToken, createNodeList(streamStatementList), closeBraceToken), null); + + statementsList.add(streamLockStatementNode); + ReturnStatementNode returnStatementNode = createReturnStatementNode(createToken(RETURN_KEYWORD), + streamMessageNode, semicolonToken); + statementsList.add(returnStatementNode); + } + + private LockStatementNode getConnectionActiveCheck() { + // lock { + // if !self.isActive { + // return error ("ConnectionError: Connection has been closed"); + // } + // } + NodeList ifIsActiveNode = createNodeList(createIfElseStatementNode(createToken(IF_KEYWORD), + createSimpleNameReferenceNode(createIdentifierToken(NOT + SELF + DOT + IS_ACTIVE)), + createBlockStatementNode(openBraceToken, createNodeList(createReturnStatementNode( + createToken(RETURN_KEYWORD), createErrorConstructorExpressionNode(createToken(ERROR_KEYWORD), + null, openParenToken, createSeparatedNodeList(createIdentifierToken( + CONNECTION_CLOSED_MESSAGE)), + closeParenToken), semicolonToken)), closeBraceToken), null)); + return createLockStatementNode(createToken(LOCK_KEYWORD), + createBlockStatementNode(openBraceToken, ifIsActiveNode, closeBraceToken), null); + } + + private void createNoResponseFunctionBodyStatement(List statementsList, String requestType) { + // check self.writeMessageQueue.produce(tuple, timeout); + + TypeDescriptorNode messageTypeNode = NodeParser.parseTypeDescriptor(MESSAGE + PIPE + ERROR); + SimpleNameReferenceNode messageVarNode = createSimpleNameReferenceNode(createIdentifierToken(MESSAGE_VAR_NAME)); + SimpleNameReferenceNode requestTypePipeNode = createSimpleNameReferenceNode(createIdentifierToken(requestType)); + + statementsList.add(getConnectionActiveCheck()); + + MethodCallExpressionNode cloneWithTypeNode = createMethodCallExpressionNode( + requestTypePipeNode, dotToken, createSimpleNameReferenceNode(createIdentifierToken(CLONE_WITH_TYPE)), + openParenToken, createSeparatedNodeList(), closeParenToken); + + VariableDeclarationNode responseTypeCloneStatement = createVariableDeclarationNode(createEmptyNodeList(), + null, createTypedBindingPatternNode(messageTypeNode, createFieldBindingPatternVarnameNode( + messageVarNode)), equalToken, cloneWithTypeNode, semicolonToken); + + statementsList.add(responseTypeCloneStatement); + statementsList.add(getCloningMessageError(MESSAGE_VAR_NAME)); + statementsList.addAll(getProduceToWriteMessageQueueVar()); + } + + /** + * Generate common statements in function body. + */ + private void createSimpleRPCFunctionBodyStatements(List statementsList, String requestType, + String responseType, String dispatcherStreamId, + boolean isSubscribe) { + String responseTypeCamelCaseName; + if (responseType.contains(PIPE)) { + responseTypeCamelCaseName = "unionResult"; + } else { + char responseTypeFirstChar = Character.toLowerCase(responseType.charAt(0)); //Lowercase the first character + String responseRemainingString = responseType.substring(1); + responseTypeCamelCaseName = responseTypeFirstChar + responseRemainingString; + } + String pipeId = String.format("\"%s\"", requestType); + if (!isSubscribe) { + statementsList.add(getConnectionActiveCheck()); + } + + if (!Objects.isNull(dispatcherStreamId)) { + // TODO: Add this after generated-stream-id flag implementation +// statementsList.add(getStatementToGenerateUuid(requestType, dispatcherStreamId)); + pipeId = requestType + DOT + escapeIdentifier(dispatcherStreamId); + } + + addProduceStatementForWriteMessageQueue(statementsList, requestType, isSubscribe); + + TypeDescriptorNode responseTypeName = NodeParser.parseTypeDescriptor(responseType + PIPE + ERROR); + TypeDescriptorNode consumeResponseType = NodeParser.parseTypeDescriptor(MESSAGE + PIPE + PIPE_ERROR_NODE); + SimpleNameReferenceNode responseMessageVarNode = createSimpleNameReferenceNode(createIdentifierToken( + RESPONSE_MESSAGE)); + SimpleNameReferenceNode responseNameNode; + if (!requestType.equals(ERROR)) { + responseNameNode = createSimpleNameReferenceNode(createIdentifierToken(responseTypeCamelCaseName)); + } else { + responseNameNode = createSimpleNameReferenceNode(createIdentifierToken( + responseTypeCamelCaseName + MESSAGE)); + } + + VariableDeclarationNode callRelevantPipeConsumeVar = createVariableDeclarationNode(createEmptyNodeList(), + null, createTypedBindingPatternNode(consumeResponseType, + createFieldBindingPatternVarnameNode(responseMessageVarNode)), equalToken, + NodeParser.parseExpression(String.format(SELF_PIPES_GET_PIPE, pipeId) + + DOT + CONSUME + String.format(WITHIN_PAREN_TEMPLATE, TIMEOUT)), semicolonToken); + // Message|pipe:Error responseMessage = tuplePipe.consume(timeout); + statementsList.add(callRelevantPipeConsumeVar); + statementsList.add(getPipeError(RESPONSE_MESSAGE, CONSUMING)); + + if (!Objects.isNull(dispatcherStreamId)) { +// error? pipeCloseErr = self.pipes.removePipe(chat.id); +// if pipeCloseErr is error { +// log:printDebug("[doChat]PipeError: Error in closing pipe"); +// } + String pipeCloseErr = "pipeCloseError"; + statementsList.add(NodeParser.parseStatement(String.format(PIPE_CLOSE_STATEMENT, pipeCloseErr, pipeId))); + statementsList.add(createIfElseStatementNode(createToken(IF_KEYWORD), NodeParser.parseExpression( + pipeCloseErr + IS + ERROR), createBlockStatementNode(openBraceToken, + createNodeList(NodeParser.parseStatement(String.format(LOG_PRINT_DEBUG_TEMPLATE, PIPE_ERR_CAPITAL, + ERROR_PIPE_CLOSE, pipeCloseErr))), closeBraceToken), null)); + } + + //PongMessage pongMessage = responseMessage.cloneWithType(); + MethodCallExpressionNode cloneWithTypeMethodCallExpressionNode = createMethodCallExpressionNode( + responseMessageVarNode, dotToken, createSimpleNameReferenceNode(createIdentifierToken(CLONE_WITH_TYPE)), + openParenToken, createSeparatedNodeList(), closeParenToken); + + VariableDeclarationNode responseTypeCloneStatement = createVariableDeclarationNode(createEmptyNodeList(), + null, createTypedBindingPatternNode(responseTypeName, createFieldBindingPatternVarnameNode( + responseNameNode)), equalToken, cloneWithTypeMethodCallExpressionNode, semicolonToken); + + statementsList.add(responseTypeCloneStatement); + statementsList.add(getCloningMessageError(responseTypeCamelCaseName)); + ReturnStatementNode returnStatementNode = createReturnStatementNode(createIdentifierToken(RETURN), + responseNameNode, semicolonToken); + statementsList.add(returnStatementNode); + } + + private static StatementNode getStatementToGenerateUuid(String requestType, String dispatcherStreamId) { + return NodeParser.parseStatement(String.format(CREATE_UUID_STATEMENT, requestType, + escapeIdentifier(dispatcherStreamId))); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionReturnTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionReturnTypeGenerator.java new file mode 100644 index 000000000..ac82d0bbd --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionReturnTypeGenerator.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.asyncapi.AsyncApiMessage; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DEFAULT_RETURN; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_KEY; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.extractReferenceType; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.getValidName; + +/** + * This util class for maintain the operation response with ballerina return type. + * + */ +public class RemoteFunctionReturnTypeGenerator { + private AsyncApi25DocumentImpl asyncAPI; + + public RemoteFunctionReturnTypeGenerator(AsyncApi25DocumentImpl asyncAPI) { + this.asyncAPI = asyncAPI; + } + + /** + * Get return type of the remote function. + *

+ * // * @param operation swagger operation. + * + * @return string with return type. + * @throws BallerinaAsyncApiExceptionWs - throws exception if creating return type fails. + */ + public String getReturnType(JsonNode xResponse, JsonNode xResponseType, ArrayList responseMessages + ) throws BallerinaAsyncApiExceptionWs { + //TODO: Handle multiple media-type + ArrayList returnTypes = new ArrayList<>(); + Map messages = asyncAPI.getComponents().getMessages(); + + if (xResponse.get("oneOf") != null) { //Handle Union references + if (xResponse.get("oneOf") instanceof ArrayNode) { + ArrayNode test = (ArrayNode) xResponse.get("oneOf"); + if (xResponseType != null) { + for (Iterator it = test.iterator(); it.hasNext(); ) { + JsonNode jsonNode = it.next(); + if (jsonNode.get("$ref") != null) { + handleReferenceReturn(jsonNode, messages, responseMessages, returnTypes); + } else if (jsonNode.get("payload") != null) { + throw new BallerinaAsyncApiExceptionWs("Ballerina service file cannot be generate to the " + + "given AsyncAPI specification, Response type must be a Record"); + } + } + } else { + throw new BallerinaAsyncApiExceptionWs("x-response-type must be included ex:-" + + " x-response-type: streaming || x-response-type: simple-rpc"); + } + } + } else if (xResponse.get("payload") != null && xResponse.get("payload") + .get("type") != new TextNode("object")) { //Handle payload references + throw new BallerinaAsyncApiExceptionWs("Ballerina service file cannot be generate to the " + + "given AsyncAPI specification, Response type must be a Record"); + } else if (xResponse.get("$ref") != null) { //Handle reference responses + handleReferenceReturn(xResponse, messages, responseMessages, returnTypes); + + } + //Add |error to the response + if (!returnTypes.isEmpty()) { + return String.join(PIPE, returnTypes); + } else { + return DEFAULT_RETURN; + } + } + + private void handleReferenceReturn(JsonNode jsonNode, Map messages, + ArrayList responseMessages, ArrayList returnTypes) + throws BallerinaAsyncApiExceptionWs { + TextNode textNode = (TextNode) asyncAPI.getExtensions().get(X_DISPATCHER_KEY); + String dispatcherKey = textNode.asText(); + String reference = jsonNode.get("$ref").asText(); + // TODO: Consider adding getValidName here , removed because of lowercase and + // uppercase error + String messageName = extractReferenceType(reference); + AsyncApiMessage message = messages.get(messageName); + TextNode schemaReference = (TextNode) message.getPayload().get("$ref"); + String schemaName = extractReferenceType(schemaReference.asText()); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) asyncAPI.getComponents().getSchemas().get(schemaName); + if (responseMessages != null) { + responseMessages.add(schemaName); + } + CommonFunctionUtils commonFunctionUtils = new CommonFunctionUtils(asyncAPI); + if (!commonFunctionUtils.isDispatcherPresent(schemaName, refSchema, dispatcherKey, true)) { + throw new BallerinaAsyncApiExceptionWs(String.format( + "dispatcherKey must be inside %s schema properties", schemaName)); + } + String type = getValidName(schemaName, true); + returnTypes.add(type); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionSignatureGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionSignatureGenerator.java new file mode 100644 index 000000000..c5fc2b59a --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/RemoteFunctionSignatureGenerator.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.document.DocCommentsGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DECIMAL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DESCRIPTION; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OPTIONAL_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SERVER_STREAMING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.TIMEOUT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_DISPATCHER_KEY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_RESPONSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_RESPONSE_TYPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.extractReferenceType; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.getValidName; +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.isValidSchemaName; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionSignatureNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURNS_KEYWORD; + +/** + * This util class uses for generating {@link FunctionSignatureNode} for given OAS + * operation. + * + */ +public class RemoteFunctionSignatureGenerator { + private final AsyncApi25DocumentImpl asyncAPI; + private final List typeDefinitionNodeList; + private final BallerinaTypesGenerator ballerinaSchemaGenerator; + + public RemoteFunctionSignatureGenerator(AsyncApi25DocumentImpl asyncAPI, + BallerinaTypesGenerator ballerinaSchemaGenerator, + List typeDefinitionNodeList) { + this.asyncAPI = asyncAPI; + this.ballerinaSchemaGenerator = ballerinaSchemaGenerator; + this.typeDefinitionNodeList = typeDefinitionNodeList; + } + + public List getTypeDefinitionNodeList() { + return typeDefinitionNodeList; + } + + /** + * This function for generate function signatures. + * + * @param payload - asyncAPI operation + * @return {@link FunctionSignatureNode} + * @throws BallerinaAsyncApiExceptionWs - throws exception when node creation fails. + */ + public FunctionSignatureNode getFunctionSignatureNode(JsonNode payload, List remoteFunctionDoc, + Map extensions, String returnType, + List streamReturns) + throws BallerinaAsyncApiExceptionWs { + List parameterList = new ArrayList<>(); + if (payload != null) { + String parameterType = getDataType(payload); + Node requestTypeParamNode = getRequestTypeParameterNode(parameterType); + parameterList.add(requestTypeParamNode); + parameterList.add(createToken(COMMA_TOKEN)); + TextNode descriptionNode = (TextNode) payload.get(DESCRIPTION); + if (descriptionNode != null) { + MarkdownParameterDocumentationLineNode paramDoc = + DocCommentsGenerator.createAPIParamDoc(getValidName(parameterType, false), + descriptionNode.asText()); + MarkdownParameterDocumentationLineNode timeoutDoc = + DocCommentsGenerator.createAPIParamDoc(TIMEOUT, + "waiting period to keep the event in the buffer in seconds"); + remoteFunctionDoc.add(paramDoc); + remoteFunctionDoc.add(timeoutDoc); + } + } + + parameterList.add(getTimeOutParameterNode()); + + SeparatedNodeList parameters = createSeparatedNodeList(parameterList); + //Create Return type - function with response + + ReturnTypeDescriptorNode returnTypeDescriptorNode; + if (extensions != null) { + JsonNode xResponse = extensions.get(X_RESPONSE); + JsonNode xResponseType = extensions.get(X_RESPONSE_TYPE); + if (xResponseType != null && xResponseType.equals(new TextNode(SERVER_STREAMING))) { + if (!streamReturns.contains(returnType)) { + streamReturns.add(returnType); + } + returnType = "stream<" + returnType + ",error?>"; + } + String finalReturnType = returnType + PIPE_TOKEN.stringValue() + ERROR; + TextNode responseDescription = (TextNode) xResponse.get(DESCRIPTION); + if (xResponse.get(DESCRIPTION) != null) { + MarkdownParameterDocumentationLineNode returnDoc = + DocCommentsGenerator.createAPIParamDoc("return", responseDescription.asText()); + remoteFunctionDoc.add(returnDoc); + } + // Return Type + returnTypeDescriptorNode = createReturnTypeDescriptorNode(createToken(RETURNS_KEYWORD), + createEmptyNodeList(), createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(finalReturnType))); + } else { + returnTypeDescriptorNode = createReturnTypeDescriptorNode(createToken(RETURNS_KEYWORD), + createEmptyNodeList(), createSimpleNameReferenceNode(createIdentifierToken(OPTIONAL_ERROR))); + } + return createFunctionSignatureNode(createToken(OPEN_PAREN_TOKEN), parameters, createToken(CLOSE_PAREN_TOKEN), + returnTypeDescriptorNode); + } + + private Node getTimeOutParameterNode() { + TypeDescriptorNode typeName = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(DECIMAL)); + IdentifierToken paramNameNode = createIdentifierToken(TIMEOUT); + return createRequiredParameterNode(createNodeList(), typeName, paramNameNode); + } + + public String getDataType(JsonNode payload) throws BallerinaAsyncApiExceptionWs { + String type = ""; + if (payload.get("$ref") != null) { + // TODO: Consider adding getValidName here , removed because of lowercase and uppercase error + type = extractReferenceType(payload.get("$ref").textValue()); + AsyncApi25SchemaImpl componentSchema = (AsyncApi25SchemaImpl) asyncAPI.getComponents(). + getSchemas().get(type).asSchema(); + TextNode textNode = (TextNode) asyncAPI.getExtensions().get(X_DISPATCHER_KEY); + String dispatcherKey = textNode.asText(); + CommonFunctionUtils commonFunctionUtils = new CommonFunctionUtils(asyncAPI); + if (!commonFunctionUtils.isDispatcherPresent(type, componentSchema, dispatcherKey, true)) { + throw new BallerinaAsyncApiExceptionWs(String.format( + "dispatcherKey must be inside %s schema properties", type)); + } + + if (!isValidSchemaName(type)) { + List responseDocs = new ArrayList<>(); + if (payload.get(DESCRIPTION) != null) { + responseDocs.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + payload.get(DESCRIPTION).asText(), false)); + } + TypeDefinitionNode typeDefinitionNode = ballerinaSchemaGenerator.getTypeDefinitionNode + (componentSchema, type, responseDocs); + GeneratorUtils.updateTypeDefNodeList(type, typeDefinitionNode, typeDefinitionNodeList); + } + } + return type; + } + + /** + * Create parameter for remote function. + *

+ */ + public Node getRequestTypeParameterNode(String paramType) { + TypeDescriptorNode typeName; + typeName = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken( + getValidName(paramType, true))); + IdentifierToken paramName = + createIdentifierToken(getValidName(paramType, false)); + return createRequiredParameterNode(createNodeList(new ArrayList<>()), typeName, paramName); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/TestGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/TestGenerator.java new file mode 100644 index 000000000..692deedde --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/TestGenerator.java @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.BuiltinSimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.CaptureBindingPatternNode; +import io.ballerina.compiler.syntax.tree.CheckExpressionNode; +import io.ballerina.compiler.syntax.tree.ExplicitNewExpressionNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.FunctionArgumentNode; +import io.ballerina.compiler.syntax.tree.FunctionBodyNode; +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MappingFieldNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; +import io.ballerina.compiler.syntax.tree.ModulePartNode; +import io.ballerina.compiler.syntax.tree.ModuleVariableDeclarationNode; +import io.ballerina.compiler.syntax.tree.NamedArgumentNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.ParenthesizedArgList; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.TypedBindingPatternNode; +import io.ballerina.tools.text.TextDocument; +import io.ballerina.tools.text.TextDocuments; +import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.API_KEY_CONFIG; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createAnnotationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCaptureBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createCheckExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createExplicitNewExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionBodyBlockNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionSignatureNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMappingConstructorExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createModulePartNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createModuleVariableDeclarationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createNamedArgumentNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createParenthesizedArgList; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypedBindingPatternNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CHECK_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_DEFINITION; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.NEW_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; + +/** + * This class use for generating boilerplate codes for test cases. + * + */ +public class TestGenerator { + private final IntermediateClientGenerator intermediateClientGenerator; + private final List remoteFunctionNameList; + private final String configFileName; + private final boolean isHttpOrOAuth; + + public TestGenerator(IntermediateClientGenerator intermediateClientGenerator) { + this.intermediateClientGenerator = intermediateClientGenerator; + this.remoteFunctionNameList = intermediateClientGenerator.getRemoteFunctionNameList(); + this.configFileName = ""; + this.isHttpOrOAuth = false; + } + + /** + * Generate test.bal file synatx tree. + * + * @return {@link SyntaxTree} + * @throws IOException Throws exception when syntax tree not modified + * @throws BallerinaAsyncApiExceptionWs Throws exception if open api validation failed + */ + public SyntaxTree generateSyntaxTree() throws IOException, BallerinaAsyncApiExceptionWs { + List functions = new ArrayList<>(); + getFunctionDefinitionNodes(functions); + List nodes = new ArrayList<>(getModuleVariableDeclarationNodes()); + NodeList imports = getImportNodes(); + nodes.addAll(functions); + Token eofToken = createIdentifierToken(""); + ModulePartNode modulePartNode = createModulePartNode(imports, createNodeList(nodes), eofToken); + TextDocument textDocument = TextDocuments.from(""); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); + return syntaxTree.modifyWith(modulePartNode); + } + + /** + * Generate import nodes for test.bal file. + * + * @return Import node list + */ + private NodeList getImportNodes() { + NodeList imports; + ImportDeclarationNode importForTest = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA, + GeneratorConstants.MODULE_TEST); + ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode(GeneratorConstants.BALLERINA, + GeneratorConstants.HTTP); + if (isHttpOrOAuth) { + imports = AbstractNodeFactory.createNodeList(importForTest, importForHttp); + } else { + imports = AbstractNodeFactory.createNodeList(importForTest); + } + return imports; + } + + /** + * Returns String of the relevant config file to the generated test.bal. + * + * @return {@link String} + * @throws IOException Throws an exception if file not exists + */ + public String getConfigTomlFile() throws IOException { + ClassLoader classLoader = getClass().getClassLoader(); + if (!configFileName.isBlank()) { + if (!isHttpOrOAuth) { + StringBuilder configFileContent = new StringBuilder("[" + API_KEY_CONFIG + "]\n"); + for (String apiKey : intermediateClientGenerator.getApiKeyNameList()) { + configFileContent.append(GeneratorUtils.getValidName(apiKey, false)). + append(" = \"\"\n"); + } + return configFileContent.toString(); + } + InputStream inputStream = classLoader.getResourceAsStream("config_toml_files/" + configFileName); + if (inputStream != null) { + return IOUtils.toString(inputStream, StandardCharsets.UTF_8); + } + } + return ""; + } + + /** + * Provide module variable declaration nodes of the test.bal file. + * -- ex: Variable declaration nodes of test.bal for basic auth. + *

+     *      configurable http:CredentialsConfig & readonly authConfig = ?;
+     *      ClientConfig clientConfig = {authConfig : authConfig};
+     *      Client baseClient = check new Client(clientConfig, serviceUrl = "https://domain/services/data");
+     * 
+ * + * @return {@link List} List of variable declaration nodes + */ + private List getModuleVariableDeclarationNodes() { + List moduleVariableDeclarationNodes = new ArrayList<>(); + moduleVariableDeclarationNodes.add(getClientInitForNoAuth()); + return moduleVariableDeclarationNodes; + } + + /** + * Generate client initialization node when no auth mehanism found. + * + * @return {@link ModuleVariableDeclarationNode} + */ + private ModuleVariableDeclarationNode getClientInitForNoAuth() { + String clientName = intermediateClientGenerator.getClientName(); + String serverURL = intermediateClientGenerator.getServerUrl(); + MetadataNode metadataNode = createMetadataNode(null, createEmptyNodeList()); + BuiltinSimpleNameReferenceNode typeBindingPattern = createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(clientName)); + CaptureBindingPatternNode bindingPattern = createCaptureBindingPatternNode( + createIdentifierToken("baseClient")); + TypedBindingPatternNode typedBindingPatternNode = createTypedBindingPatternNode(typeBindingPattern, + bindingPattern); + Token openParenArg = createToken(OPEN_PAREN_TOKEN); + Token closeParenArg = createToken(CLOSE_PAREN_TOKEN); + Token newKeyWord = createToken(NEW_KEYWORD); + List argumentsList = new ArrayList<>(); + ExpressionNode expressionNode = createRequiredExpressionNode(createIdentifierToken + ("\"" + serverURL + "\"")); + NamedArgumentNode positionalArgumentNode = createNamedArgumentNode(createSimpleNameReferenceNode + (createIdentifierToken(GeneratorConstants.SERVICE_URL)), createToken(EQUAL_TOKEN), expressionNode); + argumentsList.add(positionalArgumentNode); + SeparatedNodeList arguments = createSeparatedNodeList(argumentsList); + ParenthesizedArgList parenthesizedArgList = createParenthesizedArgList(openParenArg, arguments, + closeParenArg); + TypeDescriptorNode clientClassType = createBuiltinSimpleNameReferenceNode(null, createIdentifierToken + (clientName)); + ExplicitNewExpressionNode explicitNewExpressionNode = createExplicitNewExpressionNode(newKeyWord, + clientClassType, parenthesizedArgList); + CheckExpressionNode initializer = createCheckExpressionNode(null, createToken(CHECK_KEYWORD), + explicitNewExpressionNode); + NodeList nodeList = createEmptyNodeList(); + return createModuleVariableDeclarationNode(metadataNode, null, nodeList, typedBindingPatternNode, + createToken(EQUAL_TOKEN), initializer, createToken(SEMICOLON_TOKEN)); + } + + /** + * Generate test functions for each remote function in the generated client.bal. + *
+     *      @test:Config {}
+     *      isolated function  testCurrentWeatherData() {
+     *      }
+     * 
+ * + * @param functions Empty function definition node list + */ + private void getFunctionDefinitionNodes(List functions) { + if (!remoteFunctionNameList.isEmpty()) { + for (String functionName : remoteFunctionNameList) { + MetadataNode metadataNode = getAnnotation(); + Token functionKeyWord = createToken(FUNCTION_KEYWORD); + IdentifierToken testFunctionName = createIdentifierToken(GeneratorConstants.PREFIX_TEST + + modifyFunctionName(functionName.trim())); + FunctionSignatureNode functionSignatureNode = getFunctionSignature(); + FunctionBodyNode functionBodyNode = getFunctionBody(); + NodeList relativeResourcePath = createEmptyNodeList(); + Token isolatedQualifierNode = AbstractNodeFactory.createIdentifierToken("isolated"); + NodeList qualifierList = createNodeList(isolatedQualifierNode); + FunctionDefinitionNode functionDefinitionNode = createFunctionDefinitionNode(FUNCTION_DEFINITION, + metadataNode, qualifierList, functionKeyWord, testFunctionName, relativeResourcePath, + functionSignatureNode, functionBodyNode); + functions.add(functionDefinitionNode); + } + } + } + + /** + * Generate function signature node. + * -- ex: {@code isolated function testCurrentWeatherData()} + * + * @return {@link FunctionSignatureNode} + */ + private FunctionSignatureNode getFunctionSignature() { + List parameterList = new ArrayList<>(); + SeparatedNodeList parameters = createSeparatedNodeList(parameterList); + return createFunctionSignatureNode(createToken(OPEN_PAREN_TOKEN), + parameters, createToken(CLOSE_PAREN_TOKEN), null); + } + + /** + * Generate empty function body node. + * -- ex: {@code isolated function testCurrentWeatherData()} + * + * @return {@link FunctionBodyNode} + */ + private FunctionBodyNode getFunctionBody() { + List statementsList = new ArrayList<>(); + NodeList statementsNodeList = createNodeList(statementsList); + return createFunctionBodyBlockNode(createToken(OPEN_BRACE_TOKEN), + null, statementsNodeList, createToken(CLOSE_BRACE_TOKEN), null); + } + + /** + * Generate test annotation node. + * --ex: {@code @test:Config {}} + * + * @return {@link MetadataNode} + */ + private MetadataNode getAnnotation() { + SimpleNameReferenceNode annotateReference = + createSimpleNameReferenceNode(createIdentifierToken(GeneratorConstants.ANNOT_TEST)); + List fileds = new ArrayList<>(); + SeparatedNodeList fieldNodesList = createSeparatedNodeList(fileds); + MappingConstructorExpressionNode annotValue = createMappingConstructorExpressionNode( + createToken(OPEN_BRACE_TOKEN), fieldNodesList, createToken(CLOSE_BRACE_TOKEN)); + AnnotationNode annotationNode = createAnnotationNode(createToken(SyntaxKind.AT_TOKEN), + annotateReference, annotValue); + return createMetadataNode(null, createNodeList(annotationNode)); + } + + /** + * Modify function name by capitalizing the first letter. + * + * @param name remote function name + * @return formatted name + */ + private String modifyFunctionName(String name) { + return name.substring(0, 1).toUpperCase(Locale.getDefault()) + name.substring(1); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/UtilGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/UtilGenerator.java new file mode 100644 index 000000000..2d0ec3b05 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/UtilGenerator.java @@ -0,0 +1,518 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client; + +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.generators.document.DocCommentsGenerator; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.AssignmentStatementNode; +import io.ballerina.compiler.syntax.tree.ChildNodeEntry; +import io.ballerina.compiler.syntax.tree.ClassDefinitionNode; +import io.ballerina.compiler.syntax.tree.FunctionBodyNode; +import io.ballerina.compiler.syntax.tree.FunctionDefinitionNode; +import io.ballerina.compiler.syntax.tree.FunctionSignatureNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; +import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; +import io.ballerina.compiler.syntax.tree.ModulePartNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.ObjectFieldNode; +import io.ballerina.compiler.syntax.tree.ParameterNode; +import io.ballerina.compiler.syntax.tree.RequiredParameterNode; +import io.ballerina.compiler.syntax.tree.ReturnTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SeparatedNodeList; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.StatementNode; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.TypeReferenceNode; +import io.ballerina.compiler.syntax.tree.WhileStatementNode; +import io.ballerina.projects.DocumentId; +import io.ballerina.projects.Package; +import io.ballerina.projects.Project; +import io.ballerina.projects.directory.ProjectLoader; +import io.ballerina.tools.text.TextDocument; +import io.ballerina.tools.text.TextDocuments; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BALLERINA; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CLOSE_STREAM_STATEMENT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DECIMAL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.DOT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.INIT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.IS; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.MESSAGE_VAR_NAME; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.NEXT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.OPTIONAL_ERROR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPES; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPES_MAP; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.PIPE_ID; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.RESPONSE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SELF; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SEMICOLON; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SIMPLE_PIPE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.SPACE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_GENERATORS_MAP; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_GENERATOR_CAPITAL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_NEXT_CONSUME_MESSAGE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STREAM_NEXT_RESPONSE_CLONE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.TIMEOUT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.TRUE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.TYPE_INCLUSION_GENERATOR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.URL; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WITHIN_BRACE_TEMPLATE; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.XLIBB; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.XLIBB_PIPE; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createSeparatedNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createAssignmentStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBlockStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createClassDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionBodyBlockNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createFunctionSignatureNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIfElseStatementNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createModulePartNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createObjectFieldNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredParameterNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createReturnTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSingletonTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeDefinitionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createWhileStatementNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ASTERISK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLASS_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLIENT_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.COMMA_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CONTINUE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EOF_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FINAL_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.FUNCTION_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.IF_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ISOLATED_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PRIVATE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURNS_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RETURN_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.WHILE_KEYWORD; + +/** + * This class is used to generate util file syntax tree according to the generated client. + * + */ +public class UtilGenerator { + private static final Logger LOGGER = LoggerFactory.getLogger(UtilGenerator.class); + private static final String GET_ENCODED_URI = "getEncodedUri"; + private static final String GET_PATH_FOR_QUERY_PARAM = "getPathForQueryParam"; + private static final String GET_COMBINE_HEADERS = "getCombineHeaders"; + private static final Token openParenToken = createToken(OPEN_PAREN_TOKEN); + private static final Token closeParenToken = createToken(CLOSE_PAREN_TOKEN); + private static final Token openBraceToken = createToken(OPEN_BRACE_TOKEN); + private static final Token closeBraceToken = createToken(CLOSE_BRACE_TOKEN); + private static final Token semicolonToken = createToken(SEMICOLON_TOKEN); + private final ArrayList streamReturns; + private boolean headersFound = false; + private boolean queryParamsFound = false; + private boolean pathParametersFound = false; + + public UtilGenerator(ArrayList streamReturns) { + this.streamReturns = streamReturns; + } + + + /** + * Set `queryParamsFound` flag to `true` when at least one query parameter found. + * + * @param flag Function will be called only in the occasions where flag needs to be set to `true` + */ + public void setQueryParamsFound(boolean flag) { + this.queryParamsFound = flag; + } + + /** + * Set `headersFound` flag to `true` when at least one header found. + * + * @param flag Function will be called only in the occasions where flag needs to be set to `true` + */ + public void setHeadersFound(boolean flag) { + this.headersFound = flag; + } + + /** + * Set `pathParametersFound` flag to `true` when at least one path parameter found. + * + * @param flag Function will be called only in the occasions where flag needs to be set to `true` + */ + public void setPathParametersFound(boolean flag) { + this.pathParametersFound = flag; + } + + + /** + * Generates util file syntax tree. + * + * @return Syntax tree of the util.bal file + */ + public SyntaxTree generateUtilSyntaxTree() throws IOException { + Set functionNameList = new LinkedHashSet<>(); + List imports = new ArrayList<>(); + functionNameList.add(PIPES_MAP); + ImportDeclarationNode importForXLibbPipe = GeneratorUtils.getImportDeclarationNode(XLIBB, XLIBB_PIPE); + imports.add(importForXLibbPipe); + if (queryParamsFound) { + functionNameList.addAll(Arrays.asList(GET_ENCODED_URI, GET_PATH_FOR_QUERY_PARAM)); + } + if (headersFound) { + functionNameList.add(GET_COMBINE_HEADERS); + } + if (pathParametersFound) { + functionNameList.add(GET_ENCODED_URI); + } + + List memberDeclarationNodes = new ArrayList<>(); + getUtilTypeDeclarationNodes(memberDeclarationNodes); + + if (!streamReturns.isEmpty()) { + for (String returnType : streamReturns) { + memberDeclarationNodes.add(createStreamGenerator(returnType)); + } + functionNameList.add(TYPE_INCLUSION_GENERATOR); + functionNameList.add(STREAM_GENERATORS_MAP); + } + + Path path = getResourceFilePath(); + + Project project = ProjectLoader.loadProject(path); + Package currentPackage = project.currentPackage(); + DocumentId docId = currentPackage.getDefaultModule().documentIds().iterator().next(); + SyntaxTree syntaxTree = currentPackage.getDefaultModule().document(docId).syntaxTree(); + + ModulePartNode modulePartNode = syntaxTree.rootNode(); + NodeList members = modulePartNode.members(); + for (ModuleMemberDeclarationNode node : members) { + if (node.kind().equals(SyntaxKind.FUNCTION_DEFINITION) || node.kind().equals(SyntaxKind.CLASS_DEFINITION) + || node.kind().equals(SyntaxKind.TYPE_DEFINITION)) { + for (ChildNodeEntry childNodeEntry : node.childEntries()) { + if (childNodeEntry.name().equals("functionName") || childNodeEntry.name().equals + ("className") || childNodeEntry.name().equals("typeName")) { + if (functionNameList.contains(childNodeEntry.node().get().toString().trim())) { + memberDeclarationNodes.add(node); + } + break; + } + } + } + } + + if (functionNameList.contains(GET_ENCODED_URI)) { + ImportDeclarationNode importForUrl = GeneratorUtils.getImportDeclarationNode(BALLERINA, URL); + imports.add(importForUrl); + } + + NodeList importsList = createNodeList(imports); + ModulePartNode utilModulePartNode = createModulePartNode(importsList, createNodeList(memberDeclarationNodes), + createToken(EOF_TOKEN)); + TextDocument textDocument = TextDocuments.from(""); + SyntaxTree utilSyntaxTree = SyntaxTree.from(textDocument); + return utilSyntaxTree.modifyWith(utilModulePartNode); + } + + private ClassDefinitionNode createStreamGenerator(String returnType) { + // Collect members for class definition node + List memberNodeList = new ArrayList<>(); + + memberNodeList.addAll(createClassInstanceVariables()); + memberNodeList.add(createInitFunction()); + memberNodeList.add(createNextFunction(returnType)); + memberNodeList.add(createCloseFunction()); + + MetadataNode metadataNode = getClassMetadataNode(returnType); + returnType = GeneratorUtils.getStreamGeneratorName(returnType); + IdentifierToken className = createIdentifierToken(returnType + STREAM_GENERATOR_CAPITAL); + NodeList classTypeQualifiers = createNodeList(createToken(CLIENT_KEYWORD), + createToken(ISOLATED_KEYWORD)); + return createClassDefinitionNode(metadataNode, createToken(PUBLIC_KEYWORD), classTypeQualifiers, + createToken(CLASS_KEYWORD), className, openBraceToken, createNodeList(memberNodeList), + closeBraceToken, null); + } + + private List createClassInstanceVariables() { + List fieldNodeList = new ArrayList<>(); + Token privateKeywordToken = createToken(PRIVATE_KEYWORD); + Token finalKeywordToken = createToken(FINAL_KEYWORD); + ArrayList prefixTokens = new ArrayList<>(); + prefixTokens.add(privateKeywordToken); + prefixTokens.add(finalKeywordToken); + NodeList qualifierList = createNodeList(prefixTokens); + + //*Generator + TypeReferenceNode typeReferenceNode = createTypeReferenceNode(createToken(ASTERISK_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(TYPE_INCLUSION_GENERATOR)), semicolonToken); + + //private final pipe:Pipe pipe; + ObjectFieldNode pipesField = createObjectFieldNode(null, null, qualifierList, + NodeParser.parseTypeDescriptor(PIPES_MAP), createIdentifierToken(PIPES), null, null, semicolonToken); + + //private final string pipeId; + SimpleNameReferenceNode stringType = createSimpleNameReferenceNode(createIdentifierToken(STRING)); + IdentifierToken pipeId = createIdentifierToken(PIPE_ID); + + ObjectFieldNode pipeIdField = createObjectFieldNode(null, null, qualifierList, + stringType, pipeId, null, null, semicolonToken); + + //private final decimal timeout; + SimpleNameReferenceNode decimalType = createSimpleNameReferenceNode(createIdentifierToken(DECIMAL)); + IdentifierToken timeout = createIdentifierToken(TIMEOUT); + + ObjectFieldNode timeoutField = createObjectFieldNode(null, null, qualifierList, + decimalType, timeout, null, null, semicolonToken); + + fieldNodeList.add(typeReferenceNode); + fieldNodeList.add(pipesField); + fieldNodeList.add(pipeIdField); + fieldNodeList.add(timeoutField); + return fieldNodeList; + } + + + + private MetadataNode getClassMetadataNode(String returnType) { + List classLevelAnnotationNodes = new ArrayList<>(); + // Generate api doc + List documentationLines = new ArrayList<>(DocCommentsGenerator.createAPIDescriptionDoc( + "Stream generator class for " + returnType + " return type", false)); + MarkdownDocumentationNode apiDoc = createMarkdownDocumentationNode(createNodeList(documentationLines)); + return createMetadataNode(apiDoc, createNodeList(classLevelAnnotationNodes)); + } + + private FunctionDefinitionNode createNextFunction(String returnType) { + FunctionSignatureNode functionSignatureNode = getNextFunctionSignatureNode(returnType); + FunctionBodyNode functionBodyNode = getNextFunctionBodyNode(returnType); + NodeList qualifierList = createNodeList(createToken(PUBLIC_KEYWORD), createToken(ISOLATED_KEYWORD)); + IdentifierToken functionName = createIdentifierToken(NEXT); + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, null, qualifierList, + createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), functionSignatureNode, + functionBodyNode); + } + + + private FunctionDefinitionNode createCloseFunction() { + FunctionSignatureNode functionSignatureNode = getCloseFunctionSignatureNode(); + FunctionBodyNode functionBodyNode = getCloseFunctionBodyNode(); + NodeList qualifierList = createNodeList(createToken(PUBLIC_KEYWORD), createToken(ISOLATED_KEYWORD)); + IdentifierToken functionName = createIdentifierToken("close"); + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, null, qualifierList, + createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), functionSignatureNode, + functionBodyNode); + } + + private FunctionSignatureNode getNextFunctionSignatureNode(String returnType) { + SimpleNameReferenceNode returnTypeNode = createSimpleNameReferenceNode(createIdentifierToken( + "record {|" + returnType + " value;|}|error")); + //returns + ReturnTypeDescriptorNode returnTypeDescriptorNode = createReturnTypeDescriptorNode( + createToken(RETURNS_KEYWORD), createEmptyNodeList(), returnTypeNode); + return createFunctionSignatureNode(openParenToken, createSeparatedNodeList(), closeParenToken, + returnTypeDescriptorNode); + } + + private FunctionSignatureNode getCloseFunctionSignatureNode() { + SimpleNameReferenceNode returnTypeNode = createSimpleNameReferenceNode(createIdentifierToken( + "error?")); + //returns + ReturnTypeDescriptorNode returnTypeDescriptorNode = createReturnTypeDescriptorNode( + createToken(RETURNS_KEYWORD), createEmptyNodeList(), returnTypeNode); + return createFunctionSignatureNode(openParenToken, createSeparatedNodeList(), closeParenToken, + returnTypeDescriptorNode); + } + + private FunctionBodyNode getCloseFunctionBodyNode() { + List assignmentNodes = new ArrayList<>(); + assignmentNodes.add(NodeParser.parseStatement(CLOSE_STREAM_STATEMENT)); + NodeList statementList = createNodeList(assignmentNodes); + return createFunctionBodyBlockNode(openBraceToken, null, statementList, closeBraceToken, null); + } + + private FunctionBodyNode getNextFunctionBodyNode(String returnType) { + + List statements = new ArrayList<>(); + statements.add(NodeParser.parseStatement(STREAM_NEXT_CONSUME_MESSAGE)); + statements.add(createIfElseStatementNode(createToken(IF_KEYWORD), NodeParser.parseExpression( + MESSAGE_VAR_NAME + IS + OPTIONAL_ERROR), createBlockStatementNode(openBraceToken, + createNodeList(NodeParser.parseStatement(CONTINUE_KEYWORD.stringValue() + SEMICOLON)), + closeBraceToken), null)); + statements.add(NodeParser.parseStatement(String.format(STREAM_NEXT_RESPONSE_CLONE, returnType))); + statements.add(NodeParser.parseStatement(RETURN_KEYWORD.stringValue() + SPACE + + String.format(WITHIN_BRACE_TEMPLATE, "value: " + RESPONSE) + SEMICOLON)); + WhileStatementNode whileStatementNode = createWhileStatementNode(createToken(WHILE_KEYWORD), + NodeParser.parseExpression(TRUE), createBlockStatementNode(openBraceToken, createNodeList(statements), + closeBraceToken), null); + NodeList statementList = createNodeList(whileStatementNode); + return createFunctionBodyBlockNode(openBraceToken, null, statementList, closeBraceToken, null); + } + + private FunctionDefinitionNode createInitFunction() { + FunctionSignatureNode functionSignatureNode = getStreamInitFunctionSignatureNode(); + FunctionBodyNode functionBodyNode = getStreamInitFunctionBodyNode(); + NodeList qualifierList = createNodeList(createToken(PUBLIC_KEYWORD), createToken(ISOLATED_KEYWORD)); + IdentifierToken functionName = createIdentifierToken(INIT); + return createFunctionDefinitionNode(SyntaxKind.OBJECT_METHOD_DEFINITION, getInitDocComment(), qualifierList, + createToken(FUNCTION_KEYWORD), functionName, createEmptyNodeList(), functionSignatureNode, + functionBodyNode); + } + + private MetadataNode getInitDocComment() { + List docs = new ArrayList<>(); + + docs.addAll(DocCommentsGenerator.createAPIDescriptionDoc("StreamGenerator", true)); + // Create method description + MarkdownParameterDocumentationLineNode pipeNodeDocs = DocCommentsGenerator.createAPIParamDoc( + SIMPLE_PIPE, "Pipe to hold stream messages"); + docs.add(pipeNodeDocs); + MarkdownParameterDocumentationLineNode timeoutNodeDocs = DocCommentsGenerator.createAPIParamDoc( + TIMEOUT, "Waiting time"); + docs.add(timeoutNodeDocs); + MarkdownDocumentationNode clientInitDoc = createMarkdownDocumentationNode(createNodeList(docs)); + return createMetadataNode(clientInitDoc, createEmptyNodeList()); + } + + + private FunctionSignatureNode getStreamInitFunctionSignatureNode() { + RequiredParameterNode pipeNode = createRequiredParameterNode(createNodeList(), + createSimpleNameReferenceNode(createIdentifierToken(PIPES_MAP)), createIdentifierToken(PIPES)); + RequiredParameterNode pipeIdNode = createRequiredParameterNode(createNodeList(), + createSimpleNameReferenceNode(createIdentifierToken(STRING)), createIdentifierToken(PIPE_ID)); + RequiredParameterNode decimalNode = createRequiredParameterNode(createNodeList(), createSimpleNameReferenceNode( + createIdentifierToken(DECIMAL)), createIdentifierToken(TIMEOUT)); + List parameterList = new ArrayList<>(); + parameterList.add(pipeNode); + parameterList.add(createToken(COMMA_TOKEN)); + parameterList.add(pipeIdNode); + parameterList.add(createToken(COMMA_TOKEN)); + parameterList.add(decimalNode); + SeparatedNodeList parameters = createSeparatedNodeList(parameterList); + return createFunctionSignatureNode(openParenToken, parameters, closeParenToken, null); + } + + private FunctionBodyNode getStreamInitFunctionBodyNode() { + List assignmentNodes = new ArrayList<>(); + AssignmentStatementNode selfPipes = createAssignmentStatementNode(createIdentifierToken( + SELF + DOT + PIPES), createToken(EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(PIPES)), createToken(SEMICOLON_TOKEN)); + AssignmentStatementNode selfPipeId = createAssignmentStatementNode(createIdentifierToken( + SELF + DOT + PIPE_ID), createToken(EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(PIPE_ID)), createToken(SEMICOLON_TOKEN)); + AssignmentStatementNode selfTimeout = createAssignmentStatementNode(createIdentifierToken(SELF + DOT + + TIMEOUT), createToken(EQUAL_TOKEN), + createSimpleNameReferenceNode(createIdentifierToken(TIMEOUT)), createToken(SEMICOLON_TOKEN)); + assignmentNodes.add(selfPipes); + assignmentNodes.add(selfPipeId); + assignmentNodes.add(selfTimeout); + NodeList statementList = createNodeList(assignmentNodes); + return createFunctionBodyBlockNode(openBraceToken, null, statementList, closeBraceToken, null); + } + + + /** + * Set the type definition nodes related to the util functions generated. + * + * @param memberDeclarationNodes {@link ModuleMemberDeclarationNode} + */ + private void getUtilTypeDeclarationNodes(List memberDeclarationNodes) { + if (queryParamsFound || headersFound) { + memberDeclarationNodes.add(getSimpleBasicTypeDefinitionNode()); + } + } + + /** + * Generates `SimpleBasicType` type. + * + * @return + */ + private TypeDefinitionNode getSimpleBasicTypeDefinitionNode() { + TypeDescriptorNode typeDescriptorNode = createSingletonTypeDescriptorNode( + createSimpleNameReferenceNode(createIdentifierToken("string|boolean|int|float|decimal"))); + return createTypeDefinitionNode(null, null, createToken(TYPE_KEYWORD), + createIdentifierToken("SimpleBasicType"), typeDescriptorNode, semicolonToken); + } + + /** + * Gets the path of the utils_asyncapi.bal template at the time of execution. + * + * @return Path to utils_asyncapi.bal file in the temporary directory created + * @throws IOException When failed to get the templates/utils_asyncapi.bal file from resources + */ + private Path getResourceFilePath() throws IOException { + Path path = null; + ClassLoader classLoader = getClass().getClassLoader(); + InputStream inputStream = classLoader.getResourceAsStream("templates/utils_asyncapi.bal"); + if (inputStream != null) { + String clientSyntaxTreeString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + Path tmpDir = Files.createTempDirectory(".util-tmp" + System.nanoTime()); + path = tmpDir.resolve("utils.bal"); + try (PrintWriter writer = new PrintWriter(path.toString(), StandardCharsets.UTF_8)) { + writer.print(clientSyntaxTreeString); + } + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + FileUtils.deleteDirectory(tmpDir.toFile()); + } catch (IOException ex) { + LOGGER.error("Unable to delete the temporary directory : " + tmpDir, ex); + } + })); + } + return path; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/model/AasClientConfig.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/model/AasClientConfig.java new file mode 100644 index 000000000..1df7983fc --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/client/model/AasClientConfig.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.client.model; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; + +/** + * This class stores metadata that related to client code generations. + * + */ +public class AasClientConfig { + private final AsyncApi25DocumentImpl asyncAPI; + private final String license; + + private AasClientConfig(Builder clientConfigBuilder) { + this.asyncAPI = clientConfigBuilder.asyncAPI; + this.license = clientConfigBuilder.license; + } + + public AsyncApi25DocumentImpl getAsyncAPI() { + return asyncAPI; + } + + public String getLicense() { + return license; + } + + /** + * Client IDL plugin meta data builder class. + */ + public static class Builder { + private AsyncApi25DocumentImpl asyncAPI; + private String license = "// AUTO-GENERATED FILE. DO NOT MODIFY.\n\n" + + "// This file is auto-generated by the Ballerina AsyncAPI tool.\n"; + + public Builder withAsyncApi(AsyncApi25DocumentImpl asyncAPI) { + this.asyncAPI = asyncAPI; + return this; + } + + public Builder withLicense(String license) { + this.license = license; + return this; + } + + public AasClientConfig build() { + return new AasClientConfig(this); + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/document/DocCommentsGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/document/DocCommentsGenerator.java new file mode 100644 index 000000000..084ba595b --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/document/DocCommentsGenerator.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.document; + +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.MarkdownParameterDocumentationLineNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.SyntaxKind; +import io.ballerina.compiler.syntax.tree.Token; + +import java.util.ArrayList; +import java.util.List; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyMinutiaeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createLiteralValueToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationLineNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownParameterDocumentationLineNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.DOCUMENTATION_DESCRIPTION; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.HASH_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.MARKDOWN_DOCUMENTATION_LINE; + +/** + * This class util for maintain the API doc comment related functions. + * + */ +public class DocCommentsGenerator { + + public static List createAPIDescriptionDoc(String description, + boolean addExtraLine) { + // Capitalize the first letter of the description. This is to maintain consistency + String[] descriptionLines = description.split("\n"); + List documentElements = new ArrayList<>(); + Token hashToken = createToken(HASH_TOKEN, createEmptyMinutiaeList(), GeneratorUtils.SINGLE_WS_MINUTIAE); + for (String line : descriptionLines) { + MarkdownDocumentationLineNode documentationLineNode = + createMarkdownDocumentationLineNode(MARKDOWN_DOCUMENTATION_LINE, hashToken, + createNodeList(createLiteralValueToken(DOCUMENTATION_DESCRIPTION, line, + createEmptyMinutiaeList(), + GeneratorUtils.SINGLE_END_OF_LINE_MINUTIAE))); + documentElements.add(documentationLineNode); + } + if (addExtraLine) { + MarkdownDocumentationLineNode newLine = createMarkdownDocumentationLineNode(MARKDOWN_DOCUMENTATION_LINE, + createToken(SyntaxKind.HASH_TOKEN), createEmptyNodeList()); + documentElements.add(newLine); + } + return documentElements; + } + + public static MarkdownParameterDocumentationLineNode createAPIParamDoc(String paramName, String description) { + String[] paramDescriptionLines = description.split("\n"); + List documentElements = new ArrayList<>(); + for (String line : paramDescriptionLines) { + if (!line.isBlank()) { + documentElements.add(createIdentifierToken(line + " ")); + } + } + return createMarkdownParameterDocumentationLineNode(null, createToken(SyntaxKind.HASH_TOKEN), + createToken(SyntaxKind.PLUS_TOKEN), createIdentifierToken(paramName), + createToken(SyntaxKind.MINUS_TOKEN), createNodeList(documentElements)); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/BallerinaTypesGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/BallerinaTypesGenerator.java new file mode 100644 index 000000000..f97d6a04a --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/BallerinaTypesGenerator.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema; + +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25ComponentsImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.AllOfRecordTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.ArrayTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.RecordTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.TypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.UnionTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.model.GeneratorMetaData; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.ModuleMemberDeclarationNode; +import io.ballerina.compiler.syntax.tree.ModulePartNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.tools.text.TextDocument; +import io.ballerina.tools.text.TextDocuments; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONNECTION_CONFIG; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.HTTP; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.WEBSOCKET; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; + +/** + * This class wraps the {@link Schema} from asyncAPI models inorder to overcome complications + * while populating syntax tree. + * + */ +public class BallerinaTypesGenerator { + + private final List typeDefinitionNodeList; + private final Set imports = new LinkedHashSet<>(); + private boolean hasConstraints; + + /** + * This public constructor is used to generate record and other relevant data type when the nullable flag is + * enabled in the asyncAPI command. + * + * @param asyncAPI AsyncAPI definition + * @param typeDefinitionNodeList list of types generated by earlier generations + */ + public BallerinaTypesGenerator(AsyncApi25DocumentImpl asyncAPI, + List typeDefinitionNodeList) { + GeneratorMetaData.createInstance(asyncAPI); + this.typeDefinitionNodeList = typeDefinitionNodeList; + this.hasConstraints = false; + } + + public BallerinaTypesGenerator(AsyncApi25DocumentImpl asyncAPI) { + this(asyncAPI, new LinkedList<>()); + } + + /** + * Create Type Definition Node for a given AsyncAPI schema. + * + * @param schema AsyncAPI schema + * @param typeName IdentifierToken of the name of the type + * @return {@link TypeDefinitionNode} + * @throws BallerinaAsyncApiExceptionWs when unsupported schema type is found + */ + public TypeDefinitionNode getTypeDefinitionNode(AsyncApi25SchemaImpl schema, String typeName, + List schemaDocs) + throws BallerinaAsyncApiExceptionWs { + IdentifierToken typeNameToken = AbstractNodeFactory.createIdentifierToken(GeneratorUtils.getValidName( + typeName.trim(), true)); + TypeGenerator typeGenerator = TypeGeneratorUtils.getTypeGenerator(schema, GeneratorUtils.getValidName( + typeName.trim(), true), null); + List typeAnnotations = new ArrayList<>(); + AnnotationNode constraintNode = TypeGeneratorUtils.generateConstraintNode(typeName, schema); + if (constraintNode != null) { + typeAnnotations.add(constraintNode); + } + TypeGeneratorUtils.getRecordDocs(schemaDocs, schema); + TypeDefinitionNode typeDefinitionNode = + typeGenerator.generateTypeDefinitionNode(typeNameToken, schemaDocs, typeAnnotations); + if (typeGenerator instanceof ArrayTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + typeDefinitionNodeList.addAll(typeGenerator.getTypeDefinitionNodeList()); + } else if (typeGenerator instanceof RecordTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + removeDuplicateNode(typeGenerator.getTypeDefinitionNodeList()); + } else if (typeGenerator instanceof AllOfRecordTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + removeDuplicateNode(typeGenerator.getTypeDefinitionNodeList()); + } else if (typeGenerator instanceof UnionTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + removeDuplicateNode(typeGenerator.getTypeDefinitionNodeList()); + } + imports.addAll(typeGenerator.getImports()); + return typeDefinitionNode; + } + + private void removeDuplicateNode(List newConstraintNode) { + for (TypeDefinitionNode newNode : newConstraintNode) { + boolean isExist = false; + for (TypeDefinitionNode oldNode : typeDefinitionNodeList) { + if (newNode.typeName().text().equals(oldNode.typeName().text())) { + isExist = true; + break; + } + } + if (!isExist) { + typeDefinitionNodeList.add(newNode); + } + } + } + + public SyntaxTree generateSyntaxTree() throws BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorMetaData.getInstance().getAsyncAPI(); + List typeDefinitionNodeListForSchema = new ArrayList<>(); + if (asyncAPI.getComponents() != null) { + // Create typeDefinitionNode + AsyncApi25ComponentsImpl components = (AsyncApi25ComponentsImpl) asyncAPI.getComponents(); + Map schemas = components.getSchemas(); + + if (schemas != null) { + for (Map.Entry schema : schemas.entrySet()) { + String schemaKey = schema.getKey().trim(); + if (!hasConstraints) { + hasConstraints = GeneratorUtils.hasConstraints(schema.getValue()); + } + if (GeneratorUtils.isValidSchemaName(schemaKey)) { + List schemaDoc = new ArrayList<>(); + typeDefinitionNodeListForSchema.add(getTypeDefinitionNode( + (AsyncApi25SchemaImpl) schema.getValue(), schemaKey, schemaDoc)); + } + } + } + } + + //Create imports for the http module, when record has http type inclusions. + NodeList imports = generateImportNodes(); + typeDefinitionNodeList.addAll(typeDefinitionNodeListForSchema); + // Create module member declaration + NodeList moduleMembers = AbstractNodeFactory.createNodeList( + typeDefinitionNodeList.toArray(new TypeDefinitionNode[typeDefinitionNodeList.size()])); + + Token eofToken = AbstractNodeFactory.createIdentifierToken(""); + ModulePartNode modulePartNode = NodeFactory.createModulePartNode(imports, moduleMembers, eofToken); + TextDocument textDocument = TextDocuments.from(""); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); + return syntaxTree.modifyWith(modulePartNode); + } + + private NodeList generateImportNodes() { + List importDeclarationNodes = new ArrayList<>(); + if (!typeDefinitionNodeList.isEmpty()) { + importsForTypeDefinitions(importDeclarationNodes); + } + if (!imports.isEmpty()) { + for (String importValue : imports) { + ImportDeclarationNode importDeclarationNode = NodeParser.parseImportDeclaration(importValue); + importDeclarationNodes.add(importDeclarationNode); + } + } + if (imports.isEmpty()) { + return createEmptyNodeList(); + } + return createNodeList(importDeclarationNodes); + } + + private void importsForTypeDefinitions(List imports) { + for (TypeDefinitionNode node : typeDefinitionNodeList) { + if (!(node.typeDescriptor() instanceof RecordTypeDescriptorNode)) { + continue; + } + if (node.typeName().text().equals(CONNECTION_CONFIG)) { + ImportDeclarationNode importForWebsocket = GeneratorUtils.getImportDeclarationNode( + GeneratorConstants.BALLERINA, + WEBSOCKET); + ImportDeclarationNode importForHttp = GeneratorUtils.getImportDeclarationNode( + GeneratorConstants.BALLERINA, + HTTP); + imports.add(importForWebsocket); + imports.add(importForHttp); + } + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/TypeGeneratorUtils.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/TypeGeneratorUtils.java new file mode 100644 index 000000000..fb151c67f --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/TypeGeneratorUtils.java @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema; + +import com.fasterxml.jackson.databind.node.BooleanNode; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.models.union.BooleanUnionValueImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.document.DocCommentsGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.AllOfRecordTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.AnyDataTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.ArrayTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.JsonTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.MapTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.PrimitiveTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.RecordTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.ReferencedTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.TypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators.UnionTypeGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.model.GeneratorMetaData; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ExpressionNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.MappingConstructorExpressionNode; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.RecordFieldNode; +import io.ballerina.compiler.syntax.tree.RecordFieldWithDefaultValueNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ARRAY; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BALLERINA; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BOOLEAN; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONSTRAINT; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.INTEGER; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.NUMBER; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.STRING; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.X_NULLABLE; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createRequiredExpressionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.AT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.EQUAL_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.MAPPING_CONSTRUCTOR; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; + +/** + * Contains util functions needed for schema generation. + * + */ +public class TypeGeneratorUtils { + private static final List primitiveTypeList = + new ArrayList<>(Arrays.asList(GeneratorConstants.INTEGER, GeneratorConstants.NUMBER, + GeneratorConstants.STRING, GeneratorConstants.BOOLEAN)); + + private static final PrintStream OUT_STREAM = System.err; + + /** + * Get SchemaType object relevant to the schema given. + * + * @param schemaValue Schema object + * @param typeName Parameter name + * @return Relevant SchemaType object + * @throws BallerinaAsyncApiExceptionWs Exception + */ + public static TypeGenerator getTypeGenerator(AsyncApi25SchemaImpl schemaValue, String typeName, + String parentName) throws BallerinaAsyncApiExceptionWs { + if (schemaValue.getType() != null) { + GeneratorUtils.convertAsyncAPITypeToBallerina(schemaValue.getType()); + } + if (schemaValue.get$ref() != null) { + return new ReferencedTypeGenerator(schemaValue, typeName); + } else if (schemaValue.getType() != null && schemaValue.getType().equals(GeneratorConstants.ARRAY)) { + return new ArrayTypeGenerator(schemaValue, typeName, parentName); + } else if (schemaValue.getType() != null && primitiveTypeList.contains(schemaValue.getType())) { + return new PrimitiveTypeGenerator(schemaValue, typeName); + } else if (schemaValue.getOneOf() != null || schemaValue.getAllOf() != null || schemaValue.getAnyOf() != null) { + if (schemaValue.getAllOf() != null) { + return new AllOfRecordTypeGenerator(schemaValue, typeName); + } else { + return new UnionTypeGenerator(schemaValue, typeName); + } + } else if ((schemaValue.getType() != null && schemaValue.getType().equals(GeneratorConstants.OBJECT)) || + schemaValue.getProperties() != null) { + return new RecordTypeGenerator(schemaValue, typeName); + } else if (schemaValue.getType() != null && schemaValue.getType().equals(GeneratorConstants.OBJECT) && + schemaValue.getAdditionalProperties() != null && + (schemaValue.getAdditionalProperties() instanceof AsyncApi25SchemaImpl || + (schemaValue.getAdditionalProperties() instanceof BooleanUnionValueImpl && + schemaValue.getAdditionalProperties().asBoolean().equals(true)))) { + return new MapTypeGenerator(schemaValue, typeName); + + } else if (schemaValue.getType() == null && schemaValue.getProperties() == null && + schemaValue.getAdditionalProperties() != null) { + return new JsonTypeGenerator(schemaValue, typeName); + } else { // when schemaValue.type == null + return new AnyDataTypeGenerator(schemaValue, typeName); + } + } + + /** + * Generate proper type name considering the nullable configurations. + * Scenario 1 : schema.getNullable() != null && schema.getNullable() == true && nullable == true -> string? + * Scenario 2 : schema.getNullable() != null && schema.getNullable() == true && nullable == false -> string? + * Scenario 3 : schema.getNullable() != null && schema.getNullable() == false && nullable == false -> string + * Scenario 4 : schema.getNullable() != null && schema.getNullable() == false && nullable == true -> string + * Scenario 5 : schema.getNullable() == null && nullable == true -> string? + * Scenario 6 : schema.getNullable() == null && nullable == false -> string + * + * @param schema Schema of the property + * @param originalTypeDesc Type name + * @return Final type of the field + */ + public static TypeDescriptorNode getNullableType(AsyncApi25SchemaImpl schema, TypeDescriptorNode originalTypeDesc) { + TypeDescriptorNode nillableType = originalTypeDesc; + if (schema.getExtensions() != null) { + if (schema.getExtensions().get(X_NULLABLE) != null && + schema.getExtensions().get(X_NULLABLE).equals(BooleanNode.TRUE)) { + nillableType = createOptionalTypeDescriptorNode(originalTypeDesc, createToken(QUESTION_MARK_TOKEN)); + } + } + return nillableType; + } + + public static ImmutablePair, Set> updateRecordFieldListWithImports( + List required, List recordFieldList, Map.Entry field, + AsyncApi25SchemaImpl fieldSchema, NodeList schemaDocNodes, IdentifierToken fieldName, + TypeDescriptorNode fieldTypeName) { + return updateRecordFieldListWithImports(required, recordFieldList, field, fieldSchema, schemaDocNodes, + fieldName, fieldTypeName, System.err); + } + + public static ImmutablePair, Set> + updateRecordFieldListWithImports(List required, List recordFieldList, Map.Entry field, + AsyncApi25SchemaImpl fieldSchema, NodeList schemaDocNodes, + IdentifierToken fieldName, TypeDescriptorNode fieldTypeName, + PrintStream outStream) { + MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(schemaDocNodes); +// Generate constraint annotation. + Set imports = new HashSet<>(); + AnnotationNode constraintNode = null; + +// MetadataNode metadataNode; + boolean isConstraintSupport = false; + if (fieldSchema != null) { + constraintNode = generateConstraintNode(fieldName.text(), fieldSchema); + isConstraintSupport = + constraintNode != null && + fieldSchema.getExtensions() != null && + fieldSchema.getExtensions().get(X_NULLABLE) != null || + ((((fieldSchema.getOneOf() != null || fieldSchema.getAllOf() != null || + fieldSchema.getAnyOf() != null))) && + (fieldSchema.getOneOf() != null || + fieldSchema.getAnyOf() != null)); + } + + if (isConstraintSupport) { + outStream.printf("WARNING: constraints in the AsyncAPI contract will be ignored for the " + + "field `%s`, as constraints are not supported on Ballerina union types%n", + fieldName.toString().trim()); + constraintNode = null; + } + MetadataNode metadataNode; + if (constraintNode == null) { + metadataNode = createMetadataNode(documentationNode, createEmptyNodeList()); + } else { + metadataNode = createMetadataNode(documentationNode, createNodeList(constraintNode)); + } + + if (required != null) { + setRequiredFields(required, recordFieldList, field, fieldSchema, fieldName, fieldTypeName, metadataNode); + } else { + RecordFieldNode recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null, + fieldTypeName, fieldName, createToken(QUESTION_MARK_TOKEN), createToken(SEMICOLON_TOKEN)); + recordFieldList.add(recordFieldNode); + } + if (constraintNode != null) { + ImportDeclarationNode constraintImport = GeneratorUtils.getImportDeclarationNode(BALLERINA, CONSTRAINT); + constraintImport.toSourceCode(); + imports.add(constraintImport.toSourceCode()); + } + return new ImmutablePair<>(recordFieldList, imports); + } + + private static void setRequiredFields(List required, List recordFieldList, + Map.Entry field, AsyncApi25SchemaImpl fieldSchema, + IdentifierToken fieldName, TypeDescriptorNode fieldTypeName, + MetadataNode metadataNode) { + + if (!required.contains(field.getKey().trim())) { + if (fieldSchema.getDefault() != null) { + RecordFieldWithDefaultValueNode defaultNode = + getRecordFieldWithDefaultValueNode(fieldSchema, fieldName, fieldTypeName, metadataNode); + recordFieldList.add(defaultNode); + } else { + RecordFieldNode recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null, + fieldTypeName, fieldName, createToken(QUESTION_MARK_TOKEN), + createToken(SEMICOLON_TOKEN)); + recordFieldList.add(recordFieldNode); + } + } else { + if (fieldSchema.getDefault() != null) { + RecordFieldWithDefaultValueNode defaultNode = + getRecordFieldWithDefaultValueNode(fieldSchema, fieldName, fieldTypeName, metadataNode); + recordFieldList.add(defaultNode); + } else { + RecordFieldNode recordFieldNode = NodeFactory.createRecordFieldNode(metadataNode, null, + fieldTypeName, fieldName, null, createToken(SEMICOLON_TOKEN)); + recordFieldList.add(recordFieldNode); + + } + } + } + + private static RecordFieldWithDefaultValueNode getRecordFieldWithDefaultValueNode(AsyncApi25SchemaImpl fieldSchema, + IdentifierToken fieldName, + TypeDescriptorNode fieldTypeName, + MetadataNode metadataNode) { + Token defaultValueToken; + String defaultValue = fieldSchema.getDefault().toString().trim(); + if ((fieldSchema.getType() != null && fieldSchema.getType().equals(STRING) || fieldSchema.getType() == null)) { + if (defaultValue.equals("\"")) { + defaultValueToken = AbstractNodeFactory.createIdentifierToken("\"" + "\\" + + fieldSchema.getDefault().asText() + "\""); + } else { + defaultValueToken = AbstractNodeFactory.createIdentifierToken(fieldSchema.getDefault().toString()); + } + } else if (!defaultValue.matches("^[0-9]*$") && !defaultValue.matches("^(\\d*\\.)?\\d+$") + && !(defaultValue.startsWith("[") && defaultValue.endsWith("]")) && + !(fieldSchema.getType() != null && fieldSchema.getType().equals(BOOLEAN))) { + //This regex was added due to avoid adding quotes for default values which are numbers and array values. + //Ex: default: 123 + defaultValueToken = AbstractNodeFactory.createIdentifierToken(fieldSchema.getDefault().asText()); + } else { + defaultValueToken = AbstractNodeFactory.createIdentifierToken(fieldSchema. + getDefault().toString().trim().replaceAll("\\\\", "")); + } + ExpressionNode expressionNode = createRequiredExpressionNode(defaultValueToken); + return NodeFactory.createRecordFieldWithDefaultValueNode + (metadataNode, null, fieldTypeName, fieldName, createToken(EQUAL_TOKEN), + expressionNode, createToken(SEMICOLON_TOKEN)); + } + + /** + * This util is to set the constraint validation for given data type in the record field and user define type. + *

+ * // * @param fieldSchema Schema for data type + * + * @return {@link MetadataNode} + */ + public static AnnotationNode generateConstraintNode(String typeName, AsyncApi25SchemaImpl fieldSchema) { + + if (fieldSchema.getType() != null && isConstraintAllowed(typeName, fieldSchema)) { + if (fieldSchema.getType().equals(STRING)) { + AsyncApi25SchemaImpl stringSchema = fieldSchema; + // Attributes : maxLength, minLength + return generateStringConstraint(stringSchema); + } else if (fieldSchema.getType().equals(INTEGER) || fieldSchema.getType().equals(NUMBER)) { + // Attribute : minimum, maximum, exclusiveMinimum, exclusiveMaximum + return generateNumberConstraint(fieldSchema); + } else if (fieldSchema.getType().equals(ARRAY)) { + AsyncApi25SchemaImpl arraySchema = fieldSchema; + // Attributes: maxItems, minItems + return generateArrayConstraint(arraySchema); + } + // Ignore Object, Map and Composed schemas. + return null; + } + return null; + } + + public static boolean isConstraintAllowed(String typeName, AsyncApi25SchemaImpl schema) { + boolean isConstraintNotAllowed = schema.getExtensions() != null && schema.getExtensions().get(X_NULLABLE) + != null || + (schema.getOneOf() != null && schema.getAllOf() != null && schema.getAnyOf() != null && + (schema.getOneOf() != null || + schema.getAnyOf() != null)); + if (isConstraintNotAllowed) { + OUT_STREAM.printf("WARNING: constraints in the AsyncAPI contract will be ignored for the " + + "type `%s`, as constraints are not supported on Ballerina union types%n", + typeName.trim()); + return false; + } + return true; + } + + /** + * /** + * Generate constraint for numbers : int, float, decimal. + */ + private static AnnotationNode generateNumberConstraint(AsyncApi25SchemaImpl fieldSchema) { + List fields = getNumberAnnotFields(fieldSchema); + if (fields.isEmpty()) { + return null; + } + String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) + + GeneratorConstants.CLOSE_BRACE; + AnnotationNode annotationNode; + if (fieldSchema.getType().equals(NUMBER)) { + if (fieldSchema.getFormat() != null && fieldSchema.getFormat().equals(GeneratorConstants.FLOAT)) { + annotationNode = createAnnotationNode(GeneratorConstants.CONSTRAINT_FLOAT, annotBody); + } else { + annotationNode = createAnnotationNode(GeneratorConstants.CONSTRAINT_NUMBER, annotBody); + } + } else { + annotationNode = createAnnotationNode(GeneratorConstants.CONSTRAINT_INT, annotBody); + } + return annotationNode; + } + + /** + * Generate constraint for string. + */ + private static AnnotationNode generateStringConstraint(AsyncApi25SchemaImpl stringSchema) { + List fields = getStringAnnotFields(stringSchema); + if (fields.isEmpty()) { + return null; + } + String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) + + GeneratorConstants.CLOSE_BRACE; + return createAnnotationNode(GeneratorConstants.CONSTRAINT_STRING, annotBody); + } + + /** + * Generate constraint for array. + */ + private static AnnotationNode generateArrayConstraint(AsyncApi25SchemaImpl arraySchema) { + List fields = getArrayAnnotFields(arraySchema); + if (fields.isEmpty()) { + return null; + } + String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) + + GeneratorConstants.CLOSE_BRACE; + return createAnnotationNode(GeneratorConstants.CONSTRAINT_ARRAY, annotBody); + } + + private static List getNumberAnnotFields(AsyncApi25SchemaImpl numberSchema) { + List fields = new ArrayList<>(); + boolean isInt = numberSchema.getType().equals(INTEGER); + if (numberSchema.getMinimum() != null && numberSchema.getExclusiveMinimum() == null) { + String value = numberSchema.getMinimum().toString(); + String fieldRef = GeneratorConstants.MINIMUM + GeneratorConstants.COLON + + (isInt ? numberSchema.getMinimum().intValue() : value); + fields.add(fieldRef); + } + if (numberSchema.getMaximum() != null && numberSchema.getExclusiveMaximum() == null) { + String value = numberSchema.getMaximum().toString(); + String fieldRef = GeneratorConstants.MAXIMUM + GeneratorConstants.COLON + + (isInt ? numberSchema.getMaximum().intValue() : value); + fields.add(fieldRef); + } + if (numberSchema.getExclusiveMinimum() != null && + numberSchema.getMinimum() != null) { + String value = numberSchema.getMinimum().toString(); + String fieldRef = GeneratorConstants.EXCLUSIVE_MIN + GeneratorConstants.COLON + + (isInt ? numberSchema.getMinimum().intValue() : value); + fields.add(fieldRef); + } + if (numberSchema.getExclusiveMaximum() != null && + numberSchema.getMaximum() != null) { + String value = numberSchema.getMaximum().toString(); + String fieldRef = GeneratorConstants.EXCLUSIVE_MAX + GeneratorConstants.COLON + + (isInt ? numberSchema.getMaximum().intValue() : value); + fields.add(fieldRef); + } + return fields; + } + + private static List getStringAnnotFields(AsyncApi25SchemaImpl stringSchema) { + List fields = new ArrayList<>(); + if (stringSchema.getMaxLength() != null && stringSchema.getMaxLength() != 0) { + String value = stringSchema.getMaxLength().toString(); + String fieldRef = GeneratorConstants.MAX_LENGTH + GeneratorConstants.COLON + value; + fields.add(fieldRef); + } + if (stringSchema.getMinLength() != null && stringSchema.getMinLength() != 0) { + String value = stringSchema.getMinLength().toString(); + String fieldRef = GeneratorConstants.MIN_LENGTH + GeneratorConstants.COLON + value; + fields.add(fieldRef); + } + return fields; + } + + private static List getArrayAnnotFields(AsyncApi25SchemaImpl arraySchema) { + List fields = new ArrayList<>(); + if (arraySchema.getMaxItems() != null && arraySchema.getMaxItems() != 0) { + String value = arraySchema.getMaxItems().toString(); + String fieldRef = GeneratorConstants.MAX_LENGTH + GeneratorConstants.COLON + value; + fields.add(fieldRef); + } + if (arraySchema.getMinItems() != null && arraySchema.getMinItems() != 0) { + String value = arraySchema.getMinItems().toString(); + String fieldRef = GeneratorConstants.MIN_LENGTH + GeneratorConstants.COLON + value; + fields.add(fieldRef); + } + return fields; + } + + /** + * This util create any annotation node by providing annotation reference and annotation body content. + * + * @param annotationReference Annotation reference value + * @param annotFields Annotation body content fields with single string + * @return {@link AnnotationNode} + */ + private static AnnotationNode createAnnotationNode(String annotationReference, String annotFields) { + MappingConstructorExpressionNode annotationBody = null; + SimpleNameReferenceNode annotReference = createSimpleNameReferenceNode( + createIdentifierToken(annotationReference)); + ExpressionNode expressionNode = NodeParser.parseExpression(annotFields); + if (expressionNode.kind() == MAPPING_CONSTRUCTOR) { + annotationBody = (MappingConstructorExpressionNode) expressionNode; + } + return NodeFactory.createAnnotationNode(createToken(AT_TOKEN), annotReference, annotationBody); + } + + /** + * Creates API documentation for record fields. + * + * @param field Schema of the field to generate + * @return Documentation node list + */ + public static List getFieldApiDocs(AsyncApi25SchemaImpl field) { + List schemaDoc = new ArrayList<>(); + if (field.getDescription() != null) { + schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + field.getDescription(), false)); + } else if (field.get$ref() != null) { + String[] split = field.get$ref().trim().split("/"); + String componentName = GeneratorUtils.getValidName(split[split.length - 1], true); + AsyncApi25DocumentImpl asyncAPI = GeneratorMetaData.getInstance().getAsyncAPI(); + if (asyncAPI.getComponents().getSchemas().get(componentName) != null) { + AsyncApi25SchemaImpl schema = (AsyncApi25SchemaImpl) asyncAPI.getComponents().getSchemas() + .get(componentName); + if (schema.getDescription() != null) { + schemaDoc.addAll(DocCommentsGenerator.createAPIDescriptionDoc(schema.getDescription(), false)); + } + } + } + return schemaDoc; + } + + /** + * Creates record documentation. + * + * @param documentation Documentation node list + * @param schemaValue AsyncAPI schema + * // * @param typeAnnotations Annotation list of the record + */ + public static void getRecordDocs(List documentation, AsyncApi25SchemaImpl schemaValue + ) throws BallerinaAsyncApiExceptionWs { + if (schemaValue.getDescription() != null) { + documentation.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + schemaValue.getDescription(), false)); + } else if (schemaValue.get$ref() != null) { + String typeName = GeneratorUtils.getValidName(GeneratorUtils.extractReferenceType( + schemaValue.get$ref()), true); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) GeneratorMetaData.getInstance().getAsyncAPI(). + getComponents().getSchemas().get(typeName); + if (refSchema.getDescription() != null) { + documentation.addAll(DocCommentsGenerator.createAPIDescriptionDoc( + refSchema.getDescription(), false)); + } + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java new file mode 100644 index 000000000..c1d80c416 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/AllOfRecordTypeGenerator.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.model.GeneratorMetaData; +import io.ballerina.asyncapi.websocketscore.generators.schema.model.RecordMetadata; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.RecordRestDescriptorNode; +import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.TypeReferenceNode; +import io.ballerina.compiler.syntax.tree.UnionTypeDescriptorNode; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils.getTypeGenerator; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ASTERISK_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ELLIPSIS_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RECORD_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for allOf schemas. + * + */ +public class AllOfRecordTypeGenerator extends RecordTypeGenerator { + private final List restSchemas = new LinkedList<>(); + + public AllOfRecordTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + /** + * This util is to create the union record rest fields, when given allOf schema has multiple additional fields. + * Note: This scenario only happens with AllOf scenarios since it maps with type inclusions. + * + * @return + */ + private static RecordRestDescriptorNode getRestDescriptorNodeForAllOf(List restSchemas) + throws BallerinaAsyncApiExceptionWs { + TypeDescriptorNode unionType = getUnionType(restSchemas); + return NodeFactory.createRecordRestDescriptorNode(unionType, createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } + + /** + * Creates the UnionType done for a given schema list. + * + * @param schemas List of schemas included in additional fields. + * @return Union type + * @throws BallerinaAsyncApiExceptionWs when unsupported combination of schemas found + */ + private static TypeDescriptorNode getUnionType(List schemas) throws BallerinaAsyncApiExceptionWs { + // TODO: this has issue with generating union type with `string?|int?... + // this will be tracked via https://github.com/ballerina-platform/openapi-tools/issues/810 + List typeDescriptorNodes = new ArrayList<>(); + for (Schema schema : schemas) { + TypeGenerator typeGenerator = getTypeGenerator((AsyncApi25SchemaImpl) schema, null, + null); + TypeDescriptorNode typeDescriptorNode = typeGenerator.generateTypeDescriptorNode(); + typeDescriptorNodes.add(typeDescriptorNode); + // error for rest field unhandled constraint support + + if (GeneratorUtils.hasConstraints(schema)) { + // use printStream for echo the error, because current asyncapi to ballerina implementation won't + // handle diagnostic message. + OUT_STREAM.println("WARNING: constraints in the AsyncAPI contract will be ignored for the " + + "additionalProperties field, as constraints are not supported on Ballerina rest record " + + "field."); + } + } + if (typeDescriptorNodes.size() > 1) { + UnionTypeDescriptorNode unionTypeDescriptorNode = null; + TypeDescriptorNode leftTypeDesc = typeDescriptorNodes.get(0); + for (int i = 1; i < typeDescriptorNodes.size(); i++) { + TypeDescriptorNode rightTypeDesc = typeDescriptorNodes.get(i); + unionTypeDescriptorNode = createUnionTypeDescriptorNode(leftTypeDesc, createToken(PIPE_TOKEN), + rightTypeDesc); + leftTypeDesc = unionTypeDescriptorNode; + } + return unionTypeDescriptorNode; + } else { + return typeDescriptorNodes.get(0); + } + } + + /** + * Generates TypeDescriptorNode for allOf schemas. + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + // This assertion is always `true` because this type generator receive ComposedSchema during the upper level + // filtering as input. Has to use this assertion statement instead of `if` condition, because to avoid + // unreachable else statement. +// assert schema instanceof ComposedSchema; + AsyncApi25SchemaImpl composedSchema = schema; + List allOfSchemas = null; + if (composedSchema.getAllOf() != null) { + allOfSchemas = composedSchema.getAllOf(); + } + + RecordMetadata recordMetadata = getRecordMetadata(); + RecordRestDescriptorNode restDescriptorNode = recordMetadata.getRestDescriptorNode(); + if (allOfSchemas != null && allOfSchemas.size() == 1 && ((AsyncApi25SchemaImpl) + allOfSchemas.get(0)).get$ref() != null) { + ReferencedTypeGenerator referencedTypeGenerator = new ReferencedTypeGenerator((AsyncApi25SchemaImpl) + allOfSchemas.get(0), typeName); + return referencedTypeGenerator.generateTypeDescriptorNode(); + } else { + List recordFieldList = null; + if (allOfSchemas != null) { + recordFieldList = generateAllOfRecordFields(allOfSchemas); + } + addAdditionalSchemas(schema); + restDescriptorNode = + restSchemas.size() > 1 ? getRestDescriptorNodeForAllOf(restSchemas) : restDescriptorNode; + + NodeList fieldNodes = AbstractNodeFactory.createNodeList(recordFieldList); + return NodeFactory.createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + recordMetadata.isOpenRecord() ? createToken(OPEN_BRACE_TOKEN) : createToken(OPEN_BRACE_PIPE_TOKEN), + fieldNodes, restDescriptorNode, + recordMetadata.isOpenRecord() ? createToken(CLOSE_BRACE_TOKEN) : + createToken(CLOSE_BRACE_PIPE_TOKEN)); + } + } + + private List generateAllOfRecordFields(List allOfSchemas) throws BallerinaAsyncApiExceptionWs { + List recordFieldList = new ArrayList<>(); + for (Schema schema : allOfSchemas) { + AsyncApi25SchemaImpl allOfSchema = (AsyncApi25SchemaImpl) schema; + if ((allOfSchema).get$ref() != null) { + String extractedSchemaName = GeneratorUtils.extractReferenceType(allOfSchema.get$ref()); + String modifiedSchemaName = GeneratorUtils.getValidName(extractedSchemaName, true); + Token typeRef = AbstractNodeFactory.createIdentifierToken(modifiedSchemaName); + TypeReferenceNode recordField = NodeFactory.createTypeReferenceNode(createToken(ASTERISK_TOKEN), + typeRef, createToken(SEMICOLON_TOKEN)); + // check whether given reference schema has additional fields. + AsyncApi25DocumentImpl asyncAPI = GeneratorMetaData.getInstance().getAsyncAPI(); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) asyncAPI.getComponents() + .getSchemas().get(extractedSchemaName); + addAdditionalSchemas(refSchema); + recordFieldList.add(recordField); + } else if (allOfSchema.getProperties() != null) { + Map properties = allOfSchema.getProperties(); + List required = allOfSchema.getRequired(); + List recordFields = addRecordFields(required, properties.entrySet(), typeName); + recordFieldList.addAll(recordFields); + addAdditionalSchemas(allOfSchema); + } else if (( + (allOfSchema.getOneOf() != null || allOfSchema.getAllOf() != null || + allOfSchema.getAnyOf() != null))) { + AsyncApi25SchemaImpl nestedComposedSchema = allOfSchema; + if (nestedComposedSchema.getAllOf() != null) { + recordFieldList.addAll(generateAllOfRecordFields(nestedComposedSchema.getAllOf())); + } else { + // TODO: Needs to improve the error message. Could not access the schema name at this level. + throw new BallerinaAsyncApiExceptionWs( + "Unsupported nested OneOf or AnyOf schema is found inside a AllOf schema."); + } + } + } + return recordFieldList; + } + + private void addAdditionalSchemas(AsyncApi25SchemaImpl refSchema) { + if (refSchema.getAdditionalProperties() != null && refSchema.getAdditionalProperties() instanceof Schema) { + restSchemas.add(refSchema.getAdditionalProperties().asSchema()); + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java new file mode 100644 index 000000000..43cb7e566 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/AnyDataTypeGenerator.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for schemas without type. + * + */ +public class AnyDataTypeGenerator extends TypeGenerator { + + public AnyDataTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + /** + * Generate TypeDescriptorNode schemas with no type. + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + return TypeGeneratorUtils.getNullableType(schema, createSimpleNameReferenceNode( + createIdentifierToken(GeneratorConstants.ANY_DATA))); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java new file mode 100644 index 000000000..4176962f8 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/ArrayTypeGenerator.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.ArrayDimensionNode; +import io.ballerina.compiler.syntax.tree.ArrayTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.NodeParser; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import java.util.ArrayList; +import java.util.List; + +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.hasConstraints; +import static io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils.getNullableType; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createEmptyNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createArrayDimensionNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createArrayTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createParenthesisedTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ARRAY_TYPE_DESC; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACKET_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_PAREN_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACKET_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_PAREN_TOKEN; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for array schemas. + * + */ +public class ArrayTypeGenerator extends TypeGenerator { + private String parentType = null; + + public ArrayTypeGenerator(AsyncApi25SchemaImpl schema, String typeName, String parentType) { + super(schema, typeName); + this.parentType = parentType; + } + + /** + * Generate TypeDescriptorNode for array type schemas. If array type is not given, type will be `AnyData` + * public type StringArray string[]; + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + AsyncApi25SchemaImpl arraySchema = schema; + AsyncApi25SchemaImpl items = (AsyncApi25SchemaImpl) arraySchema.getItems(); + boolean isConstraintsAvailable = hasConstraints(items) && typeName != null; + TypeGenerator typeGenerator; + if (isConstraintsAvailable) { + String normalizedTypeName = typeName.replaceAll(GeneratorConstants.SPECIAL_CHARACTER_REGEX, "").trim(); + List typeAnnotations = new ArrayList<>(); + AnnotationNode constraintNode = TypeGeneratorUtils.generateConstraintNode(typeName, items); + if (constraintNode != null) { + typeAnnotations.add(constraintNode); + } + typeName = GeneratorUtils.getValidName( + parentType != null ? parentType + "-" + normalizedTypeName + "-Items-" + items.getType() : + normalizedTypeName + "-Items-" + items.getType(), true); + typeGenerator = TypeGeneratorUtils.getTypeGenerator(items, typeName, null); + TypeDefinitionNode arrayItemWithConstraint = typeGenerator.generateTypeDefinitionNode( + createIdentifierToken(typeName), new ArrayList<>(), typeAnnotations); + imports.addAll(typeGenerator.getImports()); + typeDefinitionNodeList.add(arrayItemWithConstraint); + } else { + typeGenerator = TypeGeneratorUtils.getTypeGenerator(items, typeName, null); + } + TypeDescriptorNode typeDescriptorNode; + typeDefinitionNodeList.addAll(typeGenerator.getTypeDefinitionNodeList()); + if ((typeGenerator instanceof PrimitiveTypeGenerator || + typeGenerator instanceof ArrayTypeGenerator) && isConstraintsAvailable) { + typeDescriptorNode = NodeParser.parseTypeDescriptor(typeName); + } else { + typeDescriptorNode = typeGenerator.generateTypeDescriptorNode(); + } + + if (typeGenerator instanceof UnionTypeGenerator || (items.getEnum() != null && items.getEnum().size() > 0)) { + typeDescriptorNode = createParenthesisedTypeDescriptorNode( + createToken(OPEN_PAREN_TOKEN), typeDescriptorNode, createToken(CLOSE_PAREN_TOKEN)); + } + if (typeDescriptorNode instanceof OptionalTypeDescriptorNode) { + Node node = ((OptionalTypeDescriptorNode) typeDescriptorNode).typeDescriptor(); + typeDescriptorNode = (TypeDescriptorNode) node; + } + + if (arraySchema.getMaxItems() != null) { + if (arraySchema.getMaxItems() > GeneratorConstants.MAX_ARRAY_LENGTH) { + throw new BallerinaAsyncApiExceptionWs("Maximum item count defined in the definition exceeds the " + + "maximum ballerina array length."); + } + } + NodeList arrayDimensions = createEmptyNodeList(); + if (typeDescriptorNode.kind() == ARRAY_TYPE_DESC) { + ArrayTypeDescriptorNode innerArrayType = (ArrayTypeDescriptorNode) typeDescriptorNode; + arrayDimensions = innerArrayType.dimensions(); + typeDescriptorNode = innerArrayType.memberTypeDesc(); + } + + ArrayDimensionNode arrayDimension = createArrayDimensionNode( + createToken(OPEN_BRACKET_TOKEN), null, createToken(CLOSE_BRACKET_TOKEN)); + arrayDimensions = arrayDimensions.add(arrayDimension); + ArrayTypeDescriptorNode arrayTypeDescriptorNode = createArrayTypeDescriptorNode(typeDescriptorNode, + arrayDimensions); + imports.addAll(typeGenerator.getImports()); + return getNullableType(arraySchema, arrayTypeDescriptorNode); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/JsonTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/JsonTypeGenerator.java new file mode 100644 index 000000000..cb6e2f79b --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/JsonTypeGenerator.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.JSON_KEYWORD; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for Json type schema. + * + */ +public class JsonTypeGenerator extends TypeGenerator { + public JsonTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + + //TODO: Uncomment below code with improvements +// if ((schema.getAdditionalProperties() instanceof BooleanUnionValueImpl && +// schema.getAdditionalProperties().asBoolean().equals(true)) +// || ((AsyncApi25SchemaImpl) schema.getAdditionalProperties()).getType() == null) { + +// paramType = "map<" + convertAsyncAPITypeToBallerina("{}") + ">"; +// convertAsyncAPITypeToBallerina("{}") + + + return createBuiltinSimpleNameReferenceNode(JSON_KEYWORD, createIdentifierToken("json")); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/MapTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/MapTypeGenerator.java new file mode 100644 index 000000000..7561d0e87 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/MapTypeGenerator.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.models.union.BooleanUnionValueImpl; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.convertAsyncAPITypeToBallerina; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createBuiltinSimpleNameReferenceNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMapTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeParameterNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.GT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.LT_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.MAP_KEYWORD; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for map type schema. + * + */ +public class MapTypeGenerator extends TypeGenerator { + public MapTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + + if ((schema.getAdditionalProperties() instanceof BooleanUnionValueImpl && + schema.getAdditionalProperties().asBoolean().equals(true)) + || (schema.getAdditionalProperties() instanceof AsyncApi25SchemaImpl && + ((AsyncApi25SchemaImpl) schema.getAdditionalProperties()).getType() == null)) { + + return createMapTypeDescriptorNode(createToken(MAP_KEYWORD), + createTypeParameterNode(createToken(LT_TOKEN), createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(convertAsyncAPITypeToBallerina("{}"))), + createToken(GT_TOKEN))); + } else if (schema.getAdditionalProperties() instanceof AsyncApi25SchemaImpl && ((AsyncApi25SchemaImpl) + schema.getAdditionalProperties()).getType() != null) { + return createMapTypeDescriptorNode(createToken(MAP_KEYWORD), + createTypeParameterNode(createToken(LT_TOKEN), createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(convertAsyncAPITypeToBallerina(((AsyncApi25SchemaImpl) schema. + getAdditionalProperties()).getType()))), createToken(GT_TOKEN))); + } + return createMapTypeDescriptorNode(createToken(MAP_KEYWORD), + createTypeParameterNode(createToken(LT_TOKEN), createBuiltinSimpleNameReferenceNode(null, + createIdentifierToken(convertAsyncAPITypeToBallerina(((AsyncApi25SchemaImpl) schema. + getAdditionalProperties()).getType()))), createToken(GT_TOKEN))); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java new file mode 100644 index 000000000..ae5b1c3f5 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/PrimitiveTypeGenerator.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorConstants; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for primitive type schemas. + * + */ +public class PrimitiveTypeGenerator extends TypeGenerator { + + public PrimitiveTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + /** + * Generate TypeDescriptorNode for primitive type schemas. + * public type PetName string; + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + String typeDescriptorName = GeneratorUtils.convertAsyncAPITypeToBallerina(schema.getType().trim()); + // TODO: Need to the format of other primitive types too + if (schema.getType().equals(GeneratorConstants.NUMBER)) { + if (schema.getFormat() != null) { + typeDescriptorName = GeneratorUtils.convertAsyncAPITypeToBallerina(schema.getFormat().trim()); + } + } else if (schema.getType().equals(GeneratorConstants.STRING) && schema.getFormat() != null && + schema.getFormat().equals(GeneratorConstants.BINARY)) { + typeDescriptorName = "record {byte[] fileContent; string fileName;}"; + } + TypeDescriptorNode typeDescriptorNode = createSimpleNameReferenceNode( + createIdentifierToken(typeDescriptorName)); + return TypeGeneratorUtils.getNullableType(schema, typeDescriptorNode); + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java new file mode 100644 index 000000000..db77431c3 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/RecordTypeGenerator.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import com.fasterxml.jackson.databind.node.BooleanNode; +import io.apicurio.datamodels.models.Schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.apicurio.datamodels.models.union.BooleanSchemaUnion; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils; +import io.ballerina.asyncapi.websocketscore.generators.schema.model.RecordMetadata; +import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.NodeFactory; +import io.ballerina.compiler.syntax.tree.NodeList; +import io.ballerina.compiler.syntax.tree.RecordRestDescriptorNode; +import io.ballerina.compiler.syntax.tree.RecordTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.SimpleNameReferenceNode; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.BITWISE_AND_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.CLOSE_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.ELLIPSIS_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPEN_BRACE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.RECORD_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for object type schema. + * + */ +public class RecordTypeGenerator extends TypeGenerator { + + public static final PrintStream OUT_STREAM = System.err; + + public RecordTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + /** + * Creates reference rest node when additional property has reference. + */ + public static RecordRestDescriptorNode getRestDescriptorNodeForReference(AsyncApi25SchemaImpl additionalPropSchema) + throws BallerinaAsyncApiExceptionWs { + ReferencedTypeGenerator referencedTypeGenerator = new ReferencedTypeGenerator(additionalPropSchema, + null); + TypeDescriptorNode refNode = referencedTypeGenerator.generateTypeDescriptorNode(); + return NodeFactory.createRecordRestDescriptorNode(refNode, createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } + + /** + * Generates {@code RecordRestDescriptorNode} for the additional properties in object schema. + * + */ + public static RecordRestDescriptorNode getRecordRestDescriptorNode(AsyncApi25SchemaImpl additionalPropSchema) + throws BallerinaAsyncApiExceptionWs { + + RecordRestDescriptorNode recordRestDescNode = null; + if (additionalPropSchema.getType() != null && additionalPropSchema.getType().equals("number") && + additionalPropSchema.getFormat() != null) { + // this is special for `NumberSchema` because it has format with its expected type. + String type = additionalPropSchema.getFormat(); + SimpleNameReferenceNode numberNode = NodeFactory.createSimpleNameReferenceNode(createIdentifierToken(type)); + recordRestDescNode = NodeFactory.createRecordRestDescriptorNode( + TypeGeneratorUtils.getNullableType(additionalPropSchema, numberNode), + createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } else if (additionalPropSchema.getType() != null && additionalPropSchema.getType().equals("object")) { + RecordTypeGenerator record = new RecordTypeGenerator(additionalPropSchema, null); + TypeDescriptorNode recordNode = TypeGeneratorUtils.getNullableType(additionalPropSchema, + record.generateTypeDescriptorNode()); + recordRestDescNode = NodeFactory.createRecordRestDescriptorNode(recordNode, createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } else if (additionalPropSchema.getType() != null && additionalPropSchema.getType().equals("array")) { + ArrayTypeGenerator arrayTypeGenerator = new ArrayTypeGenerator(additionalPropSchema, null, + null); + TypeDescriptorNode arrayNode = arrayTypeGenerator.generateTypeDescriptorNode(); + recordRestDescNode = NodeFactory.createRecordRestDescriptorNode(arrayNode, createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } else if (additionalPropSchema.getType() != null && additionalPropSchema.getType().equals("integer") || + additionalPropSchema.getType().equals("string") || + additionalPropSchema.getType().equals("boolean")) { + PrimitiveTypeGenerator primitiveTypeGenerator = new PrimitiveTypeGenerator(additionalPropSchema, + null); + TypeDescriptorNode primitiveNode = primitiveTypeGenerator.generateTypeDescriptorNode(); + recordRestDescNode = NodeFactory.createRecordRestDescriptorNode(primitiveNode, createToken(ELLIPSIS_TOKEN), + createToken(SEMICOLON_TOKEN)); + } else { + OUT_STREAM.printf("WARNING: the Ballerina rest record field does not support with the data type `%s`", + additionalPropSchema.getType()); + } + return recordRestDescNode; + } + + /** + * Generate TypeDescriptorNode for object type schemas. + * + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + + List recordFields = new LinkedList<>(); + // extract metadata with additional properties + RecordMetadata metadataBuilder = getRecordMetadata(); + + if (schema.getProperties() != null) { + Map properties = schema.getProperties(); + List required = schema.getRequired(); + List generatedRecordFields = addRecordFields(required, properties.entrySet(), typeName); + recordFields.addAll(generatedRecordFields); + NodeList fieldNodes = AbstractNodeFactory.createNodeList(recordFields); + RecordTypeDescriptorNode recordTypeDescriptorNode = NodeFactory. + createRecordTypeDescriptorNode(createToken(RECORD_KEYWORD), + metadataBuilder.isOpenRecord() ? createToken(OPEN_BRACE_TOKEN) : + createToken(OPEN_BRACE_PIPE_TOKEN), + fieldNodes, metadataBuilder.getRestDescriptorNode(), + metadataBuilder.isOpenRecord() ? createToken(CLOSE_BRACE_TOKEN) : + createToken(CLOSE_BRACE_PIPE_TOKEN)); + if (schema.getExtensions() != null && schema.getExtensions().containsKey("readOnly") + && schema.getExtensions().get("readOnly").equals(BooleanNode.TRUE)) { + return NodeFactory.createIntersectionTypeDescriptorNode( + NodeFactory.createSimpleNameReferenceNode( + createIdentifierToken("readonly")), + createToken(BITWISE_AND_TOKEN), recordTypeDescriptorNode); + } + return recordTypeDescriptorNode; + } else { + RecordTypeDescriptorNode recordTypeDescriptorNode = NodeFactory.createRecordTypeDescriptorNode + (createToken(RECORD_KEYWORD), + metadataBuilder.isOpenRecord() ? createToken(OPEN_BRACE_TOKEN) : + createToken(OPEN_BRACE_PIPE_TOKEN), + createNodeList(recordFields), metadataBuilder.getRestDescriptorNode(), + metadataBuilder.isOpenRecord() ? createToken(CLOSE_BRACE_TOKEN) : + createToken(CLOSE_BRACE_PIPE_TOKEN)); + if (schema.getExtensions() != null && schema.getExtensions().containsKey("readOnly") + && schema.getExtensions().get("readOnly").equals(BooleanNode.TRUE)) { + return NodeFactory.createIntersectionTypeDescriptorNode( + NodeFactory.createSimpleNameReferenceNode( + createIdentifierToken("readonly")), + createToken(BITWISE_AND_TOKEN), recordTypeDescriptorNode); + } + return recordTypeDescriptorNode; + } + } + + /** + * This function is to extract the main details of the record need to be generated and return {@code + * RecordMetadata} object with required details. + * + * @return {@code RecordMetadata} + * @throws BallerinaAsyncApiExceptionWs throws when process has some failure. + */ + public RecordMetadata getRecordMetadata() throws BallerinaAsyncApiExceptionWs { + boolean isOpenRecord = true; + RecordRestDescriptorNode recordRestDescNode = null; + if (schema.getAdditionalProperties() != null) { + Object additionalProperties = schema.getAdditionalProperties(); + if (additionalProperties instanceof Schema) { + AsyncApi25SchemaImpl additionalPropSchema = (AsyncApi25SchemaImpl) additionalProperties; + if (GeneratorUtils.hasConstraints(additionalPropSchema)) { + // use printStream to echo the error, because current asyncAPI to ballerina implementation doesn't + // handle diagnostic message. + isOpenRecord = false; + OUT_STREAM.println("WARNING: constraints in the AsyncAPI contract will be ignored for the " + + "additionalProperties field, as constraints are not supported on Ballerina rest record " + + "field."); + } + if (additionalPropSchema.get$ref() != null) { + isOpenRecord = false; + recordRestDescNode = getRestDescriptorNodeForReference(additionalPropSchema); + } else if (additionalPropSchema.getType() != null) { + isOpenRecord = false; + recordRestDescNode = getRecordRestDescriptorNode(additionalPropSchema); + } else if (( + (additionalPropSchema.getOneOf() != null || additionalPropSchema.getAllOf() != null || + additionalPropSchema.getAnyOf() != null))) { + OUT_STREAM.println("WARNING: generating Ballerina rest record field will be ignored for the " + + "AsyncAPI contract additionalProperties type `allOf, oneOf, anyOf`, as it is" + + " not supported on Ballerina rest record field."); + } + } else if (((BooleanSchemaUnion) additionalProperties).asBoolean().equals(false)) { + isOpenRecord = false; + } + } + + return new RecordMetadata.Builder() + .withIsOpenRecord(isOpenRecord) + .withRestDescriptorNode(recordRestDescNode).build(); + } + + /** + * This util for generating record field with given schema properties. + * + */ + public List addRecordFields(List required, Set> fields, + String recordName) throws BallerinaAsyncApiExceptionWs { + // TODO: Handle allOf , oneOf, anyOf + List recordFieldList = new ArrayList<>(); + for (Map.Entry field : fields) { + String fieldNameStr = GeneratorUtils.escapeIdentifier(field.getKey().trim()); + // API doc generations + AsyncApi25SchemaImpl fieldSchema = (AsyncApi25SchemaImpl) field.getValue(); + List schemaDoc = TypeGeneratorUtils.getFieldApiDocs(fieldSchema); + NodeList schemaDocNodes = createNodeList(schemaDoc); + + IdentifierToken fieldName = AbstractNodeFactory.createIdentifierToken(fieldNameStr); + TypeGenerator typeGenerator = TypeGeneratorUtils.getTypeGenerator(fieldSchema, fieldNameStr, recordName); + TypeDescriptorNode fieldTypeName = typeGenerator.generateTypeDescriptorNode(); + if (typeGenerator instanceof RecordTypeGenerator) { + fieldTypeName = TypeGeneratorUtils.getNullableType(fieldSchema, fieldTypeName); + } + + //TODO: Need to figure out this + if (typeGenerator instanceof ArrayTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + typeDefinitionNodeList.addAll(typeGenerator.getTypeDefinitionNodeList()); + } else if (typeGenerator instanceof UnionTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + List newConstraintNode = + typeGenerator.getTypeDefinitionNodeList(); + typeDefinitionNodeList.addAll(newConstraintNode); + } + + imports.addAll(typeGenerator.getImports()); + ImmutablePair, Set> fieldListWithImports = TypeGeneratorUtils. + updateRecordFieldListWithImports(required, recordFieldList, field, fieldSchema, schemaDocNodes, + fieldName, fieldTypeName); + recordFieldList = fieldListWithImports.getLeft(); + imports.addAll(fieldListWithImports.getRight()); + } + return recordFieldList; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java new file mode 100644 index 000000000..017461932 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/ReferencedTypeGenerator.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.model.GeneratorMetaData; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import static io.ballerina.compiler.syntax.tree.NodeFactory.createIdentifierToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createSimpleNameReferenceNode; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for referenced schemas. + * + */ +public class ReferencedTypeGenerator extends TypeGenerator { + + public ReferencedTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + /** + * Generate TypeDescriptorNode for referenced schemas. + * + */ + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + + String extractName = GeneratorUtils.extractReferenceType(schema.get$ref()); + String typeName = GeneratorUtils.getValidName(extractName, true); + AsyncApi25SchemaImpl refSchema = (AsyncApi25SchemaImpl) GeneratorMetaData.getInstance().getAsyncAPI() + .getComponents().getSchemas().get(typeName); + refSchema = refSchema == null ? + (AsyncApi25SchemaImpl) GeneratorMetaData.getInstance().getAsyncAPI().getComponents().getSchemas() + .get(extractName) : refSchema; + TypeDescriptorNode typeDescriptorNode = createSimpleNameReferenceNode(createIdentifierToken(typeName)); + if (refSchema == null) { + throw new BallerinaAsyncApiExceptionWs(String.format("Undefined $ref: '%s' in asyncAPI contract.", + schema.get$ref())); + } + //TODO: check if we want this nullable in references then uncomment below line +// return TypeGeneratorUtils.getNullableType(refSchema, typeDescriptorNode); + return typeDescriptorNode; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/TypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/TypeGenerator.java new file mode 100644 index 000000000..558c61051 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/TypeGenerator.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.compiler.syntax.tree.AnnotationNode; +import io.ballerina.compiler.syntax.tree.IdentifierToken; +import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; +import io.ballerina.compiler.syntax.tree.MarkdownDocumentationNode; +import io.ballerina.compiler.syntax.tree.MetadataNode; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.BALLERINA; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.CONSTRAINT; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createNodeList; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMarkdownDocumentationNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createMetadataNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createTypeDefinitionNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PUBLIC_KEYWORD; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.SEMICOLON_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.TYPE_KEYWORD; + +/** + * Abstract class for schema types. + * + */ +public abstract class TypeGenerator { + + final List typeDefinitionNodeList = new ArrayList<>(); + final LinkedHashSet imports = new LinkedHashSet<>(); + AsyncApi25SchemaImpl schema; + String typeName; + + public TypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + this.schema = schema; + this.typeName = typeName; + } + + public List getTypeDefinitionNodeList() { + return typeDefinitionNodeList; + } + + public LinkedHashSet getImports() { + return imports; + } + + /** + * Create Type Definition Node for a given AsyncAPI schema. + * + * @param typeName IdentifierToken of the name of the type + * @param schemaDoc Documentation of the type + * // * @param typeAnnotations Annotations related to the type. Currently, only includes + * `Deprecated` annotation + * @return {@link TypeDefinitionNode} + * @throws BallerinaAsyncApiExceptionWs when unsupported schema type is found + */ + public TypeDefinitionNode generateTypeDefinitionNode(IdentifierToken typeName, List schemaDoc, + List typeAnnotations) + throws BallerinaAsyncApiExceptionWs { + for (AnnotationNode annotation : typeAnnotations) { + String annotationRef = annotation.annotReference().toString(); + if (annotationRef.startsWith(CONSTRAINT)) { + ImportDeclarationNode constraintImport = GeneratorUtils.getImportDeclarationNode(BALLERINA, CONSTRAINT); + //Here we are unable to add ImportDeclarationNode since newly generated node has different hashcode. + imports.add(constraintImport.toSourceCode()); + } + } + + MarkdownDocumentationNode documentationNode = createMarkdownDocumentationNode(createNodeList(schemaDoc)); + MetadataNode metadataNode = createMetadataNode(documentationNode, createNodeList(typeAnnotations)); + return createTypeDefinitionNode(metadataNode, createToken(PUBLIC_KEYWORD), createToken(TYPE_KEYWORD), + typeName, generateTypeDescriptorNode(), + createToken(SEMICOLON_TOKEN)); + } + + /** + * Create Type Descriptor Node for a given AsyncAPI schema. + * + * @return {@link TypeDescriptorNode} + * @throws BallerinaAsyncApiExceptionWs when unsupported schema type is found + */ + public abstract TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs; +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java new file mode 100644 index 000000000..56db4b7dd --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/ballerinatypegenerators/UnionTypeGenerator.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.ballerinatypegenerators; + +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25SchemaImpl; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils; +import io.ballerina.compiler.syntax.tree.Node; +import io.ballerina.compiler.syntax.tree.OptionalTypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.TypeDescriptorNode; +import io.ballerina.compiler.syntax.tree.UnionTypeDescriptorNode; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static io.ballerina.asyncapi.websocketscore.generators.schema.TypeGeneratorUtils.getTypeGenerator; +import static io.ballerina.compiler.syntax.tree.AbstractNodeFactory.createToken; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createOptionalTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.NodeFactory.createUnionTypeDescriptorNode; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.OPTIONAL_TYPE_DESC; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.PIPE_TOKEN; +import static io.ballerina.compiler.syntax.tree.SyntaxKind.QUESTION_MARK_TOKEN; + +/** + * Generate TypeDefinitionNode and TypeDescriptorNode for anyOf and oneOf schemas. + * + */ +public class UnionTypeGenerator extends TypeGenerator { + + public UnionTypeGenerator(AsyncApi25SchemaImpl schema, String typeName) { + super(schema, typeName); + } + + @Override + public TypeDescriptorNode generateTypeDescriptorNode() throws BallerinaAsyncApiExceptionWs { + AsyncApi25SchemaImpl composedSchema = schema; + List schemas; + if (composedSchema.getOneOf() != null) { + schemas = composedSchema.getOneOf(); + } else { + schemas = composedSchema.getAnyOf(); + } + TypeDescriptorNode unionTypeDesc = getUnionType(schemas, typeName); + return TypeGeneratorUtils.getNullableType(schema, unionTypeDesc); + } + + /** + * Creates the UnionType string to generate bal type for a given oneOf or anyOf type schema. + * + * @param schemas List of schemas included in the anyOf or oneOf schema + * @param typeName This is parameter or variable name that used to populate error message meaningful + * @return Union type + * @throws BallerinaAsyncApiExceptionWs when unsupported combination of schemas found + */ + private TypeDescriptorNode getUnionType(List schemas, String typeName) + throws BallerinaAsyncApiExceptionWs { + + List typeDescriptorNodes = new ArrayList<>(); + for (AsyncApiSchema schema : schemas) { + TypeGenerator typeGenerator = getTypeGenerator((AsyncApi25SchemaImpl) schema, typeName, null); + TypeDescriptorNode typeDescNode = typeGenerator.generateTypeDescriptorNode(); + if (typeDescNode instanceof OptionalTypeDescriptorNode) { + Node internalTypeDesc = ((OptionalTypeDescriptorNode) typeDescNode).typeDescriptor(); + typeDescNode = (TypeDescriptorNode) internalTypeDesc; + } + typeDescriptorNodes.add(typeDescNode); + if (typeGenerator instanceof ArrayTypeGenerator && + !typeGenerator.getTypeDefinitionNodeList().isEmpty()) { + typeDefinitionNodeList.addAll(typeGenerator.getTypeDefinitionNodeList()); + } + } + return createUnionTypeNode(typeDescriptorNodes); + } + + private TypeDescriptorNode createUnionTypeNode(List typeDescNodes) { + if (typeDescNodes.isEmpty()) { + return null; + } else if (typeDescNodes.size() == 1) { + return typeDescNodes.get(0); + } + + // if any of the member subtypes is an optional type descriptor, simplify the resultant union type by + // extracting out the optional operators from all the member subtypes and, adding only to the last one. + // + // i.e: T1?|T2?|...|Tn? <=> T1|T2|...|Tn? + if (typeDescNodes.stream().anyMatch(node -> node.kind() == OPTIONAL_TYPE_DESC)) { + typeDescNodes = typeDescNodes.stream().map(node -> { + if (node instanceof OptionalTypeDescriptorNode) { + return (TypeDescriptorNode) ((OptionalTypeDescriptorNode) node).typeDescriptor(); + } else { + return node; + } + }).collect(Collectors.toList()); + + OptionalTypeDescriptorNode optionalTypeDesc = createOptionalTypeDescriptorNode( + typeDescNodes.get(typeDescNodes.size() - 1), createToken(QUESTION_MARK_TOKEN)); + typeDescNodes.set(typeDescNodes.size() - 1, optionalTypeDesc); + } + + UnionTypeDescriptorNode unionTypeDescNode = null; + TypeDescriptorNode leftTypeDesc = typeDescNodes.get(0); + for (int i = 1; i < typeDescNodes.size(); i++) { + TypeDescriptorNode rightTypeDesc = typeDescNodes.get(i); + unionTypeDescNode = createUnionTypeDescriptorNode(leftTypeDesc, createToken(PIPE_TOKEN), rightTypeDesc); + leftTypeDesc = unionTypeDescNode; + } + return unionTypeDescNode; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/model/GeneratorMetaData.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/model/GeneratorMetaData.java new file mode 100644 index 000000000..cc069f965 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/model/GeneratorMetaData.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.model; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; + +/** + * Stores metadata related to Ballerina types generation. + * + */ +public class GeneratorMetaData { + + private static GeneratorMetaData generatorMetaData = null; + private final AsyncApi25DocumentImpl asyncAPI; + + private GeneratorMetaData(AsyncApi25DocumentImpl asyncAPI) { + this.asyncAPI = asyncAPI; + } + + public static void createInstance(AsyncApi25DocumentImpl asyncAPI) { + generatorMetaData = new GeneratorMetaData(asyncAPI); + } + + public static GeneratorMetaData getInstance() { + return generatorMetaData; + } + + public AsyncApi25DocumentImpl getAsyncAPI() { + return asyncAPI; + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/model/RecordMetadata.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/model/RecordMetadata.java new file mode 100644 index 000000000..001e8985b --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/generators/schema/model/RecordMetadata.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.generators.schema.model; + +import io.ballerina.compiler.syntax.tree.RecordRestDescriptorNode; + +/** + * RecordMetadata class for containing the details to generate record node. This contains the details with whether + * record is opened record or not, and its restField details. + * + */ +public class RecordMetadata { + private final boolean isOpenRecord; + private final RecordRestDescriptorNode restDescriptorNode; + + RecordMetadata(Builder builder) { + this.isOpenRecord = builder.isOpenRecord; + this.restDescriptorNode = builder.restDescriptorNode; + } + + public boolean isOpenRecord() { + return isOpenRecord; + } + + public RecordRestDescriptorNode getRestDescriptorNode() { + return restDescriptorNode; + } + + public static class Builder { + private boolean isOpenRecord = false; + private RecordRestDescriptorNode restDescriptorNode = null; + + public Builder withIsOpenRecord(boolean isOpenRecord) { + this.isOpenRecord = isOpenRecord; + return this; + } + + public Builder withRestDescriptorNode(RecordRestDescriptorNode restDescriptorNode) { + this.restDescriptorNode = restDescriptorNode; + return this; + } + + public RecordMetadata build() { + return new RecordMetadata(this); + } + } +} diff --git a/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/model/GenSrcFile.java b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/model/GenSrcFile.java new file mode 100644 index 000000000..d9c551a82 --- /dev/null +++ b/asyncapi-cli/src/main/java/io/ballerina/asyncapi/websocketscore/model/GenSrcFile.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.websocketscore.model; + +/** + * Model class to hold generated source file information. + * + */ +public class GenSrcFile { + private String content; + private String fileName; + private GenFileType type; + + /** + * Type specifier for generated source files. + */ + public enum GenFileType { + GEN_SRC, + MODEL_SRC, + IMPL_SRC, + TEST_SRC, + CONFIG_SRC, + RES, + UTIL_SRC; + + public boolean isOverwritable() { + if (this == GEN_SRC || this == RES || this == MODEL_SRC || this == UTIL_SRC) { + return true; + } + return false; + } + } + + public GenSrcFile(GenFileType type, String fileName, String content) { + this.type = type; + this.fileName = fileName; + this.content = content; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public GenFileType getType() { + return type; + } + + public void setType(GenFileType type) { + this.type = type; + } +} diff --git a/asyncapi-cli/src/main/java/module-info.java b/asyncapi-cli/src/main/java/module-info.java index 6e9ee7562..e512f7841 100644 --- a/asyncapi-cli/src/main/java/module-info.java +++ b/asyncapi-cli/src/main/java/module-info.java @@ -5,7 +5,12 @@ requires io.ballerina.tools.api; requires io.ballerina.parser; requires io.ballerina.formatter.core; + requires io.ballerina.runtime; requires org.apache.commons.io; requires com.fasterxml.jackson.databind; requires com.fasterxml.jackson.dataformat.yaml; + requires java.sql; + requires io.ballerina.lang; + requires org.apache.commons.lang3; + requires org.slf4j; } diff --git a/asyncapi-cli/src/main/resources/config_toml_files/api_key_config.toml b/asyncapi-cli/src/main/resources/config_toml_files/api_key_config.toml new file mode 100644 index 000000000..938f3aea8 --- /dev/null +++ b/asyncapi-cli/src/main/resources/config_toml_files/api_key_config.toml @@ -0,0 +1,2 @@ +[apiKeyConfig.apiKeys] +YOUR-API-KEY-1 = "" diff --git a/asyncapi-cli/src/main/resources/config_toml_files/basic_config.toml b/asyncapi-cli/src/main/resources/config_toml_files/basic_config.toml new file mode 100644 index 000000000..fa803ae0d --- /dev/null +++ b/asyncapi-cli/src/main/resources/config_toml_files/basic_config.toml @@ -0,0 +1,3 @@ +[authConfig] +username = "" +password = "" diff --git a/asyncapi-cli/src/main/resources/config_toml_files/bearer_config.toml b/asyncapi-cli/src/main/resources/config_toml_files/bearer_config.toml new file mode 100644 index 000000000..9198c55d7 --- /dev/null +++ b/asyncapi-cli/src/main/resources/config_toml_files/bearer_config.toml @@ -0,0 +1,2 @@ +[authConfig] +token = "" diff --git a/asyncapi-cli/src/main/resources/config_toml_files/client_credentials_config.toml b/asyncapi-cli/src/main/resources/config_toml_files/client_credentials_config.toml new file mode 100644 index 000000000..f868d79bc --- /dev/null +++ b/asyncapi-cli/src/main/resources/config_toml_files/client_credentials_config.toml @@ -0,0 +1,4 @@ +[authConfig] +tokenUrl = "" +clientId = "" +clientSecret = "" diff --git a/asyncapi-cli/src/main/resources/config_toml_files/password_config.toml b/asyncapi-cli/src/main/resources/config_toml_files/password_config.toml new file mode 100644 index 000000000..97fab5220 --- /dev/null +++ b/asyncapi-cli/src/main/resources/config_toml_files/password_config.toml @@ -0,0 +1,4 @@ +[authConfig] +tokenUrl = "" +username = "" +password = "" diff --git a/asyncapi-cli/src/main/resources/config_toml_files/refresh_token_config.toml b/asyncapi-cli/src/main/resources/config_toml_files/refresh_token_config.toml new file mode 100644 index 000000000..ad4a4c35a --- /dev/null +++ b/asyncapi-cli/src/main/resources/config_toml_files/refresh_token_config.toml @@ -0,0 +1,5 @@ +[authConfig] +refreshUrl = "" +refreshToken = "" +clientId = "" +clientSecret = "" diff --git a/asyncapi-cli/src/main/resources/templates/utils_asyncapi.bal b/asyncapi-cli/src/main/resources/templates/utils_asyncapi.bal new file mode 100644 index 000000000..aedccdeb0 --- /dev/null +++ b/asyncapi-cli/src/main/resources/templates/utils_asyncapi.bal @@ -0,0 +1,130 @@ +import ballerina/url; +import xlibb/pipe; + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# StreamGeneratorsMap class to handle generated stream generators +public isolated class StreamGeneratorsMap { + private final Generator[] streamGenerators; + public isolated function init() { + self.streamGenerators = []; + } + + public isolated function addStreamGenerator(Generator streamGenerator) { + lock { + self.streamGenerators.push(streamGenerator); + } + } + public isolated function removeStreamGenerators() returns error? { + lock { + foreach Generator streamGenerator in self.streamGenerators { + check streamGenerator.close(); + } + } + } +} + + +# Generator object type for type inclusion +public type Generator isolated object { + public isolated function next() returns record {|anydata value;|}|error; + public isolated function close() returns error?; +}; + + + +public type SimpleBasicType string|boolean|int|float|decimal; + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +public isolated function getEncodedUri(anydata value) returns string { + string|error encoded = url:encode(value.toString(), "UTF8"); + if (encoded is string) { + return encoded; + } else { + return value.toString(); + } +} + +# Generate query path with query parameter. +# +# + queryParam - Query parameter map +# + return - Returns generated Path or error at failure of client initialization +public isolated function getPathForQueryParam(map queryParam) returns string|error { + string[] param = []; + if (queryParam.length() > 0) { + param.push("?"); + foreach var [key, value] in queryParam.entries() { + if value is () { + _ = queryParam.remove(key); + continue; + } + if (value is SimpleBasicType) { + param.push(key, "=", getEncodedUri(value.toString())); + + } else { + param.push(key, "=", value.toString()); + } + param.push("&"); + } + _ = param.pop(); + } + string restOfPath = string:'join("", ...param); + return restOfPath; +} + + +# Combine custom headers and param headers +# +# + customHeaders - Custom headers map +# + paramHeaders - Headers generated using spec +# + return - Return combine custom and spec generated headers +public isolated function getCombineHeaders(map customHeaders, map paramHeaders) returns map { + foreach [string, string] [k, v] in paramHeaders.entries() { + customHeaders[k] = v; + } + return customHeaders; +} + + diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/AsyncApiWsCommandTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/AsyncApiWsCommandTest.java new file mode 100644 index 000000000..ac1d455d7 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/AsyncApiWsCommandTest.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * AsyncAPI command cmd common class to handle temp dirs and outputs. + */ +public abstract class AsyncApiWsCommandTest { + protected Path tmpDir; + protected final Path resourceDir = Paths.get("src/test/resources/websockets").toAbsolutePath(); + protected ByteArrayOutputStream console; + private final PrintStream originalOut = System.out; + + @BeforeClass + public void setup() throws IOException { + this.tmpDir = Files.createTempDirectory("asyncapi-cmd-test-out-" + System.nanoTime()); + this.console = new ByteArrayOutputStream(); + } + + @BeforeMethod + public void init() { + System.setErr(new PrintStream(this.console)); + } + + @AfterMethod + public void cleanup() throws IOException { + System.setErr(originalOut); + } + + protected String readOutput(boolean silent) throws IOException { + String output = this.console.toString(); + this.console.close(); + this.console = new ByteArrayOutputStream(); + if (!silent) { + PrintStream out = System.out; + out.println(output); + } + return output; + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/BallerinaToAsyncApiWsExceptionTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/BallerinaToAsyncApiWsExceptionTests.java new file mode 100644 index 000000000..388220fa2 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/BallerinaToAsyncApiWsExceptionTests.java @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd; + +import io.ballerina.cli.launcher.BLauncherException; +import org.testng.Assert; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import picocli.CommandLine; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHERKEY_NOT_PRESENT_IN_RECORD_FIELD; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHERKEY_NULLABLE_EXCEPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHERKEY_OPTIONAL_EXCEPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_KEY_TYPE_EXCEPTION; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.DISPATCHER_KEY_VALUE_CANNOT_BE_EMPTY; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FUNCTION_SIGNATURE_WRONG_TYPE; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.FUNCTION_WRONG_NAME; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_ANNOTATION_PRESENT; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_DISPATCHER_KEY; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.NO_SERVICE_CLASS; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.PATH_PARAM_DASH_CONTAIN_ERROR; + + +/** + * This {@code BallerinaToAsyncAPIExceptionTests} represents the tests for all the exceptions in the + * ballerina to asyncapi command. + * + */ +public class BallerinaToAsyncApiWsExceptionTests extends AsyncApiWsCommandTest { + + @BeforeTest(description = "This will create a new ballerina project for testing below scenarios.") + public void setupBallerinaProject() throws IOException { + super.setup(); + } + + @Test(description = "Test websocket:serviceConfig annotation not present exception") + public void testWebsocketServiceConfigAnnotationNotPresent() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/check_websocket_serviceConfig_annotation.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(NO_ANNOTATION_PRESENT)); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test dispatcherKey is not present in a record field") + public void testDispatcherKeyFieldNotPresentInEachRecord() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/dispatcherKey_field_not_present_in_record.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains( + String.format(DISPATCHERKEY_NOT_PRESENT_IN_RECORD_FIELD, "event", "Subscribe"))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test dispatcherKey is not string type in a record field") + public void testDispatcherKeyFieldIsNotStringType() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/dispatcherKey_field_string_type_check.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(DISPATCHER_KEY_TYPE_EXCEPTION, "event"))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test dispatcherKey field is not present in annotation ") + public void testDispatcherKeyFieldIsNotPresentInAnnotation() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/dispatcherKey_field_not_present_in_annotation.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(NO_DISPATCHER_KEY))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test dispatcherKey is empty") + public void testDispatcherKeyIsEmpty() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/empty_dispatcherKey_check.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(DISPATCHER_KEY_VALUE_CANNOT_BE_EMPTY))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test service class is not called") + public void testNoServiceClassPresent() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/no_service_class_present.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(NO_SERVICE_CLASS))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } +// +// @Test(description = "Test onClose remote function is present as a remote function") +// public void testOnCloseRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onClose_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onError remote function is present as a remote function") +// public void testOnErrorRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onError_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onIdleTimeOut remote function is present as a remote function") +// public void testOnIdleTimeOutRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onIdleTimeOut_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onTextMessage remote function is present as a remote function") +// public void testOnTextMessageRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onTextMessage_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onBinaryMessage remote function is present as a remote function") +// public void testOnBinaryMessageRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onBinaryMessage_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onOpen remote function is present as a remote function") +// public void testOnOpenRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onOpen_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// +// @Test(description = "Test onMessage remote function is present as a remote function") +// public void testOnMessageRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onMessage_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onPing remote function is present as a remote function") +// public void testOnPingRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onPing_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } +// +// @Test(description = "Test onPong remote function is present as a remote function") +// public void testOnPongRemoteFunctionNotPermitted() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/onPong_check.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(FUNCTION_DEFAULT_NAME_CONTAINS_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } + + @Test(description = "Test dispatcherKey is optional not allowed in a field") + public void testDispatcherKeyIsOptionalNotAllowedInAField() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/optional_dispatcherKey_present.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(DISPATCHERKEY_OPTIONAL_EXCEPTION, + "event", "Subscribe"))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test dispatcherKey is nullable not allowed in a field") + public void testDispatcherKeyIsNullableNotAllowedInAField() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/nullable_dispatcherKey_present.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(DISPATCHERKEY_NULLABLE_EXCEPTION, + "event", "Subscribe"))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test remote function name is not in camel case form") + public void testRemoteFunctionNameCamelCaseNotPresent() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/remotefunction_camelCase_not_present.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(FUNCTION_WRONG_NAME)); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test remote function name is not start with onPrefix") + public void testRemoteFunctionNameNotStartWithOnPrefix() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/remoteFunction_name_start.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(FUNCTION_WRONG_NAME)); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test remote function request type is not a record a type") + public void testRequestTypeRecordNotPresent() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/request_type_record_check.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(String.format(FUNCTION_SIGNATURE_WRONG_TYPE, + "Subscribe", "int"))); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Test path param contains dash character") + public void testPathParamDashContain() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + + "/path_param_dash_contain.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--protocol", "ws"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + Assert.assertTrue(readOutput(true).trim().contains(PATH_PARAM_DASH_CONTAIN_ERROR)); + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + +// @Test(description = "Test remote function returns multiple return options with stream type") +// public void testMultipleReturnTypesIncludingStreamTypeError() { +// Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/exceptions" + +// "/optional_multiple_type_stream_include_return.bal")); +// String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; +// AsyncAPICmd cmd = new AsyncAPICmd(printStream, tmpDir, false); +// new CommandLine(cmd).parseArgs(args); +// +// String output = ""; +// try { +// cmd.execute(); +// output = readOutput(true); +// Assert.assertTrue(output.trim().contains(String.format(UNION_STREAMING_SIMPLE_RPC_ERROR))); +// } catch (BLauncherException | IOException e) { +// output = e.toString(); +// Assert.fail(output); +// } +// } + + +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/BallerinaToAsyncApiWsTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/BallerinaToAsyncApiWsTests.java new file mode 100644 index 000000000..fd4ca64bb --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/cmd/BallerinaToAsyncApiWsTests.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.cmd; + +import io.ballerina.cli.launcher.BLauncherException; +import org.testng.Assert; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import picocli.CommandLine; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * This {@code BallerinaToAsyncAPITests} represents the tests for all the special scenarios in the ballerina to asyncapi + * command. + * + */ +public class BallerinaToAsyncApiWsTests extends AsyncApiWsCommandTest { + + @BeforeTest(description = "This will create a new ballerina project for testing below scenarios.") + public void setupBallerinaProject() throws IOException { + super.setup(); + } + + @Test(description = "Test ballerina to asyncApi") + public void testBallerinaToAsyncAPIGeneration() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/ballerina-file.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + } catch (BLauncherException e) { + Assert.fail(e.getDetailedMessages().get(0)); + } + } + + @Test(description = "Without asyncapi annotation ballerina to asyncapi") + public void asyncapiAnnotationWithOutContract() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/project_2/service.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + String output = readOutput(true); + Path definitionPath = resourceDir.resolve("cmd/ballerina-to-asyncapi/project_2/result.yaml"); + if (Files.exists(this.tmpDir.resolve("service_asyncapi.yaml"))) { + String generatedAsyncAPI = getStringFromGivenBalFile(this.tmpDir.resolve("service_asyncapi.yaml")); + String expectedYaml = getStringFromGivenBalFile(definitionPath); + Assert.assertEquals(expectedYaml, generatedAsyncAPI); + } + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + @Test(description = "Ballerina to asyncapi json file generation") + public void asyncApiJsonGeneration() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/normal_service.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString(), "--json"}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + String output = readOutput(true); + Path definitionPath = resourceDir.resolve("cmd/ballerina-to-asyncapi/normal_service.json"); + if (Files.exists(this.tmpDir.resolve("payloadV_asyncapi1.json"))) { + String generatedAsyncAPI = getStringFromGivenBalFile(this.tmpDir.resolve("payloadV_asyncapi1.json")); + String expectedYaml = getStringFromGivenBalFile(definitionPath); + Assert.assertEquals(expectedYaml, generatedAsyncAPI); + } + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + + @Test(description = "AsyncAPI Annotation with ballerina to asyncapi", enabled = false) + public void asyncapiAnnotationWithContract() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/project1/service.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + String output = readOutput(true); + Path definitionPath = resourceDir.resolve("cmd/ballerina-to-asyncapi/project_1/result.yaml"); + if (Files.exists(this.tmpDir.resolve("service_asyncapi.yaml"))) { + String generatedAsyncAPI = getStringFromGivenBalFile(this.tmpDir.resolve("service_asyncapi.yaml")); + String expectedYaml = getStringFromGivenBalFile(definitionPath); + Assert.assertEquals(expectedYaml, generatedAsyncAPI); + + } + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + + @Test(description = "AsyncAPI Annotation with ballerina to asyncapi", enabled = false) + public void asyncapiAnnotationWithoutFields() { + Path filePath = resourceDir.resolve(Paths.get("cmd/ballerina-to-asyncapi/project_3/service.bal")); + String[] args = {"--input", filePath.toString(), "-o", this.tmpDir.toString()}; + AsyncApiCmd cmd = new AsyncApiCmd(tmpDir, false); + new CommandLine(cmd).parseArgs(args); + try { + cmd.execute(); + String output = readOutput(true); + Path definitionPath = resourceDir.resolve("cmd/ballerina-to-asyncapi/project_3/result.yaml"); + if (Files.exists(this.tmpDir.resolve("service_asyncapi.yaml"))) { + String generatedAsyncAPI = getStringFromGivenBalFile(this.tmpDir.resolve("service_asyncapi.yaml")); + String expectedYaml = getStringFromGivenBalFile(definitionPath); + Assert.assertEquals(expectedYaml, generatedAsyncAPI); + } + } catch (BLauncherException | IOException e) { + Assert.fail(e.getMessage()); + } + } + + private String getStringFromGivenBalFile(Path expectedServiceFile) throws IOException { + Stream expectedServiceLines = Files.lines(expectedServiceFile); + String expectedServiceContent = expectedServiceLines.collect(Collectors.joining(System.lineSeparator())); + expectedServiceLines.close(); + return expectedServiceContent.trim().replaceAll("\\s+", "").replaceAll(System.lineSeparator(), ""); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpecTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpecTest.java index e11aea250..9c2eee282 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpecTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractChannelsFromSpecTest.java @@ -19,8 +19,7 @@ package io.ballerina.asyncapi.codegenerator.usecase; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.entity.MultiChannel; import io.ballerina.asyncapi.codegenerator.entity.RemoteFunction; @@ -46,7 +45,7 @@ public void testExtractWithOneChannel() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-channel.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); MultiChannel multiChannel = extractServiceTypes.extract(); List serviceTypes = multiChannel.getServiceTypes(); @@ -65,7 +64,7 @@ public void testExtractWithOneChannelWithInlineSchemas() throws BallerinaAsyncAp String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-channel-with-inline-schema.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); MultiChannel multiChannel = extractServiceTypes.extract(); List serviceTypes = multiChannel.getServiceTypes(); @@ -83,7 +82,7 @@ public void testExtractWithMultipleChannels() throws BallerinaAsyncApiException String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-multiple-channels.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); MultiChannel multiChannel = extractServiceTypes.extract(); List serviceTypes = multiChannel.getServiceTypes(); @@ -111,7 +110,7 @@ public void testExtractWithMissingXServiceType() throws BallerinaAsyncApiExcepti String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-channel-missing-x-service-type.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); MultiChannel multiChannel = extractServiceTypes.extract(); List serviceTypes = multiChannel.getServiceTypes(); @@ -134,7 +133,7 @@ public void testExtractWithMissingXEventTypeWithOneOf() throws BallerinaAsyncApi String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-channel-missing-x-event-type-with-oneof.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); extractServiceTypes.extract(); } @@ -150,7 +149,7 @@ public void testExtractWithMissingXEventTypeWithoutOneOf() throws BallerinaAsync String asyncApiSpecStr = fileRepository.getFileContentFromResources( "specs/spec-single-channel-missing-x-event-type-without-oneof.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); extractServiceTypes.extract(); } @@ -166,7 +165,7 @@ public void testExtractWithMissingPayload() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository.getFileContentFromResources( "specs/spec-single-channel-missing-reference.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); extractServiceTypes.extract(); } @@ -182,7 +181,7 @@ public void testExtractWithNullPayload() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository.getFileContentFromResources( "specs/spec-single-channel-missing-payload.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractServiceTypes = new ExtractChannelsFromSpec(asyncApiSpec); extractServiceTypes.extract(); } diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractHeaderTypeEventIdentifierFromSpecTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractHeaderTypeEventIdentifierFromSpecTest.java index 9e8562ef5..3ba7c104c 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractHeaderTypeEventIdentifierFromSpecTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractHeaderTypeEventIdentifierFromSpecTest.java @@ -1,8 +1,7 @@ package io.ballerina.asyncapi.codegenerator.usecase; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; @@ -24,7 +23,7 @@ public void testExtractWithIdentifierPathValidHeaderType() throws BallerinaAsync String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-with-event-identifier-valid-header-type.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierPathFromSpec = new ExtractIdentifierPathFromSpec(asyncApiSpec); String identifierPath = extractIdentifierPathFromSpec.extract(); @@ -44,7 +43,7 @@ public void testExtractWithIdentifierPathMissingHeaderName() throws BallerinaAsy String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-with-event-identifier-missing-header-name.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierPathFromSpec = new ExtractIdentifierPathFromSpec(asyncApiSpec); extractIdentifierPathFromSpec.extract(); } diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpecTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpecTest.java index eee768e0f..bcf1429a4 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpecTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierPathFromSpecTest.java @@ -19,8 +19,7 @@ package io.ballerina.asyncapi.codegenerator.usecase; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; @@ -41,7 +40,7 @@ public void testExtractWithIdentifierPath() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-with-identifier-path.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierPathFromSpec = new ExtractIdentifierPathFromSpec(asyncApiSpec); String identifierPath = extractIdentifierPathFromSpec.extract(); @@ -60,7 +59,7 @@ public void testExtractWithIdentifierPathMissingPath() throws BallerinaAsyncApiE String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-with-identifier-path-missing-path.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierPathFromSpec = new ExtractIdentifierPathFromSpec(asyncApiSpec); extractIdentifierPathFromSpec.extract(); } diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpecTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpecTest.java index 615a55645..b0ec04a1c 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpecTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractIdentifierTypeFromSpecTest.java @@ -19,8 +19,7 @@ package io.ballerina.asyncapi.codegenerator.usecase; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; @@ -43,7 +42,7 @@ public void testExtractWithoutIdentifierPath() throws BallerinaAsyncApiException String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-without-identifier-path.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierTypeFromSpec = new ExtractIdentifierTypeFromSpec(asyncApiSpec); extractIdentifierTypeFromSpec.extract(); } @@ -60,7 +59,7 @@ public void testExtractWithIdentifierPathMissingType() throws BallerinaAsyncApiE String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-with-identifier-path-missing-type.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierTypeFromSpec = new ExtractIdentifierTypeFromSpec(asyncApiSpec); extractIdentifierTypeFromSpec.extract(); } @@ -77,7 +76,7 @@ public void testExtractWithIdentifierPathInvalidType() throws BallerinaAsyncApiE String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-with-event-identifier-invalid-type.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractIdentifierTypeFromSpec = new ExtractIdentifierTypeFromSpec(asyncApiSpec); extractIdentifierTypeFromSpec.extract(); } diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpecTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpecTest.java index f03bc5f83..0d8485b72 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpecTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/ExtractSchemasFromSpecTest.java @@ -18,12 +18,11 @@ package io.ballerina.asyncapi.codegenerator.usecase; -import com.fasterxml.jackson.databind.node.TextNode; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.Referenceable; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; import org.testng.Assert; @@ -45,22 +44,20 @@ public void testExtractWithOneSchema() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); Assert.assertEquals(schemas.get("GenericEventWrapper").getTitle(), "Standard event wrapper for the Events API"); - Assert.assertEquals(schemas.get("GenericEventWrapper").getSchemaProperties().get("api_app_id").getType(), - "string"); + Assert.assertEquals(((AsyncApiSchema) schemas.get("GenericEventWrapper").getProperties().get("api_app_id")) + .getType(), "string"); + Assert.assertEquals(((AsyncApiSchema) schemas.get("GenericEventWrapper") + .getProperties().get("event").getProperties().get("type")).getType(), "string"); + Assert.assertEquals(((AsyncApiSchema) schemas.get("GenericEventWrapper") + .getProperties().get("event").getProperties().get("type")).getType(), "string"); Assert.assertEquals(schemas.get("GenericEventWrapper") - .getSchemaProperties().get("event").getSchemaProperties().get("type").getType(), - "string"); - Assert.assertEquals(schemas.get("GenericEventWrapper") - .getSchemaProperties().get("event").getSchemaProperties().get("type").getType(), - "string"); - Assert.assertEquals(schemas.get("GenericEventWrapper") - .getSchemaProperties().get("event").getSchemaProperties().get("type").getTitle(), + .getProperties().get("event").getProperties().get("type").getTitle(), "The specific name of the event"); } @@ -72,18 +69,14 @@ public void testExtractWithEnums() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema-with-enum.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Assert.assertEquals(((TextNode) schemas.get("occupancyStatus").getEnum().get(0)).textValue(), - "EMPTY"); - Assert.assertEquals(((TextNode) schemas.get("occupancyStatus").getEnum().get(1)).textValue(), - "MANY_SEATS_AVAILABLE"); - Assert.assertEquals(((TextNode) schemas.get("occupancyStatus").getEnum().get(5)).textValue(), - "FULL"); - Assert.assertEquals(((TextNode) schemas.get("occupancyStatus").getEnum().get(6)).textValue(), - "NOT_ACCEPTING_PASSENGERS"); + Assert.assertEquals(schemas.get("occupancyStatus").getEnum().get(0).textValue(), "EMPTY"); + Assert.assertEquals(schemas.get("occupancyStatus").getEnum().get(1).textValue(), "MANY_SEATS_AVAILABLE"); + Assert.assertEquals(schemas.get("occupancyStatus").getEnum().get(5).textValue(), "FULL"); + Assert.assertEquals(schemas.get("occupancyStatus").getEnum().get(6).textValue(), "NOT_ACCEPTING_PASSENGERS"); } @Test( @@ -94,29 +87,26 @@ public void testExtractWithMultipleSchemas() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-multiple-schemas.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map serviceTypes = extractSchemasFromSpec.extract(); + Map serviceTypes = extractSchemasFromSpec.extract(); Assert.assertEquals(serviceTypes.get("GenericEventWrapper").getTitle(), "Standard event wrapper for the Events API"); - Assert.assertEquals(serviceTypes.get("GenericEventWrapper").getSchemaProperties().get("api_app_id").getType(), - "string"); - Assert.assertEquals(serviceTypes.get("GenericEventWrapper") - .getSchemaProperties().get("event").getSchemaProperties().get("type").getType(), - "string"); + Assert.assertEquals(((AsyncApiSchema) serviceTypes.get("GenericEventWrapper").getProperties() + .get("api_app_id")).getType(), "string"); + Assert.assertEquals(((AsyncApiSchema) serviceTypes.get("GenericEventWrapper") + .getProperties().get("event").getProperties().get("type")).getType(), "string"); + Assert.assertEquals(((AsyncApiSchema) serviceTypes.get("GenericEventWrapper") + .getProperties().get("event").getProperties().get("type")).getType(), "string"); Assert.assertEquals(serviceTypes.get("GenericEventWrapper") - .getSchemaProperties().get("event").getSchemaProperties().get("type").getType(), - "string"); - Assert.assertEquals(serviceTypes.get("GenericEventWrapper") - .getSchemaProperties().get("event").getSchemaProperties().get("type").getTitle(), + .getProperties().get("event").getProperties().get("type").getTitle(), "The specific name of the event"); - Assert.assertEquals(serviceTypes.get("CustomTestSchema") - .getSchemaProperties().get("test_id").getType(), "string"); - Assert.assertEquals(serviceTypes.get("GenericEventWrapper") - .getSchemaProperties().get("custom_test_schema").getRef(), - "#/components/schemas/CustomTestSchema"); + Assert.assertEquals(((AsyncApiSchema) serviceTypes.get("CustomTestSchema") + .getProperties().get("test_id")).getType(), "string"); + Assert.assertEquals(((Referenceable) serviceTypes.get("GenericEventWrapper").getProperties() + .get("custom_test_schema")).get$ref(), "#/components/schemas/CustomTestSchema"); } } diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNodeTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNodeTest.java index c6a4a7d32..899d1fff2 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNodeTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateModuleMemberDeclarationNodeTest.java @@ -19,10 +19,9 @@ package io.ballerina.asyncapi.codegenerator.usecase; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; import io.ballerina.compiler.syntax.tree.EnumDeclarationNode; @@ -47,11 +46,11 @@ public void testGenerateWithSingleSchema() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Map.Entry entry = schemas.entrySet().iterator().next(); + Map.Entry entry = schemas.entrySet().iterator().next(); Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(entry); TypeDefinitionNode typeDefinitionNode = generateRecordNode.generate(); @@ -59,13 +58,12 @@ public void testGenerateWithSingleSchema() throws BallerinaAsyncApiException { Assert.assertTrue(typeDefinitionNode.typeDescriptor() instanceof RecordTypeDescriptorNode); RecordTypeDescriptorNode recordTypeDescriptorNode = (RecordTypeDescriptorNode) typeDefinitionNode.typeDescriptor(); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(0)).fieldName().text(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(1)).fieldName().text(), "authed_users"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(4)).fieldName().text(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(2)).fieldName().text(), "event"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(4)).typeName().toSourceCode(), - "record { #When the event was dispatchedstringevent_ts;" + - "#The specific name of the eventstring'type;} "); + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(2)).typeName().toSourceCode(), + "record { #When the event was dispatchedstringevent_ts;#The specific name of the eventstring'type;} "); } @Test(description = "Test the functionality of the generate function " + @@ -74,11 +72,11 @@ public void testGenerateWithEnums() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema-with-enum.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Map.Entry entry = schemas.entrySet().iterator().next(); + Map.Entry entry = schemas.entrySet().iterator().next(); Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(entry); EnumDeclarationNode enumDeclarationNode = generateRecordNode.generate(); @@ -97,17 +95,17 @@ public void testGenerateWithMultipleSchemas() throws BallerinaAsyncApiException String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-multiple-schemas.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Iterator> iterator = schemas.entrySet().iterator(); - Map.Entry firstEntry = iterator.next(); + Iterator> iterator = schemas.entrySet().iterator(); + Map.Entry firstEntry = iterator.next(); Generator generateRecordNode1 = new GenerateModuleMemberDeclarationNode(firstEntry); TypeDefinitionNode typeDefinitionNode1 = generateRecordNode1.generate(); Assert.assertEquals(typeDefinitionNode1.typeName().text(), "CustomTestSchema"); - Map.Entry secondEntry = iterator.next(); + Map.Entry secondEntry = iterator.next(); Generator generateRecordNode2 = new GenerateModuleMemberDeclarationNode(secondEntry); TypeDefinitionNode typeDefinitionNode2 = generateRecordNode2.generate(); @@ -115,26 +113,26 @@ public void testGenerateWithMultipleSchemas() throws BallerinaAsyncApiException Assert.assertTrue(typeDefinitionNode2.typeDescriptor() instanceof RecordTypeDescriptorNode); RecordTypeDescriptorNode recordTypeDescriptorNode = (RecordTypeDescriptorNode) typeDefinitionNode2.typeDescriptor(); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(0)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(2)).typeName().toSourceCode(), "string[]"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(5)).fieldName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(8)).fieldName().toSourceCode(), "'type"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(8)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(18)).typeName().toSourceCode(), "record {}[]"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(10)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(16)).typeName().toSourceCode(), "CustomTestSchema[]"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(12)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(0)).typeName().toSourceCode(), "CustomTestSchema"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(15)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(3)).typeName().toSourceCode(), "record { #When the event was dispatchedstringevent_ts;" + "#The specific name of the eventstring'type;} "); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(17)).typeName().toSourceCode(), "string[][]"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(18)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(12)).typeName().toSourceCode(), "record {}"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(19)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(15)).typeName().toSourceCode(), "anydata"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(19)).fieldName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode.fields().get(15)).fieldName().toSourceCode(), "'anydata"); } @@ -146,11 +144,11 @@ public void testGenerateMissingItemAttributeInArray() throws BallerinaAsyncApiEx String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema-with-unrecognized-type.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Map.Entry entry = schemas.entrySet().iterator().next(); + Map.Entry entry = schemas.entrySet().iterator().next(); Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(entry); generateRecordNode.generate(); } @@ -163,11 +161,11 @@ public void testGenerateWithInvalidNumberFormat() throws BallerinaAsyncApiExcept String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema-with-invalid-number-format.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Map.Entry entry = schemas.entrySet().iterator().next(); + Map.Entry entry = schemas.entrySet().iterator().next(); Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(entry); generateRecordNode.generate(); } @@ -178,27 +176,27 @@ public void testGenerateWithNullables() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema-with-x-nullable.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Iterator> iterator = schemas.entrySet().iterator(); - Map.Entry firstEntry = iterator.next(); + Iterator> iterator = schemas.entrySet().iterator(); + Map.Entry firstEntry = iterator.next(); Generator generateRecordNode1 = new GenerateModuleMemberDeclarationNode(firstEntry); TypeDefinitionNode typeDefinitionNode1 = generateRecordNode1.generate(); Assert.assertEquals(typeDefinitionNode1.typeName().text(), "TotalPriceSet"); - Map.Entry secondEntry = iterator.next(); + Map.Entry secondEntry = iterator.next(); Generator generateRecordNode2 = new GenerateModuleMemberDeclarationNode(secondEntry); TypeDefinitionNode typeDefinitionNode2 = generateRecordNode2.generate(); Assert.assertEquals(typeDefinitionNode2.typeName().text(), "Price"); - Map.Entry thirdEntry = iterator.next(); + Map.Entry thirdEntry = iterator.next(); Generator generateRecordNode3 = new GenerateModuleMemberDeclarationNode(thirdEntry); TypeDefinitionNode typeDefinitionNode3 = generateRecordNode3.generate(); Assert.assertEquals(typeDefinitionNode3.typeName().text(), "OrderEvent"); - Map.Entry forthEntry = iterator.next(); + Map.Entry forthEntry = iterator.next(); Generator generateRecordNode4 = new GenerateModuleMemberDeclarationNode(forthEntry); TypeDefinitionNode typeDefinitionNode4 = generateRecordNode4.generate(); Assert.assertEquals(typeDefinitionNode4.typeName().text(), "TaxLine"); @@ -207,26 +205,26 @@ public void testGenerateWithNullables() throws BallerinaAsyncApiException { RecordTypeDescriptorNode recordTypeDescriptorNode3 = (RecordTypeDescriptorNode) typeDefinitionNode3.typeDescriptor(); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(0)).typeName().toSourceCode(), - "TotalPriceSet?"); + "int?"); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(1)).typeName().toSourceCode(), - "TaxLine[]?"); + "string?"); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(2)).typeName().toSourceCode(), - "decimal?"); + "boolean?"); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(3)).typeName().toSourceCode(), - "record { Priceshop_money?;Price?presentment_money?;} ?"); + "decimal?"); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(4)).typeName().toSourceCode(), - "int?"); + "TaxLine[]?"); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(5)).typeName().toSourceCode(), - "boolean?"); + "TotalPriceSet?"); Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode3.fields().get(6)).typeName().toSourceCode(), - "string?"); + "record { Priceshop_money?;Price?presentment_money?;} ?"); Assert.assertTrue(typeDefinitionNode4.typeDescriptor() instanceof RecordTypeDescriptorNode); RecordTypeDescriptorNode recordTypeDescriptorNode4 = (RecordTypeDescriptorNode) typeDefinitionNode4.typeDescriptor(); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode4.fields().get(2)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode4.fields().get(0)).typeName().toSourceCode(), "string"); - Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode4.fields().get(3)).typeName().toSourceCode(), + Assert.assertEquals(((RecordFieldNode) recordTypeDescriptorNode4.fields().get(2)).typeName().toSourceCode(), "string?"); } } diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateUnionDescriptorNodeTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateUnionDescriptorNodeTest.java index 332d74d72..570a48edc 100644 --- a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateUnionDescriptorNodeTest.java +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/codegenerator/usecase/GenerateUnionDescriptorNodeTest.java @@ -19,10 +19,9 @@ package io.ballerina.asyncapi.codegenerator.usecase; import io.apicurio.datamodels.Library; -import io.apicurio.datamodels.asyncapi.models.AaiDocument; -import io.apicurio.datamodels.asyncapi.v2.models.Aai20Document; +import io.apicurio.datamodels.models.asyncapi.AsyncApiDocument; +import io.apicurio.datamodels.models.asyncapi.AsyncApiSchema; import io.ballerina.asyncapi.codegenerator.configuration.BallerinaAsyncApiException; -import io.ballerina.asyncapi.codegenerator.entity.Schema; import io.ballerina.asyncapi.codegenerator.repository.FileRepository; import io.ballerina.asyncapi.codegenerator.repository.FileRepositoryImpl; import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; @@ -49,11 +48,11 @@ public void testGenerateWithOneNode() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-single-schema.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); - Map.Entry entry = schemas.entrySet().iterator().next(); + Map.Entry entry = schemas.entrySet().iterator().next(); Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(entry); TypeDefinitionNode typeDefinitionNode = generateRecordNode.generate(); List typeDescriptorNodes = new ArrayList<>(); @@ -75,12 +74,12 @@ public void testGenerateWithMultipleNode() throws BallerinaAsyncApiException { String asyncApiSpecStr = fileRepository .getFileContentFromResources("specs/spec-multiple-schemas.yml"); String asyncApiSpecJson = fileRepository.convertYamlToJson(asyncApiSpecStr); - AaiDocument asyncApiSpec = (Aai20Document) Library.readDocumentFromJSONString(asyncApiSpecJson); + AsyncApiDocument asyncApiSpec = (AsyncApiDocument) Library.readDocumentFromJSONString(asyncApiSpecJson); Extractor extractSchemasFromSpec = new ExtractSchemasFromSpec(asyncApiSpec); - Map schemas = extractSchemasFromSpec.extract(); + Map schemas = extractSchemasFromSpec.extract(); List typeDescriptorNodes = new ArrayList<>(); - for (Map.Entry fields : schemas.entrySet()) { + for (Map.Entry fields : schemas.entrySet()) { Generator generateRecordNode = new GenerateModuleMemberDeclarationNode(fields); TypeDefinitionNode typeDefinitionNode = generateRecordNode.generate(); typeDescriptorNodes.add( @@ -100,8 +99,7 @@ public void testGenerateWithMultipleNode() throws BallerinaAsyncApiException { @Test(description = "Test the functionality of the generate function " + "when the nodes list is empty", expectedExceptions = BallerinaAsyncApiException.class, - expectedExceptionsMessageRegExp = - "Nodes list is empty, hence can't generate the Union Node") + expectedExceptionsMessageRegExp = "Nodes list is empty, hence can't generate the Union Node") public void testGenerateWithEmptyRemoteFunctionsList() throws BallerinaAsyncApiException { Generator generateUnionDescriptorNode = new GenerateUnionDescriptorNode(new ArrayList<>(), "GenericDataType"); diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/APIDocTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/APIDocTests.java new file mode 100644 index 000000000..a43b0a240 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/APIDocTests.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class for the covering the unit tests for return type scenarios. + */ +public class APIDocTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Resource function api doc mapped to AAS operation summary") + public void testsForResourceFunction() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/resource_function_scenario.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/resource_function.yaml"); + } + + @Test(description = "Resource function api doc mapped to AAS operation summary") + public void testsForPathParameter() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/resource_function_with_pathparam_scenario.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/path_param.yaml"); + } + + @Test(description = "Query parameter api doc mapped to AAS parameter description") + public void testsForQueryParameter() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/resource_function_with_queryparam_scenario.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/query_param.yaml"); + } + + @Test(description = "Request payload api doc mapped to AAS requestBody description") + public void testsForRequestPayload() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/resource_function_with_request_scenario.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/request.yaml"); + } + + @Test(description = "Record api doc mapped to AAS record description") + public void testsForRecord() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/record.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/record.yaml"); + } + + @Test(description = "TypeInclusion record api doc mapped to AAS description") + public void testsForRecordHasTypeInclusion() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/typeInclusion.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/typeInclusion.yaml"); + } + + @Test(description = "Reference scenarios") + public void testsForReferenceScenario() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("apidoc/reference_scenario.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "apidoc/reference_scenario.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AdditionalTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AdditionalTests.java new file mode 100644 index 000000000..66571af14 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AdditionalTests.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This {@code AdditionalTests} test class for the covering the additional tests. + */ +public class AdditionalTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/additional").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "test to check if description has been overridden") + public void testRecordFieldDescriptionsOverrided() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("override_description_of_record.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "additional/override_description_of_record.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } + +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AdvanceTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AdvanceTests.java new file mode 100644 index 000000000..e3a626503 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AdvanceTests.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import io.ballerina.asyncapi.cmd.websockets.BallerinaToAsyncApiGenerator; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ASYNC_API_SUFFIX; +import static io.ballerina.asyncapi.wsgenerators.asyncapi.TestUtils.deleteDirectory; + +/** + * This test class contains the service nodes related special scenarios. + */ +public class AdvanceTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + private static final PrintStream outStream = System.out; + + private static String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { + Stream expectedServiceLines = Files.lines(expectedServiceFile.resolve(s)); + String expectedServiceContent = expectedServiceLines.collect(Collectors.joining("\n")); + expectedServiceLines.close(); + return expectedServiceContent; + } + + public static String findFile(Path dir, String dirName) { + FilenameFilter fileNameFilter = (dir1, name) -> name.startsWith(dirName); + String[] fileNames = Objects.requireNonNull(dir.toFile().list(fileNameFilter)); + return fileNames.length > 0 ? fileNames[0] : null; + } + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Multiple META-INF.services with same absolute path") + public void multipleServiceWithSameAbsolute() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("advance/multiple_services.bal"); + executeMethod(ballerinaFilePath, "multiple_service_empty_file.yaml", String.format("hello%s.yaml", + ASYNC_API_SUFFIX), "hello_"); + } + + @Test(description = "Multiple META-INF.services with absolute path as '/'. ") + public void multipleServiceWithOutAbsolute() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("advance/multiple_services_without_base_path.bal"); + executeMethod(ballerinaFilePath, "multiple_service_empty_file.yaml", String.format("multiple_services" + + "_without_base_path%s.yaml", ASYNC_API_SUFFIX), "multiple_services_without" + + "_base_path_"); + } + + @Test(description = "Multiple META-INF.services with no absolute path") + public void multipleServiceNoBasePath() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("advance/multiple_services_no_base_path.bal"); + executeMethod(ballerinaFilePath, "multiple_service_empty_file.yaml", String.format( + "multiple_services_no_base_path%s.yaml", ASYNC_API_SUFFIX), "multiple_services_no_base_path_"); + } + + + @Test(description = "When graphql protocol use as a sub-protocol over websocket") + public void testGraphqlOverWebsocket() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("advance/graphql_over_websocket.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "advance/graphql_over_websocket.yaml"); + } + + private void executeMethod(Path ballerinaFilePath, String yamlFile, String generatedYamlFile, + String secondGeneratedFile) throws IOException { + Path tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + try { + String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("yaml_outputs/service"), + yamlFile); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, + null, false, outStream); + + if (Files.exists(tempDir.resolve(generatedYamlFile)) && findFile(tempDir, secondGeneratedFile) != null) { + String generatedYaml = getStringFromGivenBalFile(tempDir, generatedYamlFile); + generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); + expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); + } else { + Assert.fail("Yaml was not generated, Ballerina service file might have compilation errors"); + } + } catch (IOException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteDirectory(tempDir); + System.gc(); + } + } + + @AfterMethod + public void cleanUp() { + deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AliasTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AliasTests.java new file mode 100644 index 000000000..ce6b0e4ce --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AliasTests.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This {@code AliasTests} contains all the alias related testings. + */ +public class AliasTests { + private static final Path RES_DIR = + Paths.get("src/test/resources/websockets/ballerina-to-asyncapi/alias").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Use websocket alias as ws") + public void notAcceptable() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("websocket.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "alias/websocket.yaml"); + } + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AsyncApiConverterUtilsTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AsyncApiConverterUtilsTest.java new file mode 100644 index 000000000..9c679eae4 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AsyncApiConverterUtilsTest.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import io.ballerina.asyncapi.cmd.websockets.BallerinaToAsyncApiGenerator; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ASYNC_API_SUFFIX; +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.utils.ConverterCommonUtils.unescapeIdentifier; +import static io.ballerina.asyncapi.wsgenerators.asyncapi.TestUtils.compareWithGeneratedFile; +import static io.ballerina.asyncapi.wsgenerators.asyncapi.TestUtils.deleteDirectory; +import static io.ballerina.asyncapi.wsgenerators.asyncapi.TestUtils.deleteGeneratedFiles; +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.getStringFromGivenBalFile; + + +/** + * Ballerina conversion to AsyncApi will test in this class. + */ +public class AsyncApiConverterUtilsTest { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + private PrintStream outStream = System.out; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Generate AsyncAPI spec") + public void testBasicServices() { + Path ballerinaFilePath = RES_DIR.resolve("service/basic_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, + this.tempDir, null, false, System.out); + + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("hello%s.yaml", ASYNC_API_SUFFIX)))); + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("hello02%s.yaml", ASYNC_API_SUFFIX)))); + } + + @Test(description = "Generate AsyncAPI spec by filtering non existing service") + public void testBasicServicesWithInvalidServiceName() { + Path ballerinaFilePath = RES_DIR.resolve("service/basic_service.bal"); + List errors = BallerinaToAsyncApiGenerator + .generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, "/abc", false, outStream); + Assert.assertFalse(errors.isEmpty()); + Assert.assertEquals(errors.get(0).getMessage(), + "No Ballerina service found with name '/abc' to generate an AsyncAPI specification. " + + "These are the available services: [/hello, /hello02]"); + } + + @Test(description = "Test if invalid 'exampleSetFlag' attribute is coming it the generated spec") + public void testIfExampleSetFlagContains() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("service/basic_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, + null, false, outStream); + + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("hello%s.yaml", ASYNC_API_SUFFIX)))); + Assert.assertFalse(Files.readString(this.tempDir.resolve(String.format("hello%s.yaml", + ASYNC_API_SUFFIX))).contains("exampleSetFlag")); + } + + @Test(description = "Generate AsyncAPI spec by filtering service name") + public void testBasicServicesByFiltering() { + Path ballerinaFilePath = RES_DIR.resolve("service/basic_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, + "/hello02", false, outStream); + + Assert.assertFalse(Files.exists(this.tempDir.resolve(String.format("hello%s.yaml", ASYNC_API_SUFFIX)))); + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("hello02%s.yaml", ASYNC_API_SUFFIX)))); + } + + @Test(description = "Generate AsyncAPI spec with complex base paths") + public void testComplexBasePathServices() { + Path ballerinaFilePath = RES_DIR.resolve("service/complex_base_path.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, + null, false, outStream); + + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("hello_foo_bar%s.yaml", + ASYNC_API_SUFFIX)))); + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("hello02_bar_baz%s.yaml", + ASYNC_API_SUFFIX)))); + } + + @Test(description = "Generate AsyncAPI spec with no base path") + public void testServicesWithNoBasePath() { + Path ballerinaFilePath = RES_DIR.resolve("service/no_base_path_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, + null, false, outStream); + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("no_base_path_service%s.yaml", + ASYNC_API_SUFFIX)))); + } + + @Test(description = "Generate AsyncAPI spec with no base path") + public void testServicesWithNoBasePathWithFilterina() { + Path ballerinaFilePath = RES_DIR.resolve("service/no_base_path_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, + "/", false, outStream); + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("no_base_path_service%s.yaml", + ASYNC_API_SUFFIX)))); + } + + @Test(description = "Generate AsyncAPI spec for build project") + public void testRecordFieldPayLoad() { + Path ballerinaFilePath = RES_DIR.resolve("service/project_bal/record_request_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, + null, false, outStream); + Assert.assertTrue(Files.exists(this.tempDir.resolve(String.format("payloadV%s.yaml", ASYNC_API_SUFFIX)))); + } + + @Test(description = "Generate AsyncAPI spec for given ballerina file has only compiler warning", enabled = false) + public void testForCompilerWarning() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("service/compiler_warning.bal"); + compareWithGeneratedFile(ballerinaFilePath, "service/compiler_warning.yaml"); + } + + @Test(description = "Test for non websocket rabbitmq service") + public void testForNonWebsocketRabbitMqServices() { + Path ballerinaFilePath = RES_DIR.resolve("service/rabbitmq_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, + null, false, outStream); + Assert.assertFalse(Files.exists(tempDir.resolve(String.format("query%s.yaml", ASYNC_API_SUFFIX)))); + } + + @Test(description = "Test for non websocket kafka service") + public void testForNonWebsocketKafkaServices() { + Path ballerinaFilePath = RES_DIR.resolve("service/kafka_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, + null, false, outStream); + Assert.assertFalse(Files.exists(tempDir.resolve(String.format("query%s.yaml", ASYNC_API_SUFFIX)))); + } + + + @Test(description = "Test for non websocket websubhub service") + public void testForNonWebsocketWebSubHubServices() { + Path ballerinaFilePath = RES_DIR.resolve("service/websubhub_service.bal"); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, + null, false, outStream); + Assert.assertFalse(Files.exists(tempDir.resolve(String.format("query%s.yaml", ASYNC_API_SUFFIX)))); + } + + //TODO : There was a bug in the lang for escape characters, + // it is now fixing and try this testing after the issue get fixed + // https://github.com/ballerina-platform/ballerina-lang/issues/39770 + // I have created the bal file, but yaml file has to be checked and created using debugger + @Test(description = "Given ballerina service has escape character", enabled = false) + public void testForRemovingEscapeIdentifier() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("service/escape_identifier.bal"); + Path tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + try { + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, null, + false, outStream); + if (Files.exists(tempDir.resolve(String.format("v1_abc_hello%s.yaml", ASYNC_API_SUFFIX)))) { + String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("yaml_outputs/service"), + "escape_identifier.yaml"); + String generatedYaml = getStringFromGivenBalFile(tempDir, String.format("v1_abc_hello%s.yaml", + ASYNC_API_SUFFIX)); + generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); + expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); + } else { + Assert.fail("Yaml was not generated"); + } + if (Files.exists(tempDir.resolve(String.format("limit%s.yaml", ASYNC_API_SUFFIX)))) { + String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("yaml_outputs/service"), + "escape_identifier_02.yaml"); + String generatedYaml = getStringFromGivenBalFile(tempDir, String.format("limit%s.yaml", + ASYNC_API_SUFFIX)); + generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); + expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); + } else { + Assert.fail("Yaml was not generated"); + } + } catch (IOException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteGeneratedFiles(String.format("v1_abc-hello%s.yaml", ASYNC_API_SUFFIX), tempDir); + deleteDirectory(tempDir); + System.gc(); + } + } + + @Test + public void testUnescapeIdentifiers() { + Assert.assertEquals(unescapeIdentifier("'limit"), "limit"); + Assert.assertEquals(unescapeIdentifier("x\\-client"), "x-client"); + Assert.assertEquals(unescapeIdentifier("/'limit"), "/limit"); + Assert.assertEquals(unescapeIdentifier("/'limit/x\\-cl"), "/limit/x-cl"); + Assert.assertEquals(unescapeIdentifier("'พิมพ์ชื่อ"), "พิมพ์ชื่อ"); + } + + @Test + public void testDecodeIdentifier() { + Assert.assertEquals(unescapeIdentifier("ชื่\\u{E2D}"), + "ชื่อ"); + } + + @AfterMethod + public void cleanUp() { + deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AsyncApiInfoTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AsyncApiInfoTests.java new file mode 100644 index 000000000..51a8b9553 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/AsyncApiInfoTests.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.asyncapi.TestUtils.compareWithGeneratedFile; + + +/** + * Tests for AsyncAPI info section mapping. + */ +public class AsyncApiInfoTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/asyncapi_info"). + toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Generate AsyncAPI spec with default value with empty Ballerina.toml", enabled = false) + public void defaultAsyncAPIInfo() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("project01/project01.bal"); + compareWithGeneratedFile(ballerinaFilePath, "asyncapi_info/project01.yaml"); + } + //TODO : Uncomment below testings after done the annotation of @asynapi:serviceInfo { } + +// @Test(description = "Generate AsyncAPI spec with default value with version Ballerina.toml") +// public void versionAsyncAPIInfo() throws IOException { +// Path ballerinaFilePath = RES_DIR.resolve("project02/project02.bal"); +// compareWithGeneratedFile(ballerinaFilePath, "asyncapi_info/project02.yaml"); +// } +// +// @Test(description = "Generate AsyncAPI spec with default value with version Ballerina.toml") +// public void asyncAPIAnnotation() throws IOException { +// Path ballerinaFilePath = RES_DIR.resolve("project03/project03.bal"); +// compareWithGeneratedFile(ballerinaFilePath, "asyncapi_info/project02.yaml"); +// } + + +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ChannelTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ChannelTests.java new file mode 100644 index 000000000..15aae5e08 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ChannelTests.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.asyncapi.TestUtils.compareWithGeneratedFile; + +/** + * This {@code ChannelTests} is for the covering the Channel tests for ballerina to asyncapi generation. + */ +public class ChannelTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/channels").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Generate AsyncAPI spec for resource has .") + public void testChannelScenario01() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("channel_scenario01.bal"); + compareWithGeneratedFile(ballerinaFilePath, "channels/channel_scenario01.yaml"); + } + + @Test(description = "Generate AsyncAPI spec for resource has path param and query param") + public void testChannelScenario02() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("channel_scenario02.bal"); + compareWithGeneratedFile(ballerinaFilePath, "channels/channel_scenario02.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with multipath including .") + public void testChannelScenario03() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("channel_scenario03.bal"); + compareWithGeneratedFile(ballerinaFilePath, "channels/channel_scenario03.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with path parameter including .") + public void testChannelScenario04() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("channel_scenario04.bal"); + compareWithGeneratedFile(ballerinaFilePath, "channels/channel_scenario04.yaml"); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/DataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/DataTypeTests.java new file mode 100644 index 000000000..1dc225644 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/DataTypeTests.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class is used to maintain test for datatype in ballerina. + */ +public class DataTypeTests { + private static final Path RES_DIR = + Paths.get("src/test/resources/websockets/ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "When the record field has type definitions") + public void testForAllTypeDefinitions() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/type_def.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/type_def.yaml"); + } + + @Test(description = "When the record field has type definitions with nullable") + public void testForAllTypeDefinitionWithNullableValue() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/nullable_type_def.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/nullable_type_def.yaml"); + } + + @Test(description = "test for tuple type scenarios") + public void testForTupleType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/tuple_types.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/tuple_type.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/EnumTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/EnumTypeTests.java new file mode 100644 index 000000000..3ecc226a5 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/EnumTypeTests.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class for the covering the unit tests for record scenarios. + */ +public class EnumTypeTests { + private static final Path RES_DIR = + Paths.get("src/test/resources/websockets/ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "When the record field has reference to enum type") + public void testEnumType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/enum.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/enum.yaml"); + } + + @Test(description = "When the record field has reference to enum type array") + public void testEnumTypeInArray() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/enum_array.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/enum_array.yaml"); + } + + @Test(description = "When the record field has reference to enum with constant value") + public void testEnumWithConstantValue() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/enum_with_constant_value.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/enum_with_constant_value.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/HeaderTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/HeaderTests.java new file mode 100644 index 000000000..00a9d88cd --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/HeaderTests.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Ballerina header conversion to AsyncAPI will test in this class. + */ +public class HeaderTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/headers").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Generate AsyncAPI spec with header type parameter") + public void testHeadscenario01() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario01.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario01.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with header type parameter with annotation values") + public void testHeadersWithAnnotation() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario02.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario02.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with header type parameter without curly brace") + public void testHeadersWithOutCurlyBrace() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario03.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario03.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with for multiple headers") + public void testWithMultipleHeaders() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario04.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario04.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with for optional headers") + public void testOptionalHeaders() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario05.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario05.yaml"); + } + + //TODO : Uncomment this after created treatNilableAsOptional +// @Test(description = "Generate AsyncAPI spec with when the service config has nullable and optional enable field") +// public void testHeadersWithAnnotations() throws IOException { +// Path ballerinaFilePath = RES_DIR.resolve("header_scenario06.bal"); +// TestUtils.compareWithGeneratedFile(ballerinaFilePath, "header_scenario06.yaml"); +// } + + @Test(description = "Generate AsyncAPI spec when the header has defaultable parameter") + public void testHeadersWithDefaultValue() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario07.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario07.yaml"); + } + + @Test(description = "Generate AsyncAPI spec when the header has defaultable parameter with nullable enable data " + + "type") + public void testHeadersWithDefaultValueWithNullable() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario08.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario08.yaml"); + } + + @Test(description = "Generate AsyncAPI spec when the header has defaultable parameter with nullable enable data " + + "type and service config enable", enabled = false) + public void testHeadersWithDefaultValueWithNullableServiceConfig() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario09.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario09.yaml"); + } + + @Test(description = "Tests for header parameter has default value as expression") + public void testHeaderWithDefaultExpressionValue() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario10.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario10.yaml"); + } + + @Test(description = "Tests for header parameters having int and boolean types with array, default and nullable " + + "scenarios") + public void testHeaderWithIntAndBoolean() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario11.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario11.yaml"); + } + + @Test(description = "Test for header parameters having boolean array type") + public void testBooleanHeaderArray() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario12.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario12.yaml"); + } + + @Test(description = "Generate AsyncAPI spec with header type parameter") + public void testHeadScenario13() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario13.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario13.yaml"); + } + @Test(description = "Generate AsyncAPI spec with header type parameter with annotation values") + public void testHeadScenario14() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario14.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario14.yaml"); + } + @Test(description = "Generate AsyncAPI spec with header type parameter with annotation values") + public void testHeadScenario15() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("header_scenario15.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "headers/header_scenario15.yaml"); + } + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ListenerTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ListenerTests.java new file mode 100644 index 000000000..d7a18bb86 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ListenerTests.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import io.ballerina.asyncapi.cmd.websockets.BallerinaToAsyncApiGenerator; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.service.AsyncApiEndpointMapper; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +/** + * This Test class for storing all the endpoint related tests + * {@link AsyncApiEndpointMapper}. + */ +public class ListenerTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/").toAbsolutePath(); + private Path tempDir; + private static final PrintStream outStream = System.out; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + //Listeners + @Test(description = "Generate AsyncAPI spec for single listener") + public void testListeners01() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario01.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario01.yaml"); + } + + @Test(description = "Generate AsyncAPI spec for listener only have port") + public void testListeners02() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario02.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario02.yaml"); + } + + @Test(description = "Generate AsyncAPI spec for multiple listeners") + public void testListeners03() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario03.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario03.yaml"); + } + + @Test(description = "Generate AsyncAPI spec for ExplicitNewExpressionNode listeners") + public void testListeners04() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario04.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario04.yaml"); + } + + @Test(description = "Generate AsyncAPI spec for multiple listeners") + public void testListeners05() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario05.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/listener_scenario05.yaml"); + } + + @Test(description = "When given ballerina file contain some compilation issue.") + public void testListeners06() { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_scenario06.bal"); + List errors = BallerinaToAsyncApiGenerator + .generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, null, false, outStream); + Assert.assertTrue(errors.isEmpty()); + } + + @Test(description = "Generate AsyncAPI spec for http load balancer listeners") + public void testListeners07() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("listeners/listener_http_load_balancer.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "listeners/with_check_key_word.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/MapTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/MapTypeTests.java new file mode 100644 index 000000000..810d39757 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/MapTypeTests.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class for the covering the unit tests for map type scenarios. + */ +public class MapTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi").toAbsolutePath(); + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "When the record field has map type") + public void testMapFiled() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("data_type/map.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/map.yaml"); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ModuleReferenceTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ModuleReferenceTests.java new file mode 100644 index 000000000..0ce43e17f --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ModuleReferenceTests.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class for the resolve reference in the other module in ballerina package. + */ +public class ModuleReferenceTests { + private static final Path RES_DIR = Paths.get( + "src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service").toAbsolutePath(); + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "Response with separate modules") + public void testResponse01() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("snowpeak.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "ballerina-project/service/snowpeak.yaml"); + } + + + // re-enable after issue #6583 is fixed + @Test(enabled = false, description = "Response has array type the array item type in separate module") + public void testResponse02() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("arrayTypeResponse.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "ballerina-project/service/arrayTypeResponse.yaml"); + } + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "check readonly") + public void testRecordReferenceWithReadOnly() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("readonly.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "ballerina-project/service/readonly.yaml"); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/OptionalTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/OptionalTests.java new file mode 100644 index 000000000..02c14273a --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/OptionalTests.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class for optional returns. + */ +public class OptionalTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "When the remote method has an optional return") + public void testIntReturnOptional() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("optional/optional_int_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "optional/optional_int_return.yaml"); + } + + @Test(description = "When the remote method has an optional return as error") + public void testErrorReturnOptional() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("optional/optional_error_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "optional/optional_error_return.yaml"); + } + + @Test(description = "When the remote method has two union type returns with optional return") + public void testTwoTypesReturnOptional() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("optional/optional_two_union_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "optional/optional_two_union_return.yaml"); + } + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "When the remote method has multiple return types including streaming " + + "with optional return") + public void testMultipleTypesStreamIncludeReturnOptional() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("optional/optional_multiple_type_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "optional/optional_multiple_type_return.yaml"); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/QueryParameterTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/QueryParameterTests.java new file mode 100644 index 000000000..1a7384619 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/QueryParameterTests.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Tests for query parameter mapping. + */ +public class QueryParameterTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + // These are the data types that current ballerina query parameters can have.[effect from slbeta3] + // type BasicType boolean|int|float|decimal|string ; + // public type QueryParamType json | () |BasicType|BasicType[]; + + @Test(description = "Required query parameter") + public void testQueryScenario01() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario01.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario01.yaml"); + } + + @Test(description = "When the query parameter has nullable enable it default behave as optional parameter") + public void testQueryScenario02() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario02.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario02.yaml"); + } + + @Test(description = "Require query parameter array type.") + public void testQueryscenario03() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario03.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario03.yaml"); + } + + @Test(description = "Query parameter has array type with nullable value (ex: int[]? offset)") + public void testQueryscenario04() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario04.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario04.yaml"); + } + + //TODO : Test this after implement treatNilableAsOptional + @Test(description = "Query parameter has service config with optional field false", enabled = false) + public void testQueryscenario05() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario05.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario05.yaml"); + } + + @Test(description = "Query parameter has default parameter.") + public void testQueryscenario06() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario06.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario06.yaml"); + } + + //Disable till http module support the nilable array `int?[]` in query parameter + @Test(description = "Query parameter has array type with null values (ex: int?[] offset)") + public void testQueryscenario07() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario07.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario07.yaml"); + } + + @Test(description = "Default parameter scenarios do not support with tool") + public void testQueryscenario08() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("query/query_scenario08.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "query/query_scenario08.yaml"); + } + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/RecordTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/RecordTests.java new file mode 100644 index 000000000..60de133bf --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/RecordTests.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This test class for the covering the unit tests for record scenarios. + */ +public class RecordTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets/" + + "ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "When the record field has typeInclusion it map to allOfSchema in AAS") + public void testTypeInclusion() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/typeInclusion.bal"); + //Compare generated yaml file with expected yaml content + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/typeInclusion.yaml"); + } + + @Test(description = "When the record field has optional fields it map to optional fields in AAS") + public void testRequiredField() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/optional.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/optional.yaml"); + } + + @Test(description = "When the record field has nullable fields it enables nullable true in AAS") + public void testNullableFieldWithOptional() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/nullable01.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/nullable01.yaml"); + } + + @Test(description = "When the record field has nullable fields which is required") + public void testNullableFieldWithRequired() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/nullable02.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/nullable02.yaml"); + } + + @Test(description = "When the record field has nullable field , which has record type reference data type") + public void testNullableFieldWithTypeReference() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/nullable03.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/nullable03.yaml"); + } + + @Test(description = "When the record field has nullable field , which has record type reference data type") + public void testUnionTypeWithRecordType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/union.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/union.yaml"); + } + + @Test(description = "When the record field has nullable field , which has record type reference data type") + public void testUnionTypeWithPrimitive() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/union_with_primitive.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/union_with_primitive.yaml"); + } + + @Test(description = "When the record field has nullable field , which has record type reference data type") + public void testUnionTypeWithNullable() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/union_with_nullable.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/union_with_nullable.yaml"); + } + + @Test(description = "When the record field has cyclic record type") + public void testCyclicRecord() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/cyclic_record.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/cyclic_record.yaml"); + } + + @Test(description = "When the record is readOnly type") + public void testReadOnlyRecord() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("record/with_readonly_keyword.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "record/with_read_only_keyword.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ResponseTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ResponseTests.java new file mode 100644 index 000000000..97b85545a --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/ResponseTests.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import io.ballerina.asyncapi.cmd.websockets.BallerinaToAsyncApiGenerator; +import io.ballerina.asyncapi.websocketscore.generators.asyncspec.diagnostic.AsyncApiConverterDiagnostic; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +/** + * This test class for the covering the unit tests for return type scenarios. + */ +public class ResponseTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets/" + + "ballerina-to-asyncapi").toAbsolutePath(); + private Path tempDir; + private static final PrintStream outStream = System.out; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Response scenario01 without return type") + public void testResponse02() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario01_json.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario01_json.yaml"); + } + + @Test(description = "Response scenario02 - return type with Record") + public void testResponse03() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario02_simple_name_reference_record.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario02_simple_name_reference_record.yaml"); + } + + @Test(description = "Response scenario 03 - Array type response with a schema") + public void testResponse10() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario03_builtin_array.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario03_builtin_array.yaml"); + } + + @Test(description = "When the return type is string") + public void testStringReturn() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario04_builtin.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario04_builtin.yaml"); + } + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "When the return type is inline record") + public void testInlineRecordReturn() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario05_inline_record_builtin.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario05_inline_record_builtin.yaml"); + } + + @Test(description = "When the return type is xml") + public void testReturnTypeXml() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario06_xml.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario06_xml.yaml"); + } + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "When the return type is inline record and type reference") + public void testInlineRecordHasReference() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario07_inline_record_type_reference.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario07_inline_record_type_reference.yaml"); + } + + @Test(description = "When the response has float return type") + public void testResponseWithFloatReturnType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario08_float.bal"); + List errors = BallerinaToAsyncApiGenerator + .generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, null, false, outStream); + Assert.assertTrue(errors.isEmpty()); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario08_float.yaml"); + } + + @Test(description = "When the response has decimal return type") + public void testResponseWithDecimalReturnType() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario09_decimal.bal"); + List errors = BallerinaToAsyncApiGenerator + .generateAsyncAPIDefinitionsAllService(ballerinaFilePath, this.tempDir, null, false, outStream); + Assert.assertTrue(errors.isEmpty()); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario09_decimal.yaml"); + } + + @Test(description = "When the return type is inline record with typeInclusion fields", enabled = false) + public void testInlineRecordHasTypeInclusionReference() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario10_inline_record_type_inclusion.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario10_inline_record_type_inclusion.yaml"); + } + @Test(description = "When the return type is record with typeInclusion field") + public void testTypeInclusion() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario11_record_including_type_inclusion.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario11_record_including_type_inclusion.yaml"); + } + + @Test(description = "When the return type is array record ") + public void testArrayRecord() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario12_array_record.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "response/rs_scenario12_array_record.yaml"); + } + + //re-enable after issue #6583 is fixed + @Test(enabled = false, description = "When multiple return types are returning") + public void testReturningMultipleResponses() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario13_multiple_builtin_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario13_multiple_builtin_return.yaml"); + } + + + @Test(description = "When stream of strings returns") + public void testReturningStringStream() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario14_stream_string_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario14_stream_string_return.yaml"); + } + + @Test(description = "When multiple streams return as union type") + public void testReturningMultipleTypesOfStreams() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("response/rs_scenario15_multiple_stream_types_return.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, + "response/rs_scenario15_multiple_stream_types_return.yaml"); + } + + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/SecurityTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/SecurityTests.java new file mode 100644 index 000000000..004859817 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/SecurityTests.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This {@code SecurityTests} test class if for the covering the security tests for ballerina to asyncapi generation. + */ +public class SecurityTests { + private static final Path RES_DIR = + Paths.get("src/test/resources/websockets/ballerina-to-asyncapi/security").toAbsolutePath(); + private Path tempDir; + + @BeforeMethod + public void setup() throws IOException { + this.tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + } + + @Test(description = "Check for wss protocol if there is secure socket present as an annotation") + public void notAcceptable() throws IOException { + Path ballerinaFilePath = RES_DIR.resolve("secure_socket_present.bal"); + TestUtils.compareWithGeneratedFile(ballerinaFilePath, "security/secure_socket_present.yaml"); + } + @AfterMethod + public void cleanUp() { + TestUtils.deleteDirectory(this.tempDir); + } + + @AfterTest + public void clean() { + System.setErr(null); + System.setOut(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/TestUtils.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/TestUtils.java new file mode 100644 index 000000000..0b2ea3915 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/asyncapi/TestUtils.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.asyncapi; + +import io.ballerina.asyncapi.cmd.websockets.BallerinaToAsyncApiGenerator; +import org.testng.Assert; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.ballerina.asyncapi.websocketscore.generators.asyncspec.Constants.ASYNC_API_SUFFIX; + +/** + * This Util class for storing the common utils related to test in ballerina to asyncapi command implementation. + */ +public class TestUtils { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/ballerina-to-asyncapi/").toAbsolutePath(); + private static final PrintStream outStream = System.out; + + private static String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { + Stream expectedServiceLines = Files.lines(expectedServiceFile.resolve(s)); + String expectedServiceContent = expectedServiceLines.collect(Collectors.joining("\n")); + expectedServiceLines.close(); + return expectedServiceContent; + } + + public static void deleteGeneratedFiles(String filename, Path tempDir) { + try { + Files.deleteIfExists(tempDir.resolve(filename)); + Files.deleteIfExists(tempDir.resolve("schema.bal")); + } catch (IOException ignored) { + } + } + + public static void compareWithGeneratedFile(Path ballerinaFilePath, String yamlFile) throws IOException { + Path tempDir = Files.createTempDirectory("bal-to-asyncapi-test-out-" + System.nanoTime()); + try { + String expectedYamlContent = getStringFromGivenBalFile(RES_DIR.resolve("yaml_outputs"), yamlFile); + BallerinaToAsyncApiGenerator.generateAsyncAPIDefinitionsAllService(ballerinaFilePath, tempDir, null, + false, outStream); + if (Files.exists(tempDir.resolve(String.format("payloadV%s.yaml", ASYNC_API_SUFFIX)))) { + String generatedYaml = getStringFromGivenBalFile(tempDir, String.format("payloadV%s.yaml", + ASYNC_API_SUFFIX)); + generatedYaml = (generatedYaml.trim()).replaceAll("\\s+", ""); + expectedYamlContent = (expectedYamlContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedYaml.contains(expectedYamlContent)); + } else { + Assert.fail("Yaml was not generated"); + } + } catch (IOException e) { + Assert.fail("Error while generating the service. " + e.getMessage()); + } finally { + deleteGeneratedFiles(String.format("payloadV%s.yaml", ASYNC_API_SUFFIX), tempDir); + deleteDirectory(tempDir); + System.gc(); + } + } + + public static void deleteDirectory(Path path) { + if (!Files.exists(path)) { + return; + } + + try (Stream walk = Files.walk(path)) { + walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } catch (IOException ignored) { + //ignore + } + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/ballerina_project/Ballerina.toml b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/ballerina_project/Ballerina.toml new file mode 100644 index 000000000..290816894 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/ballerina_project/Ballerina.toml @@ -0,0 +1,5 @@ +[package] +org= "ballerina" +name= "test" +version= "0.0.0" + diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/ballerina_project/Package.md b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/ballerina_project/Package.md new file mode 100644 index 000000000..31977669e --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/ballerina_project/Package.md @@ -0,0 +1,81 @@ +## Module overview + +The AsyncAPI tools provide the following capabilities. + + 1. Generate the Ballerina client code for a given AsyncAPI definition. + 2. Export the AsyncAPI definition of a Ballerina service. + +The `asyncapi1` command in Ballerina is used for AsyncAPI to Ballerina and Ballerina to AsyncAPI code generations. +Code generation from AsyncAPI to Ballerina can produce `ballerina client stubs`. + + +### AsyncAPI to Ballerina +#### Generate Client Stub from an AsyncAPI Contract + +```bash +bal asyncapi1 -i + [--service-name: generated files name] + [(-o|--output): output file path] +``` +Generates Ballerina client stub for a given AsyncAPI file. + +This `-i ` parameter of the command is mandatory. It will get the path to the + AsyncAPI contract file (i.e., `my-api.yaml` or `my-api.json`) as an input. + +The `--service-name` is an optional parameter, which allows you to change the generated service name. + +The `(-o|--output)` is an optional parameter. You can use this to give the output path of the generated files. +If not, it will take the execution path as the output path. + + +If you want to generate client , you can set the mode as `client` in the AsyncAPI tool. +This client can be used in client applications to call the service defined in the AsyncAPI file. + +```bash +bal asyncapi1 -i + [(-o|--output) output file path] +``` + +### Ballerina to AsyncAPI +#### Service to AsyncAPI Export +```bash +bal asyncapi1 -i + [(-o|--output) output asyncapi file path] +``` +Export the Ballerina service to an AsyncAPI Specification 2.5.0 definition. For the export to work properly, +the input Ballerina service should be defined using the basic service and resource-level websocket annotation +@ServiceConfig + +If you need to document an AsyncAPI contract for only one given service, then use this command. +```bash + bal asyncapi1 -i (-s | --service) +``` + +### Samples for AsyncAPI Commands +#### Generate Client Stub from AsyncAPI +```bash + bal asyncapi1 -i hello.yaml +``` + +This will generate a Ballerina client stub for the `hello.yaml` AsyncAPI client named `hello-client`. +The above command can be run from within anywhere on the execution path. +It is not mandatory to run it from inside the Ballerina project. + +Output: +```bash +The service generation process is complete. The following files were created. +-- hello-client.bal +-- types.bal +-- utils.bal +``` +#### Generate an AsyncAPI Contract from a Service + + ```bash + bal asyncapi1 -i modules/helloworld/helloService.bal + ``` +This will generate the AsyncAPI contracts for the Ballerina services, which are in the `hello.bal` Ballerina file. + ```bash + bal asyncapi1 -i modules/helloworld/helloService.bal (-s | --service) helloworld + ``` +This command will generate the `helloworld-asyncapi1.yaml` file that is related to the `helloworld` service inside the + `helloService.bal` file. diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/ComparedGeneratedFileTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/ComparedGeneratedFileTests.java new file mode 100644 index 000000000..253d9162f --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/ComparedGeneratedFileTests.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.AfterTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * All the tests related to the + * {{@link io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator}} util. + */ +public class ComparedGeneratedFileTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + SyntaxTree syntaxTree; + + @Test(description = "Test asyncAPI definition to ballerina client source code generation", + dataProvider = "fileProviderForFilesComparison") + public void asyncAPIToBallerinaCodeGenTestForClient(String yamlFile, String expectedFile) throws IOException, + BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Real/" + yamlFile); + Path expectedPath = RES_DIR.resolve("baloutputs/Real/" + expectedFile); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder.withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator ballerinaClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = ballerinaClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @DataProvider(name = "fileProviderForFilesComparison") + public Object[][] fileProviderForFilesComparison() { + return new Object[][]{ +// {"gemini_websocket.yaml", "gemini_websocket.bal"}, + {"kraken_websocket.yaml", "kraken_websocket.bal"} + + }; + } + + @AfterTest + private void deleteGeneratedFiles() { + try { + TestUtils.deleteGeneratedFiles(); + } catch (IOException ignored) { + } + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/ExecuteTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/ExecuteTest.java new file mode 100644 index 000000000..4b60c4a05 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/ExecuteTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.ballerina.asyncapi.cmd.websockets.AsyncApiToBallerinaGenerator; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Paths; + +/** + * This tests class is to generate ballerina client codes. + */ +public class ExecuteTest { + + @Test(description = "Generate Client for testings", enabled = false) + public void generatePathWithPathParameterTests() throws IOException, BallerinaAsyncApiExceptionWs, + FormatterException { + AsyncApiToBallerinaGenerator asyncAPIToBallerinaGenerator = new AsyncApiToBallerinaGenerator("", false); + + asyncAPIToBallerinaGenerator.generateClient( + Paths.get("src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/" + + "multiple_stream_with_dispatcherStreamId.yaml"), + Paths.get("src/test/resources/websockets/out")); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/HeadersTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/HeadersTests.java new file mode 100644 index 000000000..52639bd9c --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/HeadersTests.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * All the tests related to the Header sections. + */ +public class HeadersTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + private SyntaxTree syntaxTree; + + @Test(description = "Test for header that comes under the parameter section") + public void getHeaderTests() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("HeaderParam/header_parameter.yaml"); + Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_client.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + //TODO: uncomment after add the capable of sending apikey as a header +// @Test(description = "Test for header that comes under the parameter section") +// public void getHeaderTestsWithoutParameter() throws IOException, BallerinaAsyncApiException { +// Path definitionPath = RES_DIR.resolve("HeaderParam/header_without_parameter.yaml"); +// Path expectedPath = RES_DIR.resolve("baloutputs/HeaderParam/header_without_parameter.bal"); +// AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); +// AASClientConfig.Builder clientMetaDataBuilder = new AASClientConfig.Builder(); +// AASClientConfig oasClientConfig = clientMetaDataBuilder +// .withAsyncAPI(asyncAPI).build(); +// IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); +// syntaxTree = intermediateClientGenerator.generateSyntaxTree(); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); +// } + + + @Test(description = "Test for header with default values") + public void getHeaderTestsWithDefaultValues() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("HeaderParam/header_param_with_default_value.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/HeaderParam/header_param_with_default_value.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + //Generate ballerina records to represent schemas in client intermediate code + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, schemaSyntaxTree); + } + + @Test(description = "Test for optional headers without default values") + public void getOptionalHeaderTestsWithoutDefaultValues() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("HeaderParam/header_with_query.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/HeaderParam/header_with_query.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/InvalidResponseTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/InvalidResponseTests.java new file mode 100644 index 000000000..43a70cb71 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/InvalidResponseTests.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Test invalid responses for given asyncapi specification. + */ +public class InvalidResponseTests { + private static final Path RES_DIR = Paths.get( + "src/test/resources/websockets/asyncapi-to-ballerina/client").toAbsolutePath(); + private SyntaxTree syntaxTree; + + @Test(description = "When response has array type payload", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Ballerina service file cannot be generate " + + "to the given AsyncAPI specification, Response type must be a Record") + public void testPayloadTypeResponse() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("InvalidResponse/payload_response.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); +// Path expectedPathForClient = RES_DIR.resolve("baloutputs/InvalidResponse/map_type_response.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + intermediateClientGenerator.generateSyntaxTree(); + + +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + @Test(description = "When response has array type payload", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Ballerina service file cannot be generate " + + "to the given AsyncAPI specification, Response type must be a Record") + public void testOneOfTypeResponse() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("InvalidResponse/one_of_response.yaml"); + Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/InvalidResponse/map_type_response.bal"); + Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + intermediateClientGenerator.generateSyntaxTree(); + + +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + +// @Test(description = "When response has map type", +// expectedExceptions = BallerinaAsyncApiException.class, +// expectedExceptionsMessageRegExp = "Response type must be a record, .*") +// public void testMapTypeResponse() throws IOException, BallerinaAsyncApiException { +// Path definitionPath = RES_DIR.resolve("InvalidResponse/map_type_response.yaml"); +//// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); +//// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); +// AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); +// AASClientConfig.Builder clientMetaDataBuilder = new AASClientConfig.Builder(); +// AASClientConfig oasClientConfig = clientMetaDataBuilder +// .withAsyncAPI(asyncAPI).build(); +// IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); +// intermediateClientGenerator.generateSyntaxTree(); +// +//// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +//// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +//// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); +// } + + @Test(description = "Test primitive type responses", expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Response type must be a record, .*", + dataProvider = "fileProviderForFilesComparison") + public void testPrimitiveTypeResponses(String yamlFile) throws IOException, + BallerinaAsyncApiExceptionWs, FormatterException, URISyntaxException { + Path definitionPath = RES_DIR.resolve("InvalidResponse/" + yamlFile); +// Path expectedPath = RES_DIR.resolve(" baloutputs/InvalidResponse/" + expectedFile); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator ballerinaClientGenerator = new IntermediateClientGenerator(oasClientConfig); + ballerinaClientGenerator.generateSyntaxTree(); +// List diagnostics = getDiagnostics(syntaxTree, asyncAPI, ballerinaClientGenerator); +// Assert.assertTrue(diagnostics.isEmpty()); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @DataProvider(name = "fileProviderForFilesComparison") + public Object[][] fileProviderForFilesComparison() { + return new Object[][]{ + {"float_type_response.yaml"}, + {"boolean_type_response.yaml"}, + {"string_type_response.yaml"}, + {"array_type_response.yaml"}, + }; + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/NoServerURLTest.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/NoServerURLTest.java new file mode 100644 index 000000000..581e5014c --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/NoServerURLTest.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + + +/** + * Test client generation when server url is not given in the async-api definition. + */ +public class NoServerURLTest { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + List list1 = new ArrayList<>(); + List list2 = new ArrayList<>(); + private SyntaxTree syntaxTree; + + @Test(description = "Test for no server url with no security schema given") + public void getClientForNoServerURL() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("NoServerUrl/missing_server_url.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/NoServerUrl/missing_server_url.bal"); + + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig aasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(aasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } +//TODO: Uncomment after adding authentication mechanisms + +// @Test(description = "Test for no server url with HTTP authentication mechanism") +// public void getClientForNoServerURLWithHTTPAuth() { +// BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( +// false, true); +// String expectedParams = TestConstants.WEBSOCKET_CLIENT_CONFIG_PARAM_NO_URL; +// StringBuilder generatedParams = new StringBuilder(); +// List generatedInitParamNodes = ballerinaAuthConfigGenerator.getConfigParamForClassInit( +// "/"); +// for (Node param: generatedInitParamNodes) { +// generatedParams.append(param.toString()); +// } +// expectedParams = (expectedParams.trim()).replaceAll("\\s+", ""); +// String generatedParamsStr = (generatedParams.toString().trim()).replaceAll("\\s+", ""); +// Assert.assertEquals(expectedParams, generatedParamsStr); +// } +// +// @Test(description = "Test for no server url with API key authentication mechanism") +// public void getClientForNoServerURLWithAPIKeyAuth() { +// BallerinaAuthConfigGenerator ballerinaAuthConfigGenerator = new BallerinaAuthConfigGenerator( +// true, false); +// String expectedParams = TestConstants.API_KEY_CONFIG_PARAM_NO_URL; +// StringBuilder generatedParams = new StringBuilder(); +// List generatedInitParamNodes = ballerinaAuthConfigGenerator.getConfigParamForClassInit( +// "/"); +// for (Node param: generatedInitParamNodes) { +// generatedParams.append(param.toString()); +// } +// expectedParams = (expectedParams.trim()).replaceAll("\\s+", ""); +// String generatedParamsStr = (generatedParams.toString().trim()).replaceAll("\\s+", ""); +// Assert.assertEquals(expectedParams, generatedParamsStr); +// } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/PathParameterTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/PathParameterTests.java new file mode 100644 index 000000000..08c393a15 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/PathParameterTests.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.cmd.websockets.AsyncApiToBallerinaGenerator; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * This tests class for the tests Path parameters in asyncapi file. + */ +public class PathParameterTests { + private static final Path RESDIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client") + .toAbsolutePath(); + private SyntaxTree syntaxTree; + + + @Test(description = "Generate Client for path parameter has parameter name as key word - unit tests for method") + public void generatePathWithPathParameterTests() throws IOException, BallerinaAsyncApiExceptionWs, + FormatterException { + AsyncApiToBallerinaGenerator asyncAPIToBallerinaGenerator = new AsyncApiToBallerinaGenerator("", false); + asyncAPIToBallerinaGenerator.generateClient( + Paths.get("src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/" + + "multiple_stream_with_dispatcherStreamId.yaml"), + Paths.get("src/test/resources/websockets/out")); + } + + //DOne + @Test(description = "Generate Client for path parameter with referenced schema") + public void generatePathParamWithReferencedSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("PathParam/path_param_with_ref_schemas.yaml"); + Path expectedPath = RESDIR.resolve("baloutputs/PathParam/path_param_with_ref_schema.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + intermediateClientGenerator.generateSyntaxTree(); + + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + //Generate ballerina records to represent schemas in client intermediate code + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, schemaSyntaxTree); + } + + //Done + @Test(description = "Generate Client while handling special characters in path parameter name") + public void generateFormattedPathParamName() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("PathParam/path_parameter_special_name.yaml"); + Path expectedPath = RESDIR.resolve("baloutputs/PathParam/path_parameter_with_special_name.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "Generate Client with duplicated path parameter name in the path") + public void generateFormattedDuplicatedPathParamName() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("PathParam/path_param_duplicated_name.yaml"); + Path expectedPath = RESDIR.resolve("baloutputs/PathParam/path_param_duplicated_name.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); + } + + @Test(description = "When path parameter has given unmatch data type in ballerina", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Ballerina doesn't support array type path parameters") + public void testInvalidPathParameterType() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("PathParam/path_parameter_invalid.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + intermediateClientGenerator.generateSyntaxTree(); + + } + + @Test(description = "When given data type not match with ballerina data type", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Unsupported AsyncAPI data type .*") + public void testInvalidDataType() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("PathParam/path_parameter_invalid02.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + intermediateClientGenerator.generateSyntaxTree(); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/QueryParameterTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/QueryParameterTests.java new file mode 100644 index 000000000..933b52a58 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/QueryParameterTests.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + + +/** + * This tests class for the tests Query parameters in asyncapi file. + */ +public class QueryParameterTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + + SyntaxTree syntaxTree; + + @Test(description = "Generate Client for query parameter has default value") + public void generateQueryParamWithDefault() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("QueryParam/query_param_with_default_value.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/QueryParam/query_param_with_default_value.bal"); + + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + //Generate ballerina records to represent schemas in client intermediate code + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, schemaSyntaxTree); + } + + @Test(description = "Generate Client for query parameter without default value") + public void generateQueryParamWithOutDefault() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("QueryParam/query_param_without_default_value.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/QueryParam/query_param_without_default_value.bal"); + + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + //Generate ballerina records to represent schemas in client intermediate code + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, schemaSyntaxTree); + } + + @Test(description = "Generate Client for query parameter with referenced schema") + public void generateQueryParamWithReferencedSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("QueryParam/query_param_with_ref_schema.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/QueryParam/query_param_with_ref_schema.bal"); + + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefNodes = new ArrayList<>( + intermediateClientGenerator.getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + + //Generate ballerina records to represent schemas in client intermediate code + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefNodes); + + SyntaxTree schemaSyntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, schemaSyntaxTree); + } + + //TODO: Uncomment after adding apikeys and http/oAuth support +// @Test(description = "Generate query parameters when both apikeys and http/OAuth is supported") +// public void genQueryParamsForCombinationOfApiKeyAndHTTPOrOAuth() throws IOException, BallerinaAsyncApiException { +// Path definitionPath = RES_DIR.resolve("QueryParam/query_param_combination_of_apikey_and_http_oauth.yaml"); +// Path expectedPath = RES_DIR.resolve("baloutputs/QueryParam/combination_of_apikey_and_http_oauth.bal"); +// +// AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); +// AASClientConfig.Builder clientMetaDataBuilder = new AASClientConfig.Builder(); +// AASClientConfig oasClientConfig = clientMetaDataBuilder +// .withAsyncAPI(asyncAPI).build(); +// IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); +// syntaxTree = intermediateClientGenerator.generateSyntaxTree(); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, syntaxTree); +// } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/RemoteFunctionTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/RemoteFunctionTests.java new file mode 100644 index 000000000..2fc080876 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/RemoteFunctionTests.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.websocketscore.GeneratorUtils.getValidName; +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * Test remote function tests for given asyncapi specification. + */ +public class RemoteFunctionTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + private SyntaxTree syntaxTree; + + @Test(description = "Test for stream request with no dispatcherStreamId") + public void testRemoteFunctionDescription() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("RemoteFunction/remote_function_description.yaml"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/RemoteFunction/remote_function_description.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); + } + + @Test(description = "Check whether the formatted function name are meeting ballerina coding conventions", + dataProvider = "sampleProvider") + public void testFunctionNameGeneration(String requestName, String expectedFunctionName) { + String generatedFunctionName = getValidName(requestName, false); + Assert.assertEquals(generatedFunctionName, expectedFunctionName); + } + + @DataProvider(name = "sampleProvider") + public Object[][] dataProvider() { + return new Object[][]{ + {"get-pet-name", "getPetName"}, + {"GET_Add_permission", "gET_Add_permission"}, + {"ListBankAccount", "listBankAccount"}, + {"chat.media.download", "chatMediaDownload"} + }; + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/SimpleResponseTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/SimpleResponseTests.java new file mode 100644 index 000000000..121589606 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/SimpleResponseTests.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * Test simple type responses for given asyncapi specification. + */ +public class SimpleResponseTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + private SyntaxTree syntaxTree; + + @Test(description = "Test for stream request with no dispatcherStreamId") + public void testOneResponseWithNoDispatcherStreamIdRequest() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("SimpleResponse/one_response_with_no_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/SimpleResponse/" + + "one_response_with_no_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + @Test(description = "Test for stream request with no dispatcherStreamId") + public void testOneResponseWithDispatcherStreamIdRequest() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("SimpleResponse/one_response_with_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/SimpleResponse/" + + "one_response_with_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + + @Test(description = "Test for header that comes under the parameter section") + public void testMultipleResponseRequestWithNoDispatcherStreamIdRequest() throws IOException, + BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("SimpleResponse/multiple_response_with_no_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/SimpleResponse/" + + "multiple_response_with_no_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + @Test(description = "Test for header that comes under the parameter section") + public void testMultipleResponseRequestWithDispatcherStreamIdRequest() throws IOException, + BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("SimpleResponse/multiple_response_with_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/SimpleResponse/" + + "multiple_response_with_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/StreamResponseTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/StreamResponseTests.java new file mode 100644 index 000000000..f4400d6ee --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/StreamResponseTests.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * Test stream responses for given asyncapi specification. + */ +public class StreamResponseTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + private SyntaxTree syntaxTree; + + @Test(description = "Test for stream request with no dispatcherStreamId") + public void testOneStreamingWithNoDispatcherStreamIdRequest() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("StreamResponse/one_stream_with_no_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/StreamResponse/" + + "one_stream_with_no_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + @Test(description = "Test for stream request with no dispatcherStreamId") + public void testOneStreamingWithDispatcherStreamIdRequest() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("StreamResponse/one_stream_with_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/StreamResponse/" + + "one_stream_with_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + + @Test(description = "Test for header that comes under the parameter section") + public void testMultipleStreamingRequestWithNoDispatcherStreamIdRequest() throws IOException, + BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("StreamResponse/multiple_stream_with_no_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/StreamResponse/" + + "multiple_stream_with_no_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } + + @Test(description = "Test for header that comes under the parameter section") + public void testMultipleStreamingRequestWithDispatcherStreamIdRequest() throws IOException, + BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("StreamResponse/multiple_stream_with_dispatcherStreamId.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/StreamResponse/" + + "multiple_stream_with_dispatcherStreamId.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForUtils, utilsSyntaxTree); +// compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForTypes, schemaSyntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/SubProtocolTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/SubProtocolTests.java new file mode 100644 index 000000000..80727eead --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/SubProtocolTests.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * Test subProtocols that can run over websocket. + */ +public class SubProtocolTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/client").toAbsolutePath(); + private SyntaxTree syntaxTree; + + @Test(description = "Test client generation of graphql over websocket sub protocol ") + public void testGraphQlOverWebsocket() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("SubProtocols/graphqloverwebsocket.yaml"); +// Path expectedPathForTypes = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_types.bal"); + Path expectedPathForClient = RES_DIR.resolve("baloutputs/SubProtocols/graphqloverwebsocket.bal"); +// Path expectedPathForUtils = RES_DIR.resolve("baloutputs/HeaderParam/header_parameter_utils.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + syntaxTree = intermediateClientGenerator.generateSyntaxTree(); + + compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPathForClient, syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/UtilGenerationTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/UtilGenerationTests.java new file mode 100644 index 000000000..306819705 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/client/UtilGenerationTests.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.client; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.AfterClass; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Test util file generation for ballerina connectors. + */ +public class UtilGenerationTests { + private static final Path RESDIR = + Paths.get("src/test/resources/websockets/asyncapi-to-ballerina/client").toAbsolutePath(); + + @Test(description = "Test default util file generation") + public void testDefaultUtilFileGen() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("Util/default_util.yaml"); + Path expectedPath = RESDIR.resolve("baloutputs/Util/default_util.bal"); + String path = expectedPath.toString(); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder.withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + intermediateClientGenerator.generateSyntaxTree(); + SyntaxTree utlisSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree(path, utlisSyntaxTree); + } + + @Test(description = "Validate the util functions generated for AsyncAPI definition with query parameters") + public void testUtilFileGenForQueryParams() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("Util/query_parameter.yaml"); + String expectedPath = "client/baloutputs/Util/query_parameter_utils.bal"; + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder.withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + SyntaxTree clientSyntaxTree = intermediateClientGenerator.generateSyntaxTree(); + SyntaxTree utlisSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, utlisSyntaxTree); + } + + @Test(description = "Validate the util functions generated for AsyncAPI definition with headers") + public void testUtilFileGenForHeader() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("Util/header_parameter.yaml"); + String expectedPath = "client/baloutputs/Util/header_parameter_utils.bal"; + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder.withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + SyntaxTree clientSyntaxTree = intermediateClientGenerator.generateSyntaxTree(); + SyntaxTree utlisSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, utlisSyntaxTree); + } + + @Test(description = "Validate the util functions generated for asyncAPI definition with URL encoded request body") + public void testUtilFileGenURLEncodedRequestBody() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("Util/path_param_url_encoded.yaml"); + String expectedPath = "client/baloutputs/Util/path_param_url_encoded.bal"; + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder.withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + SyntaxTree clientSyntaxTree = intermediateClientGenerator.generateSyntaxTree(); + SyntaxTree utlisSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath, utlisSyntaxTree); + } + + @Test(description = "Validate the util functions generated for AsyncAPI definition" + + " when all the scenarios are given") + public void testCompleteUtilFileGen() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RESDIR.resolve("Util/complete_util_gen.yaml"); + Path expectedPath = RESDIR.resolve("baloutputs/Util/complete_util_gen.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig oasClientConfig = clientMetaDataBuilder.withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); + SyntaxTree clientSyntaxTree = intermediateClientGenerator.generateSyntaxTree(); + SyntaxTree utlisSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree(expectedPath.toString(), utlisSyntaxTree); + } +// +// @Test(description = "Test the utilsbal file generation when only in:query api-key auth given") +// public void testApiKeyauthUtilGen() throws IOException, BallerinaAsyncApiException, +// FormatterException { +// Path definitionPath = RESDIR.resolve("swagger/apikey_with_no_query_param.yaml"); +// AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); +// AASClientConfig.Builder clientMetaDataBuilder = new AASClientConfig.Builder(); +// AASClientConfig oasClientConfig = clientMetaDataBuilder +// .withAsyncAPI(asyncAPI).build(); +// IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(oasClientConfig); +// SyntaxTree clientSyntaxTree = intermediateClientGenerator.generateSyntaxTree(); +// List diagnostics = getDiagnostics(clientSyntaxTree, asyncAPI, intermediateClientGenerator); +// Assert.assertTrue(diagnostics.isEmpty()); +// } +// + + @AfterClass + public void cleanUp() throws IOException { + TestUtils.deleteGeneratedFiles(); + } +} + diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/common/SwaggerParserTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/common/SwaggerParserTests.java new file mode 100644 index 000000000..58e4db800 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/common/SwaggerParserTests.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.common; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Tests for BallerinaSchemaGenerators. + */ +public class SwaggerParserTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets/generators/schema").toAbsolutePath(); + SyntaxTree syntaxTree; + + //TODO: readd expectedExceptionsMessageRegExp = "asyncAPI file has errors: .*" after checking failure + @Test(description = "Functionality tests for getBallerinaasyncAPIType", + expectedExceptions = BallerinaAsyncApiExceptionWs.class) + public void generateHandleUnsupportedData() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("swagger/invalid.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.getAsyncAPIFromAsyncAPIParser(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } + + //Get string as a content of ballerina file + private String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { + Stream expectedServiceLines = Files.lines(expectedServiceFile.resolve(s)); + String expectedServiceContent = expectedServiceLines.collect(Collectors.joining("\n")); + expectedServiceLines.close(); + return expectedServiceContent; + } + + private void compareGeneratedSyntaxTreewithExpectedSyntaxTree(String s) throws IOException { + + String expectedBallerinaContent = getStringFromGivenBalFile(RES_DIR.resolve("ballerina/"), s); + String generatedSyntaxTree = syntaxTree.toString(); + + generatedSyntaxTree = (generatedSyntaxTree.trim()).replaceAll("\\s+", ""); + expectedBallerinaContent = (expectedBallerinaContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedSyntaxTree.contains(expectedBallerinaContent)); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/common/TestUtils.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/common/TestUtils.java new file mode 100644 index 000000000..583ff3afd --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/common/TestUtils.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.common; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.projects.DocumentId; +import io.ballerina.projects.Module; +import io.ballerina.projects.Package; +import io.ballerina.projects.Project; +import io.ballerina.projects.ProjectException; +import io.ballerina.projects.ProjectKind; +import io.ballerina.projects.directory.ProjectLoader; +import io.ballerina.tools.diagnostics.Diagnostic; +import org.ballerinalang.formatter.core.Formatter; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.Assert; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * This util class for keeping all the common functions that use to tests. + */ +public class TestUtils { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/").toAbsolutePath(); + private static final Path clientPath = RES_DIR.resolve("ballerina_project/client.bal"); + private static final Path schemaPath = RES_DIR.resolve("ballerina_project/types.bal"); + private static final Path utilPath = RES_DIR.resolve("ballerina_project/utils.bal"); + private static final String LINE_SEPARATOR = System.lineSeparator(); + + // Get diagnostics + public static List getDiagnostics(SyntaxTree syntaxTree, AsyncApi25DocumentImpl asyncAPI, + IntermediateClientGenerator intermediateClientGenerator) + throws FormatterException, IOException, BallerinaAsyncApiExceptionWs { + List preGeneratedTypeDefinitionNodes = new LinkedList<>(); + preGeneratedTypeDefinitionNodes.addAll(intermediateClientGenerator. + getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefinitionNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefinitionNodes); + SyntaxTree schemaSyntax = ballerinaSchemaGenerator.generateSyntaxTree(); + SyntaxTree utilSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + writeFile(clientPath, Formatter.format(syntaxTree).toString()); + writeFile(schemaPath, Formatter.format(schemaSyntax).toString()); + writeFile(utilPath, Formatter.format(utilSyntaxTree).toString()); + SemanticModel semanticModel = getSemanticModel(clientPath); + return semanticModel.diagnostics(); + } + + public static List getDiagnostics(SyntaxTree syntaxTree) throws FormatterException, IOException { + writeFile(schemaPath, Formatter.format(syntaxTree).toString()); + SemanticModel semanticModel = getSemanticModel(schemaPath); + return semanticModel.diagnostics(); + } + + //Get string as a content of ballerina file + public static String getStringFromGivenBalFile(Path expectedServiceFile) throws IOException { + Stream expectedServiceLines = Files.lines(expectedServiceFile); + String expectedServiceContent = expectedServiceLines.collect(Collectors.joining(LINE_SEPARATOR)); + expectedServiceLines.close(); + return expectedServiceContent.replaceAll(LINE_SEPARATOR, ""); + } + + public static void compareGeneratedSyntaxTreeWithExpectedSyntaxTree(Path path, SyntaxTree syntaxTree) + throws IOException { + + String expectedBallerinaContent = getStringFromGivenBalFile(path); + String generatedSyntaxTree = syntaxTree.toString(); + generatedSyntaxTree = generatedSyntaxTree.replaceAll(LINE_SEPARATOR, ""); + generatedSyntaxTree = (generatedSyntaxTree.trim()).replaceAll("\\s+", ""); + expectedBallerinaContent = (expectedBallerinaContent.trim()).replaceAll("\\s+", ""); + Assert.assertEquals(generatedSyntaxTree, expectedBallerinaContent); + } + + /* + * Write the generated syntax tree to file. + */ + public static void writeFile(Path filePath, String content) throws IOException { + try (PrintWriter writer = new PrintWriter(filePath.toString(), StandardCharsets.UTF_8)) { + writer.print(content); + } + } + + public static SemanticModel getSemanticModel(Path servicePath) { + // Load project instance for single ballerina file + Project project = null; + try { + project = ProjectLoader.loadProject(servicePath); + } catch (ProjectException ignored) { + } + + Package packageName = project.currentPackage(); + DocumentId docId; + + if (project.kind().equals(ProjectKind.BUILD_PROJECT)) { + docId = project.documentId(servicePath); + } else { + // Take module instance for traversing the syntax tree + Module currentModule = packageName.getDefaultModule(); + Iterator documentIterator = currentModule.documentIds().iterator(); + docId = documentIterator.next(); + } + return project.currentPackage().getCompilation().getSemanticModel(docId.moduleId()); + } + +// public static AsyncApi25DocumentImpl getAsyncAPI(Path definitionPath) throws IOException, +// BallerinaAsyncApiExceptionWs{ +// String asyncAPIFileContent = Files.readString(definitionPath); +// SwaggerParseResult parseResult = new AsyncAPipar().readContents(asyncAPIFileContent); +// return parseResult.getasyncAPI(); +// } + + public static String getStringFromGivenBalFile(Path expectedServiceFile, String s) throws IOException { + Stream expectedServiceLines = Files.lines(expectedServiceFile.resolve(s)); + String expectedServiceContent = expectedServiceLines.collect(Collectors.joining(LINE_SEPARATOR)); + expectedServiceLines.close(); + return expectedServiceContent; + } + + public static void compareGeneratedSyntaxTreeWithExpectedSyntaxTree(String s, SyntaxTree syntaxTree) + throws IOException { + + String expectedBallerinaContent = getStringFromGivenBalFile(RES_DIR.resolve(s)); + String generatedSyntaxTree = syntaxTree.toString(); + generatedSyntaxTree = (generatedSyntaxTree.trim()).replaceAll("\\s+", ""); + expectedBallerinaContent = (expectedBallerinaContent.trim()).replaceAll("\\s+", ""); + Assert.assertTrue(generatedSyntaxTree.contains(expectedBallerinaContent)); + } + + /** + * Delete generated ballerina files. + */ + public static void deleteGeneratedFiles() throws IOException { + Path resourcesPath = RES_DIR.resolve("ballerina_project"); + if (Files.exists(resourcesPath)) { + File[] listFiles = Objects.requireNonNull(new File(String.valueOf(resourcesPath)).listFiles()); + for (File existsFile : listFiles) { + String fileName = existsFile.getName(); + if (fileName.endsWith(".bal")) { + existsFile.delete(); + } + } + } + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AllOfDataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AllOfDataTypeTests.java new file mode 100644 index 000000000..0e85aefc6 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AllOfDataTypeTests.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * The tests are related to the allOF data type in the asyncAPI specification. + */ +public class AllOfDataTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets/asyncapi-to-ballerina/schema") + .toAbsolutePath(); + SyntaxTree syntaxTree; + + @Test(description = "Generate record for schema has allOf reference") + public void generateAllOf() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/oneAllOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/oneAllOf.bal", syntaxTree); + } + + @Test(description = "Generate record for schema has allOf reference in record field") + public void generateAllOfInRecordField() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/twoAllOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/twoAllOf.bal", syntaxTree); + } + + @Test(description = "Generate record when allOf schema has only one references schema") + public void generateTypeForSingleAllOfSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/allOf_with_one_ref.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/allOf_with_one_ref.bal", syntaxTree); + } + + @Test(description = "Generate record when allOf schema has only one references schema with cyclic dependency " + + "schema") + public void generateCyclicSchemaAllOfSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/allOf_with_cyclic.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/allOf_with_cyclic.bal", syntaxTree); + } + + @Test(description = "Generate record for allOf schema with array schema") + public void generateAllOfWithTypeUnSpecifiedObjectSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/allOfWithNoType.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/allOfWithNoType.bal", syntaxTree); + } + + + @Test(description = "Generate record for allOf schema with empty object schema") + public void generateAllOfWithEmptyObjectSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/allOfWithEmptyObject.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/allOfWithEmptyObject.bal", syntaxTree); + } + + @Test(description = "Generate record for nested allOf schemas") + public void generateNestedAllOfSchema() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/nested_allOf_with_allOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/AllOf/nested_allOf_with_allOf.bal", syntaxTree); + } + + @Test(description = "Tests record generation for nested OneOf schema inside AllOf schema", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = + "Unsupported nested OneOf or AnyOf schema is found inside a AllOf schema.") + public void arrayHasMaxItemsExceedLimit02() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("AllOf/nested_allOf_with_oneOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AnyOfDataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AnyOfDataTypeTests.java new file mode 100644 index 000000000..2066013e9 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AnyOfDataTypeTests.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + + +/** + * Test implementation to verify the `anyOf` property related scenarios in asyncAPI schema generation, handled by + * the {@link BallerinaTypesGenerator}. + */ +public class AnyOfDataTypeTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema"). + toAbsolutePath(); + + //TODO: This need to check (this has to include in upcomming version) + @Test(description = "Test for the schema generations", enabled = false) + public void testAnyOfSchema() throws BallerinaAsyncApiExceptionWs, IOException, FormatterException { + Path definitionPath = RES_DIR.resolve("AnyOf/oneAnyOf.yaml"); + Path expectedPath = RES_DIR.resolve("baloutputs/AnyOf/oneAnyOf.bal"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + expectedPath, syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ArrayDataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ArrayDataTypeTests.java new file mode 100644 index 000000000..8f32c2cc5 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ArrayDataTypeTests.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Tests for all the possible scenarios with array type in the asyncapi definition. + */ +public class ArrayDataTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema"). + toAbsolutePath(); + private final PrintStream originalStdOut = System.out; + SyntaxTree syntaxTree; + private ByteArrayOutputStream consoleContent = new ByteArrayOutputStream(); + + @BeforeMethod + public void beforeTest() { + // Redirect all System.out to consoleContent. + System.setOut(new PrintStream(this.consoleContent)); + } + + @Test(description = "Generate record with array filed record") + public void generateRecordWithArrayField() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/oneArray.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/oneArray.bal", + syntaxTree); + } + + @Test(description = "Scenario04-Generate record with nested array filed record") + public void generateScenario04() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/nestedArray.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/nestedArray.bal", + syntaxTree); + } + + @Test(description = "Generate record with record type array filed record") + public void generateRecordWithRecordArrayField() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/refArray.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/refArray.bal", + syntaxTree); + } + + @Test(description = "Generate record for schema has array reference") + public void generateSchemaHasArrayReference() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/schemaArray.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/schemaArray.bal", + syntaxTree); + } + + @Test(description = "Array schema has no data type in items") + public void arrayNoDatatype() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_no_item_type.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/array_no_item_type.bal", + syntaxTree); + } + + @Test(description = "Array schema has max item count") + public void arrayHasMaxItems() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_max_item.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/array_max_item.bal", + syntaxTree); + } + + @Test(description = "Array schema with allOf") + public void arrayHasAllOfItems() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_with_allOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/array_with_allOf.bal", + syntaxTree); + } + + @Test(description = "Array schema with oneOf") + public void arrayHasOneOFfItems() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_with_oneOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Array/array_with_oneOf.bal", + syntaxTree); + } + + @Test(description = "Array schema with oneOf schema with nullable item") + public void arrayHasOneOfItemsWithNullable() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_with_oneOf_complex.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Array/array_with_oneOf_complex.bal", syntaxTree); + } + + @Test(description = "Array schema has max items count that ballerina doesn't support", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Maximum item count defined in the definition exceeds the.*") + public void arrayHasMaxItemsExceedLimit() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_exceed_max_item.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } + + @Test(description = "Array schema has max items count that ballerina doesn't support, in record field", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Maximum item count defined in the definition exceeds the.*") + public void arrayHasMaxItemsExceedLimit02() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Array/array_exceed_max_item_02.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } + + @AfterMethod + public void afterTest() { + // Put back the standard out. + System.setOut(this.originalStdOut); + // Clear the consoleContent. + this.consoleContent = new ByteArrayOutputStream(); + } + + // Simulate some processing time by pausing. + private void pause(long lPauseInMillisSec) { + try { + Thread.sleep(lPauseInMillisSec); + } catch (Exception ex) { + ex.printStackTrace(); + } + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AsyncAPIFileParserTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AsyncAPIFileParserTests.java new file mode 100644 index 000000000..8514f05bb --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/AsyncAPIFileParserTests.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Tests for AsyncAPI definition errors. + */ +public class AsyncAPIFileParserTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema"). + toAbsolutePath(); + + @Test(description = "Test invalid file path", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "AsyncAPI contract doesn't exist in the given .*") + public void testInvalidFilePath() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.getAsyncAPIFromAsyncAPIParser(RES_DIR.resolve("user.yaml")); + } + + //TODO: expectedExceptionsMessageRegExp = "Invalid file type.*" + @Test(description = "Test invalid file type", + expectedExceptions = BallerinaAsyncApiExceptionWs.class) + public void testInvalidFileType() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.getAsyncAPIFromAsyncAPIParser(RES_DIR.resolve( + "Invalid/petstore.txt")); + } + + //TODO expectedExceptionsMessageRegExp = "AsyncAPI file has errors: .*" + @Test(description = "Test invalid asyncapi version file ", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "AsyncAPI definition has errors." + + " Ballerina client code can only be generate for 2.5.0 version") + public void testInvalidFile() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.getAsyncAPIFromAsyncAPIParser(RES_DIR.resolve( + "Invalid/invalid.yaml")); + } + + //TODO: This error message need to improve + @Test(description = "Test asyncapi specification has undocumented reference in schema.", + expectedExceptions = BallerinaAsyncApiExceptionWs.class, + expectedExceptionsMessageRegExp = "Undefined \\$ref: '#/components/schemas/Request' in asyncAPI contract.") + public void testForUndocumentedReference() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve( + "Invalid/undocument_ref.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ConstraintTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ConstraintTests.java new file mode 100644 index 000000000..a7d1638d5 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ConstraintTests.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.getDiagnostics; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +/** + * This test class is to contain the test related to constraint validation. + */ +public class ConstraintTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema") + .toAbsolutePath(); + + @Test(description = "Tests with record field has constraint and record field type can be user defined datatype " + + "with constraint.") + public void testRecordFiledConstraint() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve( + "Constraint/record_field.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Constraint/record_field.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + + @Test(description = "Tests for all the array type scenarios:" + + "Use case 01 : User define array (Annotations on a type)" + + "Use case 02 : For both array type and array items have constraints," + + "Use case 03 : Reference array" + + "Use case 04 : Array items have constrained with number format" + + "Use case 05 : Only array items have constrained with number format") + public void testForArray() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve( + "Constraint/array.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Constraint/array.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + + @Test(description = "Tests for the field has reference type scenarios" + + "Use case 01 : Annotations on a record field" + + "Use case 02 : Annotations on a type" + + "Use case 03 : Annotations on a type used as a record field") + public void testForReference() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve( + "Constraint/type_def_node.yaml") + ); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Constraint/type_def_node.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + + @Test(description = "Tests with record field has constraint value with zero.") + public void testRecordFiledConstraintWithZeroValue() throws IOException, BallerinaAsyncApiExceptionWs, + FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve( + "Constraint/record_field_02.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Constraint/record_field_02.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + assertTrue(diagnostics.isEmpty()); + } + + @Test(description = "Tests with nested array field has constraint.") + public void testNestedArrayWithConstraint() throws IOException, BallerinaAsyncApiExceptionWs, + FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Constraint" + + "/nested_array_with_constraint.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Constraint/nested_array.bal", + syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + + @Test + public void testAdditionalPropertiesWithConstraint() throws IOException, BallerinaAsyncApiExceptionWs, + FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Constraint" + + "/additional_properties_with_constraint.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Constraint/additional_properties_with_constraint.bal", syntaxTree); + List diagnostics = getDiagnostics(syntaxTree); + boolean hasErrors = diagnostics.stream() + .anyMatch(d -> DiagnosticSeverity.ERROR.equals(d.diagnosticInfo().severity())); + assertFalse(hasErrors); + } + //TODO current tool doesn't handle union type: therefore union type constraint will handle once union type + // generation available in tool. +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/MapSchemaTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/MapSchemaTests.java new file mode 100644 index 000000000..ca312a95e --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/MapSchemaTests.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * This class is for containing the tests related to the {@code MapSchema}. + */ +public class MapSchemaTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema") + .toAbsolutePath(); + + @Test + public void testForAdditionalProperties() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Map" + + "/additional_properties_true.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Map/additional_properties_true.bal", syntaxTree); + } + + @Test + public void testForAdditionalPropertiesComposedSchema() + throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Map" + + "/additional_properties_composed_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Map/additional_properties_composed_schema.bal", syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/NullableFieldTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/NullableFieldTests.java new file mode 100644 index 000000000..4c4e4c8e5 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/NullableFieldTests.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Tests for x-nullable field. + */ +public class NullableFieldTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema/").toAbsolutePath(); + + @Test(description = "Test for nullable primitive fields") + public void testNullablePrimitive() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + + "/nullable_primitive_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Nullable/nullable_primitive.bal", + syntaxTree); + } + + @Test(description = "Test for nullable array fields") + public void testNullableArray() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + + "/nullable_array_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Nullable/nullable_array.bal", + syntaxTree); + } + + @Test(description = "Test for nullable array referenced schemas") + public void testNullableArrayRefSchemas() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + + "/nullable_ref_array.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Nullable/nullable_ref_array.bal", + syntaxTree); + } + + @Test(description = "Test for union type generation for nullable anyOf schema") + public void testNullableUnionType() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + + "/nullable_anyof_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("" + + "schema/baloutputs/Nullable/nullable_anyof_schema.bal", syntaxTree); + } + + @Test(description = "Test for union type generation for nullable anyOf schema with array schema") + public void testNullableArrayUnionType() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + + "/nullable_anyof_array_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Nullable/" + + "nullable_anyof_array_schema.bal", syntaxTree); + } + + @Test(description = "Test for type generation for object schema with no properties") + public void testNullableEmptyObjectSchema() throws IOException, BallerinaAsyncApiExceptionWs, FormatterException { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + + "/null_empty_record.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Nullable/" + + "null_empty_record.bal", syntaxTree); + } + +// @Test(description = "Test x-nullable not present") +// public void testXNullableNotPresent() throws IOException, BallerinaAsyncApiExceptionWs { +// AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Nullable" + +// "/xnullable_not_present.yaml")); +// BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); +// SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); +//// TestUtils.compareGeneratedSyntaxTreewithExpectedSyntaxTree("/baloutputs/Nullable/nullable_primitive.bal", +//// syntaxTree); +// } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/OneOfDataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/OneOfDataTypeTests.java new file mode 100644 index 000000000..e99571c33 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/OneOfDataTypeTests.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Test implementation to verify the `oneOf` property related scenarios in asyncAPI schema generation, handled by + * the {@link BallerinaTypesGenerator}. + */ +public class OneOfDataTypeTests { + + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema") + .toAbsolutePath(); + + @Test(description = "Generate record for schema has two references for oneOf") + public void generateForSchemaHasOneOf() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("OneOf/twoOneOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/OneOf/twoOneOf.bal", syntaxTree); + } + + @Test(description = "Generate record for schema has object type with OneOf") + public void generateForSchemaObjectType() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("OneOf/twoOneOfWithObjectType.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/OneOf/twoOneOfWithObjectType.bal", syntaxTree); + } + + @Test(description = "Tests full schema generations with oneOf type") + public void generateOneOFTests() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("OneOf/oneOfAsProperties.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/OneOf/" + + "oneOfAsProperties.bal", syntaxTree); + } + + @Test(description = "Tests record generation for oneOf schemas with inline object schemas") + public void oneOfWithInlineObject() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("OneOf/oneOfWithInlineSchemas.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/OneOf/oneOfWithInlineSchemas.bal", syntaxTree); + } + + @Test(description = "Tests record generation for nested OneOf schema inside AllOf schema") + public void oneOfWithNestedAllOf() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("OneOf/nestedOneOfWithAllOf.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/OneOf/nestedOneOfWithAllOf.bal", syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/PrimitiveDataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/PrimitiveDataTypeTests.java new file mode 100644 index 000000000..7895459e7 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/PrimitiveDataTypeTests.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Tests for the primitive data type. + */ +public class PrimitiveDataTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema"). + toAbsolutePath(); + private SyntaxTree syntaxTree; + private ByteArrayOutputStream outContent; + + @BeforeTest + public void setUp() { + outContent = new ByteArrayOutputStream(); + System.setErr(new PrintStream(outContent)); + } + + @Test(description = "Generate single record") + public void generateScenario01() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Primitive/scenario01.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Primitive/schema01.bal", syntaxTree); + } + + @Test(description = "Generate multiple record") + public void generateScenario02() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Primitive/scenario02.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Primitive/schema02.bal", syntaxTree); + } + + @Test(description = "Scenario for missing DataType") + public void generateMissingDatatype() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Primitive/missDataType.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Primitive/missDataType.bal", syntaxTree); + } + + @AfterTest + public void clean() { + System.setErr(null); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/RecordDataTypeTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/RecordDataTypeTests.java new file mode 100644 index 000000000..87893faa6 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/RecordDataTypeTests.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.ballerina.asyncapi.wsgenerators.common.TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree; + +/** + * Tests related to the record data structure. + */ +public class RecordDataTypeTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema").toAbsolutePath(); + SyntaxTree syntaxTree; + + @Test(description = "Generate record with record type filed record") + public void generateRecordWithRecordField() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Record/scenario05.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/schema05.bal", syntaxTree); + } + + @Test(description = "Generate empty record when no properties are given") + public void generateEmptyRecord() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Record/empty_record.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/empty_record.bal", + syntaxTree); + } + + @Test(description = "Test for default optional primitive fields in records") + public void testDefaultPrimitive() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Record" + + "/default_optional_primitive_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/" + + "default_optional_primitive_schema.bal", syntaxTree); + } + + @Test(description = "Test for default optional String fields in records") + public void testDefaultString() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Record" + + "/default_optional_string_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/" + + "default_optional_string_schema.bal", syntaxTree); + } + + @Test(description = "Test for default optional String fields with value double quote in records") + public void testDefaultWithDoubleQuote() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Record" + + "/default_optional_schema_with_doublequote.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/" + + "default_optional_schema_with_doublequote.bal", syntaxTree); + } + + @Test(description = "Test for default value for array record") + public void testDefaultArray() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Record" + + "/default_optional_array_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/" + + "default_optional_array_schema.bal", syntaxTree); + } + + @Test(description = "Test for default value for required fields") + public void testDefaultRequired() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Record" + + "/default_required_field_schema.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/" + + "default_required_field_schema.bal", syntaxTree); + } + + @Test(description = "Generate record for schema has inline record in fields reference") + public void generateSchemaHasInlineRecord() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Record/scenario11.yaml"); + + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/schema11.bal", syntaxTree); + } + + @Test(description = "Generate record for schema has object type only") + public void generateForSchemaHasObjectTypeOnly() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Record/scenario10.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/Record/schema10.bal", syntaxTree); + } + + @Test(description = "Generate records for nested referenced schemas") + public void generateAllOf() throws IOException, BallerinaAsyncApiExceptionWs { + Path definitionPath = RES_DIR.resolve("Record/nested_schema_refs.yaml"); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree + ("schema/baloutputs/Record/nested_schema_refs.bal", syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ReferenceResolveTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ReferenceResolveTests.java new file mode 100644 index 000000000..29bd8bde1 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/schema/ReferenceResolveTests.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.schema; +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Tests for Schema Reference resolve. + */ +public class ReferenceResolveTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/schema") + .toAbsolutePath(); + + @Test(description = "Tests with object type include reference") + public void testReferenceIncludeWithObjectType() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve( + "Reference/multiple_references.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree("schema/baloutputs/" + + "Reference/multiple_references.bal", syntaxTree); + } + + @Test(description = "Test Ballerina types generation when referred by another record with no additional fields") + public void testReferredTypesWithoutAdditionalFields() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Reference" + + "/referred_inclusion.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Reference/referred_inclusion.bal", syntaxTree); + } + + @Test(description = "Test doc comment generation of record fields when property is refered to another schema") + public void testDocCommentResolvingForRefferedSchemas() throws IOException, BallerinaAsyncApiExceptionWs { + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(RES_DIR.resolve("Reference" + + "/resolve_reference_docs.yaml")); + BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(asyncAPI); + SyntaxTree syntaxTree = ballerinaSchemaGenerator.generateSyntaxTree(); + TestUtils.compareGeneratedSyntaxTreeWithExpectedSyntaxTree( + "schema/baloutputs/Reference/resolve_reference_docs.bal", syntaxTree); + } +} diff --git a/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/testcases/TestGeneratorTests.java b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/testcases/TestGeneratorTests.java new file mode 100644 index 000000000..76cecca98 --- /dev/null +++ b/asyncapi-cli/src/test/java/io/ballerina/asyncapi/wsgenerators/testcases/TestGeneratorTests.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you 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 + * + * http://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 io.ballerina.asyncapi.wsgenerators.testcases; + +import io.apicurio.datamodels.models.asyncapi.v25.AsyncApi25DocumentImpl; +import io.ballerina.asyncapi.websocketscore.GeneratorUtils; +import io.ballerina.asyncapi.websocketscore.exception.BallerinaAsyncApiExceptionWs; +import io.ballerina.asyncapi.websocketscore.generators.client.IntermediateClientGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.TestGenerator; +import io.ballerina.asyncapi.websocketscore.generators.client.model.AasClientConfig; +import io.ballerina.asyncapi.websocketscore.generators.schema.BallerinaTypesGenerator; +import io.ballerina.asyncapi.wsgenerators.common.TestUtils; +import io.ballerina.compiler.api.SemanticModel; +import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.compiler.syntax.tree.TypeDefinitionNode; +import io.ballerina.tools.diagnostics.Diagnostic; +import org.ballerinalang.formatter.core.Formatter; +import org.ballerinalang.formatter.core.FormatterException; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.LinkedList; +import java.util.List; + +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.ASYNCAPI_PATH_SEPARATOR; +import static io.ballerina.asyncapi.websocketscore.GeneratorConstants.TEST_DIR; + +/** + * Test cases related to ballerina test skeleton generation. + */ +public class TestGeneratorTests { + private static final Path RES_DIR = Paths.get("src/test/resources/websockets" + + "/asyncapi-to-ballerina/test_cases/").toAbsolutePath(); + private static final Path PROJECT_DIR = RES_DIR.resolve("ballerina_project"); + private static final Path clientPath = RES_DIR.resolve("ballerina_project/client.bal"); + private static final Path utilPath = RES_DIR.resolve("ballerina_project/utils.bal"); + private static final Path schemaPath = RES_DIR.resolve("ballerina_project/types.bal"); + private static final Path testPath = RES_DIR.resolve("ballerina_project/tests/test.bal"); + private static final Path configPath = RES_DIR.resolve("ballerina_project/tests/Config.toml"); + + @Test(description = "Generate Client with test skeletons", dataProvider = "httpAuthIOProvider") + public void generateclientWithTestSkel(String yamlFile) throws IOException, + FormatterException, BallerinaAsyncApiExceptionWs, URISyntaxException { + Files.createDirectories(Paths.get(PROJECT_DIR + ASYNCAPI_PATH_SEPARATOR + TEST_DIR)); + Path definitionPath = RES_DIR.resolve("sample_yamls/" + yamlFile); + AsyncApi25DocumentImpl asyncAPI = GeneratorUtils.normalizeAsyncAPI(definitionPath); + AasClientConfig.Builder clientMetaDataBuilder = new AasClientConfig.Builder(); + AasClientConfig asyncAPIClientConfig = clientMetaDataBuilder + .withAsyncApi(asyncAPI).build(); + IntermediateClientGenerator intermediateClientGenerator = new IntermediateClientGenerator(asyncAPIClientConfig); + SyntaxTree syntaxTreeClient = intermediateClientGenerator.generateSyntaxTree(); + List preGeneratedTypeDefinitionNodes = new LinkedList<>(); + preGeneratedTypeDefinitionNodes.addAll(intermediateClientGenerator. + getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes()); + preGeneratedTypeDefinitionNodes.addAll(intermediateClientGenerator.getTypeDefinitionNodeList()); + BallerinaTypesGenerator schemaGenerator = new BallerinaTypesGenerator( + asyncAPI, preGeneratedTypeDefinitionNodes); + TestGenerator testGenerator = new TestGenerator(intermediateClientGenerator); + SyntaxTree syntaxTreeTest = testGenerator.generateSyntaxTree(); + SyntaxTree syntaxTreeSchema = schemaGenerator.generateSyntaxTree(); + SyntaxTree utilSyntaxTree = intermediateClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree(); + String configFile = testGenerator.getConfigTomlFile(); + List diagnostics = getDiagnostics(syntaxTreeClient, syntaxTreeTest, + syntaxTreeSchema, configFile, utilSyntaxTree); + + Assert.assertFalse(diagnostics.stream().anyMatch(diagnostic -> { + diagnostic.diagnosticInfo(). + severity(); + return false; + })); + } + + public List getDiagnostics(SyntaxTree clientSyntaxTree, SyntaxTree testSyntaxTree, + SyntaxTree schemaSyntaxTree, String configContent, SyntaxTree utilSyntaxTree) + throws FormatterException, IOException { + TestUtils.writeFile(clientPath, Formatter.format(clientSyntaxTree).toString()); + TestUtils.writeFile(utilPath, Formatter.format(utilSyntaxTree).toString()); + TestUtils.writeFile(schemaPath, Formatter.format(schemaSyntaxTree).toString()); + TestUtils.writeFile(testPath, Formatter.format(testSyntaxTree).toString()); + TestUtils.writeFile(configPath, configContent); + SemanticModel semanticModel = TestUtils.getSemanticModel(clientPath); + return semanticModel.diagnostics(); + } + + @AfterMethod + public void afterTest() { + try { + Files.deleteIfExists(clientPath); + Files.deleteIfExists(schemaPath); + Files.deleteIfExists(utilPath); + Files.deleteIfExists(testPath); + Files.deleteIfExists(configPath); + } catch (IOException ignored) { + } + } + + @DataProvider(name = "httpAuthIOProvider") + public Object[][] dataProvider() { + return new Object[][]{ +// "basic_auth.yaml", +// "bearer_auth.yaml", +// "oauth2_authorization_code.yaml", +// "oauth2_implicit.yaml", +// "query_api_key.yaml", + {"no_auth.yaml"} +// "query_param_combination_of_apikey_and_http_oauth.yaml", +// "oauth2_password.yaml" + }; + } +} diff --git a/asyncapi-cli/src/test/resources/expected_gen/data_types.bal b/asyncapi-cli/src/test/resources/expected_gen/data_types.bal index 5061e7a54..df6dd66ad 100644 --- a/asyncapi-cli/src/test/resources/expected_gen/data_types.bal +++ b/asyncapi-cli/src/test/resources/expected_gen/data_types.bal @@ -7,39 +7,39 @@ public type CustomTestSchema record { }; public type GenericEventWrapper record { - # An array of string-based User IDs. Each member of the collection represents a user that has installed your application/bot and indicates the described event would be visible to those users. - string[] authed_users; - anydata[] array_with_anydata?; - boolean boolean_value?; + CustomTestSchema custom_test_schema?; # The unique identifier your installed Slack application. string api_app_id; + # An array of string-based User IDs. Each member of the collection represents a user that has installed your application/bot and indicates the described event would be visible to those users. + string[] authed_users; + # The actual event, an object, that happened + record { # When the event was dispatched + string event_ts; # The specific name of the event + string 'type;} event; + # A unique identifier for this specific event, globally unique across all workspaces. + string event_id; + # The epoch timestamp in seconds indicating when this event was dispatched. + int event_time; # The unique identifier of the workspace where the event occurred string team_id; - # Indicates which kind of event dispatch this is, usually `event_callback` - string 'type; # A verification token to validate the event originated from Slack string token; - CustomTestSchema custom_test_schema?; - record {}[] array_with_inner_object?; - # A unique identifier for this specific event, globally unique across all workspaces. - string event_id; - CustomTestSchema[] array_with_ref?; + # Indicates which kind of event dispatch this is, usually `event_callback` + string 'type; + decimal decimal_number?; float float_number?; + boolean boolean_value?; + record {} plain_object?; CustomTestSchema ref_object?; - decimal decimal_number?; record { # When the event was dispatched string event_ts?; # The specific name of the event string 'type?;} object_without_type?; - # The actual event, an object, that happened - record { # When the event was dispatched - string event_ts; # The specific name of the event - string 'type;} event; - # The epoch timestamp in seconds indicating when this event was dispatched. - int event_time; - string[][] array_with_inner_array?; - record {} plain_object?; # This should be considered as anydata anydata 'anydata?; + CustomTestSchema[] array_with_ref?; + string[][] array_with_inner_array?; + record {}[] array_with_inner_object?; + anydata[] array_with_anydata?; }; public type GenericDataType CustomTestSchema|GenericEventWrapper; diff --git a/asyncapi-cli/src/test/resources/specs/spec-multiple-channels.yml b/asyncapi-cli/src/test/resources/specs/spec-multiple-channels.yml index 2534af5a5..6c44e62f0 100644 --- a/asyncapi-cli/src/test/resources/specs/spec-multiple-channels.yml +++ b/asyncapi-cli/src/test/resources/specs/spec-multiple-channels.yml @@ -1,4 +1,4 @@ -asyncapi: 2.1.0 +asyncapi: 2.6.0 components: schemas: GenericEventWrapper: diff --git a/asyncapi-cli/src/test/resources/testng.xml b/asyncapi-cli/src/test/resources/testng.xml index 750f0b773..ef90b8c46 100644 --- a/asyncapi-cli/src/test/resources/testng.xml +++ b/asyncapi-cli/src/test/resources/testng.xml @@ -41,6 +41,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/ballerina_project/Ballerina.toml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/ballerina_project/Ballerina.toml new file mode 100644 index 000000000..290816894 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/ballerina_project/Ballerina.toml @@ -0,0 +1,5 @@ +[package] +org= "ballerina" +name= "test" +version= "0.0.0" + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/ballerina_project/Package.md b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/ballerina_project/Package.md new file mode 100644 index 000000000..ff3dffe23 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/ballerina_project/Package.md @@ -0,0 +1,145 @@ +## Module overview + +The OpenAPI tools provide the following capabilities. + + 1. Generate the Ballerina service or client code for a given OpenAPI definition. + 2. Export the OpenAPI definition of a Ballerina service. + 3. Validate the service implementation of a given OpenAPI contract. + +The `openapi` command in Ballerina is used for OpenAPI to Ballerina and Ballerina to OpenAPI code generations. +Code generation from OpenAPI to Ballerina can produce `ballerina service stubs` and `ballerina client stubs`. +The OpenAPI compiler plugin will allow you to validate a service implementation against an OpenAPI contract during + the compile time. +This plugin ensures that the implementation of a service does not deviate from its OpenAPI contract. + +### OpenAPI to Ballerina +#### Generate Service and Client Stub from an OpenAPI Contract + +```bash +bal openapi -i + [--service-name: generated files name] + [--tags: tags list] + [--operations: operationsID list] + [--mode service|client ] + [(-o|--output): output file path] +``` +Generates both the Ballerina service and Ballerina client stub for a given OpenAPI file. + +This `-i ` parameter of the command is mandatory. It will get the path to the + OpenAPI contract file (i.e., `my-api.yaml` or `my-api.json`) as an input. + +The `--service-name` is an optional parameter, which allows you to change the generated service name. + +You can give the specific tags and operations that you need to document as services without documenting all the operations using these optional `--tags` and `--operations` commands. + +The `(-o|--output)` is an optional parameter. You can use this to give the output path of the generated files. +If not, it will take the execution path as the output path. + +##### Modes +If you want to generate a service only, you can set the mode as `service` in the OpenAPI tool. + +```bash +bal openapi -i --mode service [(-o|--output) output file path] +``` + +If you want to generate a client only, you can set the mode as `client` in the OpenAPI tool. +This client can be used in client applications to call the service defined in the OpenAPI file. + +```bash +bal openapi -i --mode client + [(-o|--output) output file path] +``` + +### Ballerina to OpenAPI +#### Service to OpenAPI Export +```bash +bal openapi -i + [(-o|--output) output openapi file path] +``` +Export the Ballerina service to an OpenAPI Specification 3.0 definition. For the export to work properly, +the input Ballerina service should be defined using the basic service and resource-level HTTP annotations. +If you need to document an OpenAPI contract for only one given service, then use this command. +```bash + bal openapi -i (-s | --service) +``` + +### Samples for OpenAPI Commands +#### Generate Service and Client Stub from OpenAPI +```bash + bal openapi -i hello.yaml +``` + +This will generate a Ballerina service and client stub for the `hello.yaml` OpenAPI contract named `hello-service +` and client named `hello-client`. The above command can be run from within anywhere on the execution path. +It is not mandatory to run it from inside the Ballerina project. + +Output: +```bash +The service generation process is complete. The following files were created. +-- hello-service.bal +-- hello-client.bal +-- schema.bal +``` +#### Generate an OpenAPI Contract from a Service + + ```bash + bal openapi -i modules/helloworld/helloService.bal + ``` +This will generate the OpenAPI contracts for the Ballerina services, which are in the `hello.bal` Ballerina file. + ```bash + bal openapi -i modules/helloworld/helloService.bal (-s | --service) helloworld + ``` +This command will generate the `helloworld-openapi.yaml` file that is related to the `helloworld` service inside the + `helloService.bal` file. + +## OpenAPI Validator Compiler Plugin + +The OpenAPI Validator Compiler plugin validates a service against a given OpenAPI contract. +The Compiler Plugin is activated if a service has the `openapi:ServiceInfo` annotation. This plugin compares +the service and the OpenAPI Contract and validates both against a pre-defined set of validation rules. +If any of the rules fail, the plugin will give the result as one or more compilation errors. + +### Annotation for Validator Plugin +The `@openapi:ServiceInfo` annotation is used to bind the service with an OpenAPI contract. You need to add +this annotation to the service file with the required values for enabling the validations. +The following is an example of the annotation usage. +```ballerina +@openapi:ServiceInfo{ + contract: “/path/to/openapi.json|yaml”, + [ tag : “store” ], + [ operations: [“op1”, “op2”] ] + [ failOnErrors]: true/false → default : true + [ excludeTags ]: [“pets”, “user”] + [ excludeOperations: [“op1”, “op2”] ] + } +service greet on new http:Listener(9090) { + ... +} +``` +#### Annotation Support for the Following Attributes: +- **Contract** (Required) : **string** : +Here, you can provide a path to the OpenAPI contract as a string and the OpenAPI file can either be `.yaml` or `.json` +This is a required attribute. + +- **Tag** (Optional) : **string[]?** : +The compiler will only validate resources against operations, which are tagged with a tag specified in the list. +If not specified, the compiler will validate resources against all the operations defined in the OpenAPI contract. + +- **Operations** (Optional): **string[]?** : +Should contain a list of operation names that need to be validated against the resources in the service. +If not specified, the compiler will validate resources against all the operations defined in the OpenAPI contract. If both tags and operations are defined, it will validate against the union set of the resources. + +- **ExcludeTags** (Optional) : **string[]?** : +This feature is for users to store the tag. It does not need to be validated. +At the same time, the `excludeTag` and `Tag` cannot store and the plugin will generate warning messages regarding + it. + +- **ExcludeOperations** (Optional) : **string[]?** : +This feature is for users to store the operations that do not need to be validated. +At the same time, the `excludeOperations` and `Operations` can not store and they will generate warning messages. +The `Tag` feature can store with `excludeOperations`. Then, all the tag operations will be validated except the `exclude` + operations. + +- **FailOnErrors** (Optional) : **boolean value** : +If you need to turn off the validation, add this to the annotation with the value as `false`. + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/custome_api_key_doc.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/custome_api_key_doc.yaml new file mode 100644 index 000000000..37342322f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/custome_api_key_doc.yaml @@ -0,0 +1,321 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/header_api_key.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/header_api_key.yaml new file mode 100644 index 000000000..380e64aee --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/header_api_key.yaml @@ -0,0 +1,321 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - API-X-KEY: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + API-X-KEY: + type: apiKey + description: API key to authorize requests. + name: API-X-KEY + in: header diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/header_api_key_only.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/header_api_key_only.yaml new file mode 100644 index 000000000..fd58421c9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/header_api_key_only.yaml @@ -0,0 +1,248 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - API-X-KEY: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + API-X-KEY: + type: apiKey + description: API key to authorize requests. + name: API-X-KEY + in: header diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiline_api_key_desc.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiline_api_key_desc.yaml new file mode 100644 index 000000000..b6bbbd52a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiline_api_key_desc.yaml @@ -0,0 +1,333 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: > + To use API you have to sign up and get your own API key. Unify API accounts have sandbox mode and live mode API keys. + To change modes just use the appropriate key to get a live or test object. + + Authenticate your API requests by including your test or live secret API key in the request header. + + You should use the public keys on the SDKs and the secret keys to authenticate API requests. + + **Do not share or include your secret API keys on client side code.** Your API keys carry significant privileges. Please ensure to keep them 100% secure and be sure to not share your secret API keys in areas that are publicly accessible like GitHub. + + Learn how to set the Authorization header inside Postman https://learning.postman.com/docs/postman/sending-api-requests/authorization/#api-key + + Go to Unify to grab your API KEY https://openweathermap/me/api-keys + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiple_api_keys.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiple_api_keys.yaml new file mode 100644 index 000000000..73f3df726 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiple_api_keys.yaml @@ -0,0 +1,326 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. + name: appid + in: query + API-X-Key: + type: apiKey + description: API key to authorize requests. + name: API-X-Key + in: header diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiple_apikey_descriptions.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiple_apikey_descriptions.yaml new file mode 100644 index 000000000..24587ca8e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/multiple_apikey_descriptions.yaml @@ -0,0 +1,326 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize GET requests. + name: appid + in: query + x_api_key: + type: apiKey + description: API key to authorize POST requests. + name: X-API-Key + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/query_api_key.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/query_api_key.yaml new file mode 100644 index 000000000..37342322f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/api_key/query_api_key.yaml @@ -0,0 +1,321 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/basic_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/basic_auth.yaml new file mode 100644 index 000000000..1cc792797 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/basic_auth.yaml @@ -0,0 +1,416 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - basicAuth: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + basicAuth: + type: http + scheme: basic \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/bearer_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/bearer_auth.yaml new file mode 100644 index 000000000..001eb46c5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/bearer_auth.yaml @@ -0,0 +1,418 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - bearerAuth: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + bearerAuth: + type: http + scheme: bearer + links: {} + callbacks: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/multiple_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/multiple_auth.yaml new file mode 100644 index 000000000..3320f1067 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/http/multiple_auth.yaml @@ -0,0 +1,422 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - bearerAuth: [] + - basicAuth: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + bearerAuth: + type: http + scheme: bearer + basicAuth: + type: http + scheme: basic + links: {} + callbacks: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_authorization_code.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_authorization_code.yaml new file mode 100644 index 000000000..fdfa9e707 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_authorization_code.yaml @@ -0,0 +1,421 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2AuthCode: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2AuthCode: + type: oauth2 + description: For more information, see https://api.slack.com/docs/oauth + flows: + authorizationCode: + authorizationUrl: https://login.salesforce.com/services/oauth2/autherize + tokenUrl: https://login.salesforce.com/services/oauth2/token + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_authorization_code_without_tokenurl.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_authorization_code_without_tokenurl.yaml new file mode 100644 index 000000000..f83e55f73 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_authorization_code_without_tokenurl.yaml @@ -0,0 +1,119 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2AuthCode: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + MessagewithErrorCode: + properties: + code: + type: string + description: Code + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2AuthCode: + type: oauth2 + description: For more information, see https://api.slack.com/docs/oauth + flows: + authorizationCode: + authorizationUrl: https://login.salesforce.com/services/oauth2/autherize + tokenUrl: "" + scopes: {} + \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_client_credential.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_client_credential.yaml new file mode 100644 index 000000000..ed73cf2e1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_client_credential.yaml @@ -0,0 +1,420 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2ClientCredentials: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2ClientCredentials: + type: oauth2 + description: See salesforce.help.com + flows: + clientCredentials: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_client_credential_without_tokenurl.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_client_credential_without_tokenurl.yaml new file mode 100644 index 000000000..703b44f46 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_client_credential_without_tokenurl.yaml @@ -0,0 +1,420 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2ClientCredentials: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2ClientCredentials: + type: oauth2 + description: See salesforce.help.com + flows: + clientCredentials: + tokenUrl: "" + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_implicit.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_implicit.yaml new file mode 100644 index 000000000..ae9671a81 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_implicit.yaml @@ -0,0 +1,420 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2Implicit: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2Implicit: + type: oauth2 + description: See salesforce.help.com + flows: + implicit: + authorizationUrl: https://test.salesforce.com/services/oauth2/authorize + scopes: {} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_multipleflows.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_multipleflows.yaml new file mode 100644 index 000000000..d135453cc --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_multipleflows.yaml @@ -0,0 +1,425 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oauth_2_0: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oauth_2_0: + type: oauth2 + description: Authentication based on OAuth 2.0. + flows: + authorizationCode: + authorizationUrl: /oauth/authorize + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} + password: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_password.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_password.yaml new file mode 100644 index 000000000..778837b7b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_password.yaml @@ -0,0 +1,420 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2Password: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2Password: + type: oauth2 + description: Authentication based on OAuth 2.0. + flows: + password: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_password_without_tokenurl.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_password_without_tokenurl.yaml new file mode 100644 index 000000000..c8da5efe5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/oauth2_password_without_tokenurl.yaml @@ -0,0 +1,118 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2Password: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + MessagewithErrorCode: + properties: + code: + type: string + description: Code + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2Password: + type: oauth2 + description: Authentication based on OAuth 2.0. + flows: + password: + tokenUrl: "" + scopes: {} + \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/unsupported_security_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/unsupported_security_schema.yaml new file mode 100644 index 000000000..aaa36fed7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Auth/oauth2/unsupported_security_schema.yaml @@ -0,0 +1,425 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2ClientCredentials: [] + - ApiKey1: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2ClientCredentials: + type: oauth2 + description: See salesforce.help.com + flows: + clientCredentials: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} + ApiKey1: + type: apiKey + in: query + name: Salesfore_API-Key \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_param_with_default_value.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_param_with_default_value.yaml new file mode 100644 index 000000000..b46290582 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_param_with_default_value.yaml @@ -0,0 +1,97 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + default: 5 + lat: + type: string + description: "Latitude" + default: "78'08" + lon: + type: string + description: 'Longtitude' + default: "90'78" + exclude: + type: string + description: 'exclude' + default: "56'89" + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_parameter.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_parameter.yaml new file mode 100644 index 000000000..93475b49b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_parameter.yaml @@ -0,0 +1,93 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_with_query.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_with_query.yaml new file mode 100644 index 000000000..fdf2d7c61 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/HeaderParam/header_with_query.yaml @@ -0,0 +1,113 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' + headers: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/array_type_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/array_type_response.yaml new file mode 100644 index 000000000..712e6d4dd --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/array_type_response.yaml @@ -0,0 +1,57 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: array + items: + $ref: "#/components/schemas/Pet" + Pet: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/boolean_type_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/boolean_type_response.yaml new file mode 100644 index 000000000..4abb8d798 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/boolean_type_response.yaml @@ -0,0 +1,53 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: boolean + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/float_type_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/float_type_response.yaml new file mode 100644 index 000000000..b63c96a2b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/float_type_response.yaml @@ -0,0 +1,53 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: number + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/int_type_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/int_type_response.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/map_type_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/map_type_response.yaml new file mode 100644 index 000000000..4650efe56 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/map_type_response.yaml @@ -0,0 +1,54 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + additionalProperties: true + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/one_of_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/one_of_response.yaml new file mode 100644 index 000000000..0e99c09f9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/one_of_response.yaml @@ -0,0 +1,114 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: boolean + - payload: + type: object + additionalProperties: {} + - payload: + type: object + additionalProperties: + type: string + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/Payment' +components: + schemas: + Subscribe: + type: object + required: + - body + - event + properties: + body: + type: string + event: + type: string + const: Subscribe + Payment: + type: object + required: + - cardholderName + - cardNumber + - expiryMonth + - expiryYear + - event + properties: + cardholderName: + type: string + description: Name of the card holder + cardNumber: + type: integer + description: Card number + format: int64 + expiryMonth: + type: string + description: Expiration month of the card in mm + expiryYear: + type: string + description: Expiaration year of the card in yyyy + event: + type: string + const: Payment + description: Event description + description: Reperesents payement for rooms + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: boolean + x-response-type: simple-rpc + Payment: + payload: + $ref: '#/components/schemas/Payment' + description: Payment representation + description: Represents Snowpeak payment resource + x-response: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: object + additionalProperties: {} + - payload: + type: object + additionalProperties: + type: string + description: '`PaymentCreated` or `PaymentConflict` representation' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/payload_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/payload_response.yaml new file mode 100644 index 000000000..4932f89e8 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/payload_response.yaml @@ -0,0 +1,100 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Represents Snowpeak location resource + subscribe: + message: + payload: + type: array + items: + $ref: '#/components/schemas/Location' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + Link: + type: object + required: + - rel + - href + properties: + rel: + type: string + description: linnk rel + href: + type: string + description: link href + mediaTypes: + type: array + items: + type: string + description: link mediatype + description: Link details + Links: + type: object + required: + - links + properties: + links: + type: array + items: + $ref: '#/components/schemas/Link' + description: Array links + description: Link details + Location: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - name + - id + - address + properties: + name: + type: string + description: Name of the location + id: + type: string + description: Unique identification + address: + type: string + description: Address of the location + description: Represents locations + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/Location' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/string_type_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/string_type_response.yaml new file mode 100644 index 000000000..bdb842cd5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/InvalidResponse/string_type_response.yaml @@ -0,0 +1,53 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/NoServerUrl/missing_server_url.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/NoServerUrl/missing_server_url.yaml new file mode 100644 index 000000000..1f8a6651e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/NoServerUrl/missing_server_url.yaml @@ -0,0 +1,179 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + Error: + type: object + required: + - type + properties: + type: + type: string + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + description: subscribe payload description + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + description: subscribe response description + x-response-type: server-streaming + description: subscribemessage description + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc +x-dispatcherKey: type \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_param_duplicated_name.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_param_duplicated_name.yaml new file mode 100644 index 000000000..1ed2f54c5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_param_duplicated_name.yaml @@ -0,0 +1,71 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1/{version}/version-name/{version-name}: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + version: + schema: + type: integer + description: Version Id + version-name: + schema: + type: string + description: Version Name +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_param_with_ref_schemas.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_param_with_ref_schemas.yaml new file mode 100644 index 000000000..c1141f29b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_param_with_ref_schemas.yaml @@ -0,0 +1,72 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + description: Unique identification of location + schema: + $ref: "#/components/schemas/Id" +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + Id: + type: integer + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_invalid.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_invalid.yaml new file mode 100644 index 000000000..627048888 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_invalid.yaml @@ -0,0 +1,73 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + description: Unique identification of location + schema: + type: array + items: + type: integer +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_invalid02.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_invalid02.yaml new file mode 100644 index 000000000..da26cd6e1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_invalid02.yaml @@ -0,0 +1,71 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + description: Unique identification of location + schema: + type: int +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_special_name.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_special_name.yaml new file mode 100644 index 000000000..f6a8de4c0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_special_name.yaml @@ -0,0 +1,74 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1/{version}/v2/{version-name}: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + version: + schema: + type: integer + description: Version Id + version-name: + schema: + type: string + description: Version Name +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_valid.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_valid.yaml new file mode 100644 index 000000000..f462dbbd9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/PathParam/path_parameter_valid.yaml @@ -0,0 +1,187 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + Error: + type: object + required: + - type + properties: + type: + type: string + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + description: subscribe payload description + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + description: subscribe response description + x-response-type: server-streaming + description: subscribemessage description + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_with_default_value.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_with_default_value.yaml new file mode 100644 index 000000000..383a7a2ec --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_with_default_value.yaml @@ -0,0 +1,96 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + description: query params + properties: + offset: + type: boolean + default: true + description: "Offset" + lat: + type: string + default: "05'06'" + description: "Latitude" + lon: + type: string + default: "90'05" + description: "Longtitude" + exclude: + type: string + default: 'current' + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_with_ref_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_with_ref_schema.yaml new file mode 100644 index 000000000..9c07f6668 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_with_ref_schema.yaml @@ -0,0 +1,100 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + description: query params + properties: + offset: + type: boolean + default: true + description: "Offset" + lat: + type: string + default: "78'" + $ref: '#/components/schemas/Latitude' + description: "Latitude" + lon: + type: string + default: "90'05" + description: "Longtitude" + exclude: + type: string + default: 'current' + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Latitude: + type: string + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_without_default_value.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_without_default_value.yaml new file mode 100644 index 000000000..e731945b5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/QueryParam/query_param_without_default_value.yaml @@ -0,0 +1,91 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + description: query params + properties: + offset: + type: boolean + description: "Offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: "Longtitude" + exclude: + type: string + description: 'exclude' + units: + type: integer + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Real/gemini_websocket.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Real/gemini_websocket.yaml new file mode 100644 index 000000000..12f02097c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Real/gemini_websocket.yaml @@ -0,0 +1,210 @@ +# +# +# +# This example showcases usage of AsyncAPI for the purpose of describing a WebSocket API. It is based on a real public service maintained by company called Gemini that provides cryptocurency trading products. It uses AsyncAPI bindings. +# +# This AsyncAPI document describes their v1 of the API. The v2 is also available and changes in the way that it provides a multimessage channel, where you subscribe for messages by sending a subscription message instead of using query parameters. For example with multimessage channel check out this article https://www.asyncapi.com/blog/websocket-part2 about another real public API called Kraken +# +# All available learning materials about AsyncAPI and WebSocket are: +# - WebSocket, Shrek, and AsyncAPI - An Opinionated Intro article: https://www.asyncapi.com/blog/websocket-part1 +# - Creating AsyncAPI for WebSocket API - Step by Step article: https://www.asyncapi.com/blog/websocket-part2 +# - From API-First to Code Generation - A WebSocket Use Case article: https://www.asyncapi.com/blog/websocket-part3 +# - Live stream about topics mentioned in part 1 and 2 articles: https://www.youtube.com/watch?v=8tFBcf31e_c +# + +asyncapi: '2.5.0' + +# +# Overal information for users of the application +# +info: + title: Gemini Market Data Websocket API + version: '1.0.0' + contact: + name: Gemini + url: https://www.gemini.com/ + description: | + Market data is a public API that streams all the market data on a given symbol. + + You can quickly play with the API using [websocat](https://github.com/vi/websocat#installation) like this: + ```bash + websocat wss://api.gemini.com/v1/marketdata/btcusd?heartbeat=true -S + ``` + +# +# Link to external docs +# +externalDocs: + url: https://docs.sandbox.gemini.com/websocket-api/#market-data + +# +# Details on how to connect to the application +# +servers: + public: + url: wss://api.gemini.com + protocol: wss + +# +# Details about all the channels that you can listen to or send to messages +# +channels: + /v1/marketdata/{symbol}: + parameters: + symbol: + description: | + Symbols are formatted as CCY1CCY2 where prices are in CCY2 and quantities are in CCY1. To read more click [here](https://docs.sandbox.gemini.com/websocket-api/#symbols-and-minimums). + schema: + type: string + enum: ['btcusd', 'ethbtc', 'ethusd', 'zecusd', 'zecbtc', 'zeceth', 'zecbch', 'zecltc', 'bchusd', 'bchbtc', 'bcheth', 'ltcusd', 'ltcbtc', 'ltceth', 'ltcbch', 'batusd', 'daiusd', 'linkusd', 'oxtusd', 'batbtc', 'linkbtc', 'oxtbtc', 'bateth', 'linketh', 'oxteth', 'ampusd', 'compusd', 'paxgusd', 'mkrusd', 'zrxusd', 'kncusd', 'manausd', 'storjusd', 'snxusd', 'crvusd', 'balusd', 'uniusd', 'renusd', 'umausd', 'yfiusd', 'btcdai', 'ethdai', 'aaveusd', 'filusd', 'btceur', 'btcgbp', 'etheur', 'ethgbp', 'btcsgd', 'ethsgd', 'sklusd', 'grtusd', 'bntusd', '1inchusd', 'enjusd', 'lrcusd', 'sandusd', 'cubeusd', 'lptusd', 'bondusd', 'maticusd', 'injusd', 'sushiusd'] + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + description: | + The semantics of entry type filtering is: + + If any entry type is specified as true or false, all of them must be explicitly flagged true to show up in the response + If no entry types filtering parameters are included in the url, then all entry types will appear in the response + + NOTE: top_of_book has no meaning and initial book events are empty when only trades is specified + properties: + heartbeat: + type: boolean + default: false + description: Optionally add this parameter and set to true to receive a heartbeat every 5 seconds + top_of_book: + type: boolean + default: false + description: If absent or false, receive full order book depth; if present and true, receive top of book only. Only applies to bids and offers. + bids: + type: boolean + default: true + description: Include bids in change events + offers: + type: boolean + default: true + description: Include asks in change events + trades: + type: boolean + default: true + description: Include trade events + auctions: + type: boolean + default: true + description: Include auction events + subscribe: + summary: Receive market updates on a given symbol + message: + $ref: '#/components/messages/marketData' + +# +# All reusable parts for readability and staying DRY +# +components: + messages: + marketData: + summary: Message with marked data information. + description: | + The initial response message will show the existing state of the order book. Subsequent messages will show all executed trades, as well as all other changes to the order book from orders placed or canceled. + payload: + $ref: '#/components/schemas/market' + examples: + - name: updateMessage + summary: Example of an update message that contains a change in price information. + payload: + type: update + eventId: 36902233362 + timestamp: 1619769673 + timestamps: 1619769673527 + socket_sequence: 661 + events: + - type: change + side: bid + price: 54350.40 + remaining: 0.002 + delta: 0.002 + reason: place + - name: heartbeatMessage + summary: Example of additional heartbeat message when you enable them. + payload: + type: heartbeat + socket_sequence: 1656 + schemas: + market: + type: object + oneOf: + - $ref: '#/components/schemas/heartbeat' + - $ref: '#/components/schemas/update' + heartbeat: + allOf: + - properties: + type: + type: string + const: heartbeat + required: + - type + - $ref: '#/components/schemas/default' + update: + allOf: + - properties: + type: + type: string + const: update + eventId: + type: integer + description: A monotonically increasing sequence number indicating when this change occurred. These numbers are persistent and consistent between market data connections. + events: + $ref: '#/components/schemas/events' + timestamp: + type: number + description: The timestamp in seconds for this group of events (included for compatibility reasons). We recommend using the timestampms field instead. + timestampms: + type: number + description: The timestamp in milliseconds for this group of events. + required: + - type + - eventId + - events + - timestamp + - timestampms + - $ref: '#/components/schemas/default' + default: + type: object + description: This object is always part of the payload. In case of type=heartbeat, these are the only fields. + required: + - type + - socket_sequence + properties: + socket_sequence: + type: integer + description: zero-indexed monotonic increasing sequence number attached to each message sent - if there is a gap in this sequence, you have missed a message. If you choose to enable heartbeats, then heartbeat and update messages will share a single increasing sequence. See [Sequence Numbers](https://docs.sandbox.gemini.com/websocket-api/#sequence-numbers) for more information. + events: + type: array + description: Either a change to the order book, or the indication that a trade has occurred. + items: + type: object + additionalProperties: false + properties: + type: + type: string + enum: ['trade', 'change', 'auction, block_trade'] + price: + type: number + multipleOf: 0.01 + description: The price of this order book entry. + side: + type: string + enum: ['bid', 'side'] + reason: + type: string + enum: ['place', 'trade', 'cancel', 'initial'] + description: Indicates why the change has occurred. initial is for the initial response message, which will show the entire existing state of the order book. + remaining: + type: number + description: The quantity remaining at that price level after this change occurred. May be zero if all orders at this price level have been filled or canceled. + delta: + type: number + description: The quantity changed. May be negative, if an order is filled or canceled. For initial messages, delta will equal remaining. +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Real/kraken_websocket.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Real/kraken_websocket.yaml new file mode 100644 index 000000000..9d682b49d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Real/kraken_websocket.yaml @@ -0,0 +1,379 @@ +asyncapi: 2.5.0 + +info: + title: Kraken Websockets API + version: '1.8.0' + description: | + WebSockets API offers real-time market data updates. WebSockets is a bidirectional protocol offering fastest real-time data, helping you build real-time applications. The public message types presented below do not require authentication. Private-data messages can be subscribed on a separate authenticated endpoint. + + ### General Considerations + + - TLS with SNI (Server Name Indication) is required in order to establish a Kraken WebSockets API connection. See Cloudflare's [What is SNI?](https://www.cloudflare.com/learning/ssl/what-is-sni/) guide for more details. + - All messages sent and received via WebSockets are encoded in JSON format + - All decimal fields (including timestamps) are quoted to preserve precision. + - Timestamps should not be considered unique and not be considered as aliases for transaction IDs. Also, the granularity of timestamps is not representative of transaction rates. + - At least one private message should be subscribed to keep the authenticated client connection open. + - Please use REST API endpoint [AssetPairs](https://www.kraken.com/features/api#get-tradable-pairs) to fetch the list of pairs which can be subscribed via WebSockets API. For example, field 'wsname' gives the supported pairs name which can be used to subscribe. + - Cloudflare imposes a connection/re-connection rate limit (per IP address) of approximately 150 attempts per rolling 10 minutes. If this is exceeded, the IP is banned for 10 minutes. + - Recommended reconnection behaviour is to (1) attempt reconnection instantly up to a handful of times if the websocket is dropped randomly during normal operation but (2) after maintenance or extended downtime, attempt to reconnect no more quickly than once every 5 seconds. There is no advantage to reconnecting more rapidly after maintenance during cancel_only mode. + +servers: + public: + url: ws.kraken.com + protocol: wss + description: | + Public server available without authorization. + Once the socket is open you can subscribe to a public channel by sending a subscribe request message. + private: + url: ws-auth.kraken.com + protocol: wss + description: | + Private server that requires authorization. + Once the socket is open you can subscribe to private-data channels by sending an authenticated subscribe request message. + + The API client must request an authentication "token" via the following REST API endpoint "GetWebSocketsToken" to connect to WebSockets Private endpoints. For more details read https://support.kraken.com/hc/en-us/articles/360034437672-How-to-retrieve-a-WebSocket-authentication-token-Example-code-in-Python-3 + + The resulting token must be provided in the "token" field of any new private WebSocket feed subscription: + ``` + { + "event": "subscribe", + "subscription": + { + "name": "ownTrades", + "token": "WW91ciBhdXRoZW50aWNhdGlvbiB0b2tlbiBnb2VzIGhlcmUu" + } + } + ``` + +channels: + /: + publish: + description: Send messages to the API + operationId: processReceivedMessage + message: + oneOf: + - $ref: '#/components/messages/ping' + - $ref: '#/components/messages/subscribe' + - $ref: '#/components/messages/unsubscribe' + + subscribe: + description: Messages that you receive from the API + operationId: sendMessage + message: + oneOf: + - $ref: '#/components/messages/pong' + - $ref: '#/components/messages/heartbeat' + - $ref: '#/components/messages/systemStatus' + - $ref: '#/components/messages/subscriptionStatus' + +components: + messages: + ping: + summary: Ping server to determine whether connection is alive + description: Client can ping server to determine whether connection is alive, server responds with pong. This is an application level ping as opposed to default ping in websockets standard which is server initiated + payload: + $ref: '#/components/schemas/ping' + x-response: + $ref: '#/components/messages/pong' + heartbeat: + description: Server heartbeat sent if no subscription traffic within 1 second (approximately) + payload: + $ref: '#/components/schemas/heartbeat' + pong: + summary: Pong is a response to ping message + description: Server pong response to a ping to determine whether connection is alive. This is an application level pong as opposed to default pong in websockets standard which is sent by client in response to a ping + payload: + $ref: '#/components/schemas/pong' + systemStatus: + description: Status sent on connection or system status changes. + payload: + $ref: '#/components/schemas/systemStatus' + examples: + - payload: + connectionID: 8628615390848610000 + event: systemStatus + status: online + version: 1.0.0 + subscribe: + description: Subscribe to a topic on a single or multiple currency pairs. + payload: + $ref: '#/components/schemas/subscribe' + examples: + - payload: + event: subscribe + pair: + - XBT/USD + - XBT/EUR + subscription: + name: ticker + - payload: + event: subscribe + subscription: + name: ownTrades + token: WW91ciBhdXRoZW50aWNhdGlvbiB0b2tlbiBnb2VzIGhlcmUu + x-response: + $ref: '#/components/messages/subscriptionStatus' + unsubscribe: + description: Unsubscribe, can specify a channelID or multiple currency pairs. + payload: + $ref: '#/components/schemas/unsubscribe' + examples: + - payload: + event: unsubscribe + pair: + - XBT/EUR + - XBT/USD + subscription: + name: ticker + - payload: + event: unsubscribe + subscription: + name: ownTrades + token: WW91ciBhdXRoZW50aWNhdGlvbiB0b2tlbiBnb2VzIGhlcmUu + x-response: + $ref: '#/components/messages/subscriptionStatus' + subscriptionStatus: + description: Subscription status response to subscribe, unsubscribe or exchange initiated unsubscribe. + payload: + $ref: '#/components/schemas/subscriptionStatus' + examples: + - payload: + channelID: 10001 + channelName: ohlc-5 + event: subscriptionStatus + pair: XBT/EUR + reqid: 42 + status: unsubscribed + subscription: + interval: 5 + name: ohlc + - payload: + errorMessage: Subscription depth not supported + event: subscriptionStatus + pair: XBT/USD + status: error + subscription: + depth: 42 + name: book + + schemas: + ping: + type: object + properties: + event: + type: string + const: ping + reqid: + $ref: '#/components/schemas/reqid' + required: + - event + heartbeat: + type: object + properties: + event: + type: string + const: heartbeat + required: + - event + pong: + type: object + properties: + event: + type: string + const: pong + reqid: + $ref: '#/components/schemas/reqid' + required: + - event + systemStatus: + type: object + properties: + event: + type: string + const: systemStatus + connectionID: + type: integer + description: The ID of the connection + status: + $ref: '#/components/schemas/status' + version: + type: string + required: + - event + status: + type: string + enum: + - online + - maintenance + - cancel_only + - limit_only + - post_only + subscribe: + type: object + properties: + event: + type: string + const: subscribe + reqid: + $ref: '#/components/schemas/reqid' + pair: + $ref: '#/components/schemas/pair' + subscription: + type: object + properties: + depth: + $ref: '#/components/schemas/depth' + interval: + $ref: '#/components/schemas/interval' + name: + $ref: '#/components/schemas/name' + ratecounter: + $ref: '#/components/schemas/ratecounter' + snapshot: + $ref: '#/components/schemas/snapshot' + token: + $ref: '#/components/schemas/token' + required: + - name + required: + - event + unsubscribe: + type: object + properties: + event: + type: string + const: unsubscribe + reqid: + $ref: '#/components/schemas/reqid' + pair: + $ref: '#/components/schemas/pair' + subscription: + type: object + properties: + depth: + $ref: '#/components/schemas/depth' + interval: + $ref: '#/components/schemas/interval' + name: + $ref: '#/components/schemas/name' + token: + $ref: '#/components/schemas/token' + required: + - name + required: + - event + subscriptionStatus: + type: object + oneOf: + - $ref: '#/components/schemas/subscriptionStatusError' + - $ref: '#/components/schemas/subscriptionStatusSuccess' + subscriptionStatusError: + allOf: + - properties: + errorMessage: + type: string + required: + - errorMessage + - $ref: '#/components/schemas/subscriptionStatusCommon' + subscriptionStatusSuccess: + allOf: + - properties: + channelID: + type: integer + description: ChannelID on successful subscription, applicable to public messages only. + channelName: + type: string + description: Channel Name on successful subscription. For payloads 'ohlc' and 'book', respective interval or depth will be added as suffix. + required: + - channelID + - channelName + - $ref: '#/components/schemas/subscriptionStatusCommon' + subscriptionStatusCommon: + type: object + required: + - event + properties: + event: + type: string + const: subscriptionStatus + reqid: + $ref: '#/components/schemas/reqid' + pair: + $ref: '#/components/schemas/pair' + status: + $ref: '#/components/schemas/status' + subscription: + required: + - name + type: object + properties: + depth: + $ref: '#/components/schemas/depth' + interval: + $ref: '#/components/schemas/interval' + maxratecount: + $ref: '#/components/schemas/maxratecount' + name: + $ref: '#/components/schemas/name' + token: + $ref: '#/components/schemas/token' + interval: + type: integer + description: Time interval associated with ohlc subscription in minutes. + default: 1 + enum: + - 1 + - 5 + - 15 + - 30 + - 60 + - 240 + - 1440 + - 10080 + - 21600 + name: + type: string + description: The name of the channel you subscribe too. + enum: + - book + - ohlc + - openOrders + - ownTrades + - spread + - ticker + - trade + token: + type: string + description: base64-encoded authentication token for private-data endpoints. + depth: + type: integer + default: 10 + enum: + - 10 + - 25 + - 100 + - 500 + - 1000 + description: Depth associated with book subscription in number of levels each side. + maxratecount: + type: integer + description: Max rate-limit budget. Compare to the ratecounter field in the openOrders updates to check whether you are approaching the rate limit. + ratecounter: + type: boolean + default: false + description: Whether to send rate-limit counter in updates (supported only for openOrders subscriptions) + snapshot: + type: boolean + default: true + description: Whether to send historical feed data snapshot upon subscription (supported only for ownTrades subscriptions) + reqid: + type: integer + description: client originated ID reflected in response message. + pair: + type: array + description: Array of currency pairs. + items: + type: string + description: Format of each pair is "A/B", where A and B are ISO 4217-A3 for standardized assets and popular unique symbol if not standardized. + pattern: '[A-Z\s]+\/[A-Z\s]+' +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/RemoteFunction/remote_function_description.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/RemoteFunction/remote_function_description.yaml new file mode 100644 index 000000000..63ec58a84 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/RemoteFunction/remote_function_description.yaml @@ -0,0 +1,67 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: 'subscribe request description' + x-response: + $ref: '#/components/messages/UnSubscribe' + description: 'unsubscribe response description' + x-response-type: simple-rpc + description: 'remote description' +x-dispatcherKey: event + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/multiple_response_with_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/multiple_response_with_dispatcherStreamId.yaml new file mode 100644 index 000000000..fc1ed2e69 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/multiple_response_with_dispatcherStreamId.yaml @@ -0,0 +1,104 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + oneOf: + - $ref: '#/components/messages/Response' + - $ref: '#/components/messages/UnSubscribe' + publish: + message: + oneOf: + - $ref: '#/components/messages/Request' + - $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + Request: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + Response: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc + Response: + payload: + $ref: '#/components/schemas/Response' + Request: + payload: + $ref: '#/components/schemas/Request' + x-response: + $ref: '#/components/messages/Response' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/multiple_response_with_no_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/multiple_response_with_no_dispatcherStreamId.yaml new file mode 100644 index 000000000..12c9a0eb4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/multiple_response_with_no_dispatcherStreamId.yaml @@ -0,0 +1,103 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + oneOf: + - $ref: '#/components/messages/Response' + - $ref: '#/components/messages/UnSubscribe' + publish: + message: + oneOf: + - $ref: '#/components/messages/Request' + - $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + Request: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + Response: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc + Response: + payload: + $ref: '#/components/schemas/Response' + Request: + payload: + $ref: '#/components/schemas/Request' + x-response: + $ref: '#/components/messages/Response' + x-response-type: simple-rpc +x-dispatcherKey: event + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/one_response_with_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/one_response_with_dispatcherStreamId.yaml new file mode 100644 index 000000000..1e0339b19 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/one_response_with_dispatcherStreamId.yaml @@ -0,0 +1,65 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/one_response_with_no_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/one_response_with_no_dispatcherStreamId.yaml new file mode 100644 index 000000000..17a868a8a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SimpleResponse/one_response_with_no_dispatcherStreamId.yaml @@ -0,0 +1,64 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/multiple_stream_with_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/multiple_stream_with_dispatcherStreamId.yaml new file mode 100644 index 000000000..ef0f7a368 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/multiple_stream_with_dispatcherStreamId.yaml @@ -0,0 +1,252 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/schemas/Testing' + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + Error: + type: object + required: + - type + properties: + type: + type: string + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + Testing: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + Tuple: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming + Testing: + payload: + $ref: '#/components/schemas/Testing' + x-response: + $ref: '#/components/messages/NextMessage' + x-response-type: server-streaming + Tuple: + payload: + $ref: '#/components/schemas/Tuple' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc +x-dispatcherKey: "type" +x-dispatcherStreamId: "id" \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/multiple_stream_with_no_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/multiple_stream_with_no_dispatcherStreamId.yaml new file mode 100644 index 000000000..2425abab0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/multiple_stream_with_no_dispatcherStreamId.yaml @@ -0,0 +1,218 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + Error: + type: object + required: + - type + properties: + type: + type: string + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + Tuple: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming + Tuple: + payload: + $ref: '#/components/schemas/Tuple' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc +x-dispatcherKey: "type" diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/one_stream_with_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/one_stream_with_dispatcherStreamId.yaml new file mode 100644 index 000000000..75dcb9778 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/one_stream_with_dispatcherStreamId.yaml @@ -0,0 +1,112 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' +components: + schemas: + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming +x-dispatcherKey: "type" +x-dispatcherStreamId: "id" \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/one_stream_with_no_dispatcherStreamId.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/one_stream_with_no_dispatcherStreamId.yaml new file mode 100644 index 000000000..236ac4a27 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/StreamResponse/one_stream_with_no_dispatcherStreamId.yaml @@ -0,0 +1,111 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' +components: + schemas: + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming +x-dispatcherKey: "type" diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SubProtocols/graphqloverwebsocket.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SubProtocols/graphqloverwebsocket.yaml new file mode 100644 index 000000000..d50e3524e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/SubProtocols/graphqloverwebsocket.yaml @@ -0,0 +1,189 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + Error: + type: object + required: + - type + properties: + type: + type: string + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + description: subscribe payload description + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + description: subscribe response description + x-response-type: server-streaming + description: subscribemessage description + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc +x-dispatcherKey: type +x-dispatcherStreamId: id \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/apikey_with_no_query_param.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/apikey_with_no_query_param.yaml new file mode 100644 index 000000000..d0fcb0386 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/apikey_with_no_query_param.yaml @@ -0,0 +1,58 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + responses: + 200: + description: Successful response + content: + application/json: + schema: {} + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/complete_util_gen.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/complete_util_gen.yaml new file mode 100644 index 000000000..163de1e1a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/complete_util_gen.yaml @@ -0,0 +1,169 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1/{version}/v2/{version-name}: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' + query: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' + parameters: + version: + schema: + type: integer + description: Version Id + version-name: + schema: + type: string + description: Version Name + +components: + schemas: + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming +x-dispatcherKey: type +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/default_util.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/default_util.yaml new file mode 100644 index 000000000..897b2606d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/default_util.yaml @@ -0,0 +1,69 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/header_parameter.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/header_parameter.yaml new file mode 100644 index 000000000..93475b49b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/header_parameter.yaml @@ -0,0 +1,93 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/path_param_url_encoded.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/path_param_url_encoded.yaml new file mode 100644 index 000000000..0d96efb67 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/path_param_url_encoded.yaml @@ -0,0 +1,126 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1/{version}/v2/{version-name}: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + parameters: + version: + schema: + type: integer + description: Version Id + version-name: + schema: + type: string + description: Version Name + +components: + schemas: + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + x-response-type: server-streaming +x-dispatcherKey: type +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/query_parameter.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/query_parameter.yaml new file mode 100644 index 000000000..04e4fb4e7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/Util/query_parameter.yaml @@ -0,0 +1,93 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /v1: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + description: header params + properties: + offset: + type: integer + description: "offset" + lat: + type: string + description: "Latitude" + lon: + type: string + description: 'Longtitude' + exclude: + type: string + description: 'exclude' + units: + type: integer + default: 12 + description: 'units description' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - type + - event + properties: + type: + type: string + const: UnSubscribe + payload: + type: object + additionalProperties: true + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + description: subscribe description + x-response: + $ref: '#/components/messages/UnSubscribe' + description: unsubscribe description + description: remote description + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_param_with_default_value.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_param_with_default_value.bal new file mode 100644 index 000000000..24b964092 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_param_with_default_value.bal @@ -0,0 +1,29 @@ +# Header parameters as a record +# +public type HeaderParams record {| + # offset + int offset = 5; + # Latitude + string lat = "78'08"; + # Longtitude + string lon = "90'78"; + # exclude + string exclude = "56'89"; + # units description + int units = 12; +|}; + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +public type Subscribe record { + string id; + string event; +}; + +public type UnSubscribe record { + string 'type; + record {} payload?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_parameter_client.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_parameter_client.bal new file mode 100644 index 000000000..73dca3e9c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_parameter_client.bal @@ -0,0 +1,148 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVv1Client { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + # + headerParams - header parameters + public isolated function init(HeaderParams headerParams, websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/v1`; + map headerParam = {"offset": headerParams.offset.toString(), "lat": headerParams.lat, "lon": headerParams.lon, "exclude": headerParams.exclude, "units": headerParams.units.toString()}; + map customHeaders = getCombineHeaders(clientConfig.customHeaders,headerParam); + clientConfig.customHeaders = customHeaders; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # remote description + # + # + subscribe - subscribe description + # + timeout - waiting period to keep the event in the buffer in seconds + # + return - unsubscribe description + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(subscribe.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(subscribe.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_parameter_types.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_parameter_types.bal new file mode 100644 index 000000000..10d4a2c48 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_parameter_types.bal @@ -0,0 +1,29 @@ +# Header parameters as a record +# +public type HeaderParams record {| + # offset + int offset; + # Latitude + string lat; + # Longtitude + string lon; + # exclude + string exclude; + # units description + int units = 12; +|}; + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +public type Subscribe record { + string id; + string event; +}; + +public type UnSubscribe record { + string 'type; + record {} payload?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_with_query.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_with_query.bal new file mode 100644 index 000000000..17d713b4d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/HeaderParam/header_with_query.bal @@ -0,0 +1,151 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVv1Client { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + # + queryParams - query parameters + # + headerParams - header parameters + public isolated function init(HeaderParams headerParams, QueryParams queryParams, websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/v1`; + map queryParam = {"offset": queryParams.offset, "lat": queryParams.lat, "lon": queryParams.lon, "exclude": queryParams.exclude, "units": queryParams.units}; + modifiedUrl = modifiedUrl + check getPathForQueryParam(queryParam); + map headerParam = {"offset": headerParams.offset.toString(), "lat": headerParams.lat, "lon": headerParams.lon, "exclude": headerParams.exclude, "units": headerParams.units.toString()}; + map customHeaders = getCombineHeaders(clientConfig.customHeaders,headerParam); + clientConfig.customHeaders = customHeaders; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # remote description + # + # + subscribe - subscribe description + # + timeout - waiting period to keep the event in the buffer in seconds + # + return - unsubscribe description + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(subscribe.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(subscribe.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/NoServerUrl/missing_server_url.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/NoServerUrl/missing_server_url.bal new file mode 100644 index 000000000..a5e554e65 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/NoServerUrl/missing_server_url.bal @@ -0,0 +1,226 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class ChatClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(string serviceUrl, websocket:ClientConfiguration clientConfig = {}) returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.'type); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # subscribemessage description + # + # + subscribeMessage - subscribe payload description + # + timeout - waiting period to keep the event in the buffer in seconds + # + return - subscribe response description + remote isolated function doSubscribeMessage(SubscribeMessage subscribeMessage, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageCompleteMessageErrorMessageStreamGenerator streamGenerator = new (self.pipes, "subscribeMessage", timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doPingMessage(PingMessage pingMessage, decimal timeout) returns PongMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pingMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("pingMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + PongMessage|error pongMessage = responseMessage.cloneWithType(); + if pongMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", pongMessage); + } + return pongMessage; + } + + remote isolated function doPongMessage(PongMessage pongMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pongMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + remote isolated function doConnectionInitMessage(ConnectionInitMessage connectionInitMessage, decimal timeout) returns ConnectionAckMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = connectionInitMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("connectionInitMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + ConnectionAckMessage|error connectionAckMessage = responseMessage.cloneWithType(); + if connectionAckMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", connectionAckMessage); + } + return connectionAckMessage; + } + + remote isolated function doCompleteMessage(CompleteMessage completeMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = completeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_param_duplicated_name.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_param_duplicated_name.bal new file mode 100644 index 000000000..828da7b1c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_param_duplicated_name.bal @@ -0,0 +1,140 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVv1versionversionnameversionnameClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + # + pathParams - path parameters + public isolated function init(PathParams pathParams, websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/v1/${getEncodedUri(pathParams.version)}/version-name/${getEncodedUri(pathParams.'version\-name)}`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(subscribe.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(subscribe.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_param_with_ref_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_param_with_ref_schema.bal new file mode 100644 index 000000000..bb13cc398 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_param_with_ref_schema.bal @@ -0,0 +1,23 @@ +# Path parameters as a record +# +# + id - Unique identification of location +public type PathParams record {| + Id id; +|}; + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +public type Subscribe record { + string id; + string event; +}; + +public type Id int; + +public type UnSubscribe record { + string 'type; + record {} payload?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_parameter_with_special_name.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_parameter_with_special_name.bal new file mode 100644 index 000000000..6d4130a02 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/PathParam/path_parameter_with_special_name.bal @@ -0,0 +1,140 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVv1versionv2versionnameClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + # + pathParams - path parameters + public isolated function init(PathParams pathParams, websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/v1/${getEncodedUri(pathParams.version)}/v2/${getEncodedUri(pathParams.'version\-name)}`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(subscribe.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(subscribe.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_with_default_value.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_with_default_value.bal new file mode 100644 index 000000000..f1736319e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_with_default_value.bal @@ -0,0 +1,29 @@ +# Query parameters as a record +# +public type QueryParams record {| + # Offset + boolean offset = true; + # Latitude + string lat = "05'06'"; + # Longtitude + string lon = "90'05"; + # exclude + string exclude = "current"; + # units description + int units = 12; +|}; + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +public type Subscribe record { + string id; + string event; +}; + +public type UnSubscribe record { + string 'type; + record {} payload?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_with_ref_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_with_ref_schema.bal new file mode 100644 index 000000000..63bf07442 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_with_ref_schema.bal @@ -0,0 +1,31 @@ +# Query parameters as a record +# +public type QueryParams record {| + # Offset + boolean offset = true; + # Latitude + Latitude lat = "78'"; + # Longtitude + string lon = "90'05"; + # exclude + string exclude = "current"; + # units description + int units = 12; +|}; + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +public type Latitude string; + +public type Subscribe record { + string id; + string event; +}; + +public type UnSubscribe record { + string 'type; + record {} payload?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_without_default_value.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_without_default_value.bal new file mode 100644 index 000000000..55f1b560d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/QueryParam/query_param_without_default_value.bal @@ -0,0 +1,29 @@ +# Query parameters as a record +# +public type QueryParams record {| + # Offset + boolean offset; + # Latitude + string lat; + # Longtitude + string lon; + # exclude + string exclude; + # units description + int units; +|}; + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +public type Subscribe record { + string id; + string event; +}; + +public type UnSubscribe record { + string 'type; + record {} payload?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Real/gemini_websocket.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Real/gemini_websocket.bal new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Real/kraken_websocket.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Real/kraken_websocket.bal new file mode 100644 index 000000000..9fe692f9d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Real/kraken_websocket.bal @@ -0,0 +1,232 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +# WebSockets API offers real-time market data updates. WebSockets is a bidirectional protocol offering fastest real-time data, helping you build real-time applications. The public message types presented below do not require authentication. Private-data messages can be subscribed on a separate authenticated endpoint. +# +# ### General Considerations +# +# - TLS with SNI (Server Name Indication) is required in order to establish a Kraken WebSockets API connection. See Cloudflare's [What is SNI?](https://www.cloudflare.com/learning/ssl/what-is-sni/) guide for more details. +# - All messages sent and received via WebSockets are encoded in JSON format +# - All decimal fields (including timestamps) are quoted to preserve precision. +# - Timestamps should not be considered unique and not be considered as aliases for transaction IDs. Also, the granularity of timestamps is not representative of transaction rates. +# - At least one private message should be subscribed to keep the authenticated client connection open. +# - Please use REST API endpoint [AssetPairs](https://www.kraken.com/features/api#get-tradable-pairs) to fetch the list of pairs which can be subscribed via WebSockets API. For example, field 'wsname' gives the supported pairs name which can be used to subscribe. +# - Cloudflare imposes a connection/re-connection rate limit (per IP address) of approximately 150 attempts per rolling 10 minutes. If this is exceeded, the IP is banned for 10 minutes. +# - Recommended reconnection behaviour is to (1) attempt reconnection instantly up to a handful of times if the websocket is dropped randomly during normal operation but (2) after maintenance or extended downtime, attempt to reconnect no more quickly than once every 5 seconds. There is no advantage to reconnecting more rapidly after maintenance during cancel_only mode. +public client isolated class KrakenWebsocketsAPIClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws.kraken.com") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.event); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Ping server to determine whether connection is alive + # + remote isolated function doPing(Ping ping, decimal timeout) returns Pong|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = ping.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("ping").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + Pong|error pong = responseMessage.cloneWithType(); + if pong is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", pong); + } + return pong; + } + + # Subscribe to a topic on a single or multiple currency pairs. + # + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns SubscriptionStatus|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("subscribe").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + SubscriptionStatus|error subscriptionStatus = responseMessage.cloneWithType(); + if subscriptionStatus is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", subscriptionStatus); + } + return subscriptionStatus; + } + + # Unsubscribe, can specify a channelID or multiple currency pairs. + # + remote isolated function doUnsubscribe(Unsubscribe unsubscribe, decimal timeout) returns SubscriptionStatus|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = unsubscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("unsubscribe").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + SubscriptionStatus|error subscriptionStatus = responseMessage.cloneWithType(); + if subscriptionStatus is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", subscriptionStatus); + } + return subscriptionStatus; + } + + remote isolated function doHeartbeat(decimal timeout) returns Heartbeat|error { + Message|pipe:Error responseMessage = self.pipes.getPipe("heartbeat").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + Heartbeat|error heartbeat = responseMessage.cloneWithType(); + if heartbeat is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", heartbeat); + } + return heartbeat; + } + + remote isolated function doSystemStatus(decimal timeout) returns SystemStatus|error { + Message|pipe:Error responseMessage = self.pipes.getPipe("systemStatus").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + SystemStatus|error systemStatus = responseMessage.cloneWithType(); + if systemStatus is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", systemStatus); + } + return systemStatus; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/RemoteFunction/remote_function_description.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/RemoteFunction/remote_function_description.bal new file mode 100644 index 000000000..2417030e2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/RemoteFunction/remote_function_description.bal @@ -0,0 +1,134 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVlocationsClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/locations`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.event); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # remote description + # + # + subscribe - subscribe request description + # + timeout - waiting period to keep the event in the buffer in seconds + # + return - unsubscribe response description + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("subscribe").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/multiple_response_with_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/multiple_response_with_dispatcherStreamId.bal new file mode 100644 index 000000000..c5bc29ef0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/multiple_response_with_dispatcherStreamId.bal @@ -0,0 +1,172 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVlocationsClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/locations`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doRequest(Request request, decimal timeout) returns Response|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = request.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(request.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(request.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + Response|error response = responseMessage.cloneWithType(); + if response is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", response); + } + return response; + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(subscribe.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(subscribe.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/multiple_response_with_no_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/multiple_response_with_no_dispatcherStreamId.bal new file mode 100644 index 000000000..3a63fe336 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/multiple_response_with_no_dispatcherStreamId.bal @@ -0,0 +1,158 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVlocationsClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/locations`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.event); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doRequest(Request request, decimal timeout) returns Response|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = request.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("request").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + Response|error response = responseMessage.cloneWithType(); + if response is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", response); + } + return response; + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("subscribe").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/one_response_with_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/one_response_with_dispatcherStreamId.bal new file mode 100644 index 000000000..0c76fcab2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/one_response_with_dispatcherStreamId.bal @@ -0,0 +1,139 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVlocationsClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/locations`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(subscribe.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(subscribe.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/one_response_with_no_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/one_response_with_no_dispatcherStreamId.bal new file mode 100644 index 000000000..335b52ed4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SimpleResponse/one_response_with_no_dispatcherStreamId.bal @@ -0,0 +1,129 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class PayloadVlocationsClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/payloadV") returns error? { + self.pipes = new (); + self.writeMessageQueue = new (1000); + string modifiedUrl = serviceUrl + string `/locations`; + websocket:Client websocketEp = check new (modifiedUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.event); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns UnSubscribe|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("subscribe").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + UnSubscribe|error unSubscribe = responseMessage.cloneWithType(); + if unSubscribe is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", unSubscribe); + } + return unSubscribe; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/multiple_stream_with_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/multiple_stream_with_dispatcherStreamId.bal new file mode 100644 index 000000000..49f02e0d5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/multiple_stream_with_dispatcherStreamId.bal @@ -0,0 +1,252 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class ChatClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/chat") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.'type); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doTesting(Testing testing, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = testing.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageStreamGenerator streamGenerator = new (self.pipes, testing.id, timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doSubscribeMessage(SubscribeMessage subscribeMessage, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageCompleteMessageErrorMessageStreamGenerator streamGenerator = new (self.pipes, subscribeMessage.id, timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doPingMessage(PingMessage pingMessage, decimal timeout) returns PongMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pingMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("pingMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + PongMessage|error pongMessage = responseMessage.cloneWithType(); + if pongMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", pongMessage); + } + return pongMessage; + } + + remote isolated function doPongMessage(PongMessage pongMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pongMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + remote isolated function doConnectionInitMessage(ConnectionInitMessage connectionInitMessage, decimal timeout) returns ConnectionAckMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = connectionInitMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("connectionInitMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + ConnectionAckMessage|error connectionAckMessage = responseMessage.cloneWithType(); + if connectionAckMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", connectionAckMessage); + } + return connectionAckMessage; + } + + remote isolated function doCompleteMessage(CompleteMessage completeMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = completeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/multiple_stream_with_no_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/multiple_stream_with_no_dispatcherStreamId.bal new file mode 100644 index 000000000..0b4e76e9f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/multiple_stream_with_no_dispatcherStreamId.bal @@ -0,0 +1,221 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class ChatClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/chat") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.'type); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribeMessage(SubscribeMessage subscribeMessage, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageCompleteMessageErrorMessageStreamGenerator streamGenerator = new (self.pipes, "subscribeMessage", timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doPingMessage(PingMessage pingMessage, decimal timeout) returns PongMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pingMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("pingMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + PongMessage|error pongMessage = responseMessage.cloneWithType(); + if pongMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", pongMessage); + } + return pongMessage; + } + + remote isolated function doPongMessage(PongMessage pongMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pongMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + remote isolated function doConnectionInitMessage(ConnectionInitMessage connectionInitMessage, decimal timeout) returns ConnectionAckMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = connectionInitMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("connectionInitMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + ConnectionAckMessage|error connectionAckMessage = responseMessage.cloneWithType(); + if connectionAckMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", connectionAckMessage); + } + return connectionAckMessage; + } + + remote isolated function doCompleteMessage(CompleteMessage completeMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = completeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/one_stream_with_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/one_stream_with_dispatcherStreamId.bal new file mode 100644 index 000000000..b3495fe0a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/one_stream_with_dispatcherStreamId.bal @@ -0,0 +1,133 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class ChatClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/chat") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.'type); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribeMessage(SubscribeMessage subscribeMessage, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageCompleteMessageErrorMessageStreamGenerator streamGenerator = new (self.pipes, subscribeMessage.id, timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/one_stream_with_no_dispatcherStreamId.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/one_stream_with_no_dispatcherStreamId.bal new file mode 100644 index 000000000..9c9e2ded1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/StreamResponse/one_stream_with_no_dispatcherStreamId.bal @@ -0,0 +1,127 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class ChatClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/chat") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.'type); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribeMessage(SubscribeMessage subscribeMessage, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageCompleteMessageErrorMessageStreamGenerator streamGenerator = new (self.pipes, "subscribeMessage", timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SubProtocols/graphqloverwebsocket.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SubProtocols/graphqloverwebsocket.bal new file mode 100644 index 000000000..f2e456ea6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/SubProtocols/graphqloverwebsocket.bal @@ -0,0 +1,232 @@ +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class ChatClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9090/chat") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.'type); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # subscribemessage description + # + # + subscribeMessage - subscribe payload description + # + timeout - waiting period to keep the event in the buffer in seconds + # + return - subscribe response description + remote isolated function doSubscribeMessage(SubscribeMessage subscribeMessage, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + NextMessageCompleteMessageErrorMessageStreamGenerator streamGenerator = new (self.pipes, subscribeMessage.id, timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doPingMessage(PingMessage pingMessage, decimal timeout) returns PongMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pingMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("pingMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + PongMessage|error pongMessage = responseMessage.cloneWithType(); + if pongMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", pongMessage); + } + return pongMessage; + } + + remote isolated function doPongMessage(PongMessage pongMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = pongMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + remote isolated function doConnectionInitMessage(ConnectionInitMessage connectionInitMessage, decimal timeout) returns ConnectionAckMessage|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = connectionInitMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("connectionInitMessage").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + ConnectionAckMessage|error connectionAckMessage = responseMessage.cloneWithType(); + if connectionAckMessage is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", connectionAckMessage); + } + return connectionAckMessage; + } + + remote isolated function doCompleteMessage(CompleteMessage completeMessage, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = completeMessage.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/complete_util_gen.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/complete_util_gen.bal new file mode 100644 index 000000000..427a7f812 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/complete_util_gen.bal @@ -0,0 +1,159 @@ +import xlibb/pipe; +import ballerina/url; +type SimpleBasicType string|boolean|int|float|decimal; + +# Stream generator class for NextMessage|CompleteMessage|ErrorMessage return type +public client isolated class NextMessageCompleteMessageErrorMessageStreamGenerator { + *Generator; + private final PipesMap pipes; + private final string pipeId; + private final decimal timeout; + + # StreamGenerator + # + # + pipe - Pipe to hold stream messages + # + timeout - Waiting time + public isolated function init(PipesMap pipes, string pipeId, decimal timeout) { + self.pipes = pipes; + self.pipeId = pipeId; + self.timeout = timeout; + } + + public isolated function next() returns record {|NextMessage|CompleteMessage|ErrorMessage value;|}|error { + while true { + anydata|error? message = self.pipes.getPipe(self.pipeId).consume(self.timeout); + if message is error? { + continue; + } + NextMessage|CompleteMessage|ErrorMessage response = check message.cloneWithType(); + return {value: response}; + } + } + + public isolated function close() returns error? { + check self.pipes.removePipe(self.pipeId); + } +} + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# StreamGeneratorsMap class to handle generated stream generators +public isolated class StreamGeneratorsMap { + private final Generator[] streamGenerators; + + public isolated function init() { + self.streamGenerators = []; + } + + public isolated function addStreamGenerator(Generator streamGenerator) { + lock { + self.streamGenerators.push(streamGenerator); + } + } + + public isolated function removeStreamGenerators() returns error? { + lock { + foreach Generator streamGenerator in self.streamGenerators { + check streamGenerator.close(); + } + } + } +} + +# Generator object type for type inclusion +public type Generator isolated object { + public isolated function next() returns record {|anydata value;|}|error; + public isolated function close() returns error?; +}; + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +public isolated function getEncodedUri(anydata value) returns string { + string|error encoded = url:encode(value.toString(), "UTF8"); + if (encoded is string) { + return encoded; + } else { + return value.toString(); + } +} + +# Generate query path with query parameter. +# +# + queryParam - Query parameter map +# + return - Returns generated Path or error at failure of client initialization +public isolated function getPathForQueryParam(map queryParam) returns string|error { + string[] param = []; + if (queryParam.length() > 0) { + param.push("?"); + foreach var [key, value] in queryParam.entries() { + if value is () { + _ = queryParam.remove(key); + continue; + } + if (value is SimpleBasicType) { + param.push(key, "=", getEncodedUri(value.toString())); + + } else { + param.push(key, "=", value.toString()); + } + param.push("&"); + } + _ = param.pop(); + } + string restOfPath = string:'join("", ...param); + return restOfPath; +} + +# Combine custom headers and param headers +# +# + customHeaders - Custom headers map +# + paramHeaders - Headers generated using spec +# + return - Return combine custom and spec generated headers +public isolated function getCombineHeaders(map customHeaders, map paramHeaders) returns map { + foreach [string, string] [k, v] in paramHeaders.entries() { + customHeaders[k] = v; + } + return customHeaders; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/default_util.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/default_util.bal new file mode 100644 index 000000000..983f7d6ee --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/default_util.bal @@ -0,0 +1,43 @@ +import xlibb/pipe; + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/header_parameter_utils.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/header_parameter_utils.bal new file mode 100644 index 000000000..026f3d992 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/header_parameter_utils.bal @@ -0,0 +1,57 @@ +import xlibb/pipe; + +type SimpleBasicType string|boolean|int|float|decimal; + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# Combine custom headers and param headers +# +# + customHeaders - Custom headers map +# + paramHeaders - Headers generated using spec +# + return - Return combine custom and spec generated headers +public isolated function getCombineHeaders(map customHeaders, map paramHeaders) returns map { + foreach [string, string] [k, v] in paramHeaders.entries() { + customHeaders[k] = v; + } + return customHeaders; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/path_param_url_encoded.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/path_param_url_encoded.bal new file mode 100644 index 000000000..420a3ae20 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/path_param_url_encoded.bal @@ -0,0 +1,119 @@ +import xlibb/pipe; +import ballerina/url; + +# Stream generator class for NextMessage|CompleteMessage|ErrorMessage return type +public client isolated class NextMessageCompleteMessageErrorMessageStreamGenerator { + *Generator; + private final PipesMap pipes; + private final string pipeId; + private final decimal timeout; + + # StreamGenerator + # + # + pipe - Pipe to hold stream messages + # + timeout - Waiting time + public isolated function init(PipesMap pipes, string pipeId, decimal timeout) { + self.pipes = pipes; + self.pipeId = pipeId; + self.timeout = timeout; + } + + public isolated function next() returns record {|NextMessage|CompleteMessage|ErrorMessage value;|}|error { + while true { + anydata|error? message = self.pipes.getPipe(self.pipeId).consume(self.timeout); + if message is error? { + continue; + } + NextMessage|CompleteMessage|ErrorMessage response = check message.cloneWithType(); + return {value: response}; + } + } + + public isolated function close() returns error? { + check self.pipes.removePipe(self.pipeId); + } +} + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# StreamGeneratorsMap class to handle generated stream generators +public isolated class StreamGeneratorsMap { + private final Generator[] streamGenerators; + + public isolated function init() { + self.streamGenerators = []; + } + + public isolated function addStreamGenerator(Generator streamGenerator) { + lock { + self.streamGenerators.push(streamGenerator); + } + } + + public isolated function removeStreamGenerators() returns error? { + lock { + foreach Generator streamGenerator in self.streamGenerators { + check streamGenerator.close(); + } + } + } +} + +# Generator object type for type inclusion +public type Generator isolated object { + public isolated function next() returns record {|anydata value;|}|error; + public isolated function close() returns error?; +}; + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +public isolated function getEncodedUri(anydata value) returns string { + string|error encoded = url:encode(value.toString(), "UTF8"); + if (encoded is string) { + return encoded; + } else { + return value.toString(); + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/query_parameter_utils.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/query_parameter_utils.bal new file mode 100644 index 000000000..03292c9c4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/baloutputs/Util/query_parameter_utils.bal @@ -0,0 +1,86 @@ +import xlibb/pipe; +import ballerina/url; + +type SimpleBasicType string|boolean|int|float|decimal; + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# Get Encoded URI for a given value. +# +# + value - Value to be encoded +# + return - Encoded string +public isolated function getEncodedUri(anydata value) returns string { + string|error encoded = url:encode(value.toString(), "UTF8"); + if (encoded is string) { + return encoded; + } else { + return value.toString(); + } +} + +# Generate query path with query parameter. +# +# + queryParam - Query parameter map +# + return - Returns generated Path or error at failure of client initialization +public isolated function getPathForQueryParam(map queryParam) returns string|error { + string[] param = []; + if (queryParam.length() > 0) { + param.push("?"); + foreach var [key, value] in queryParam.entries() { + if value is () { + _ = queryParam.remove(key); + continue; + } + if (value is SimpleBasicType) { + param.push(key, "=", getEncodedUri(value.toString())); + + } else { + param.push(key, "=", value.toString()); + } + param.push("&"); + } + _ = param.pop(); + } + string restOfPath = string:'join("", ...param); + return restOfPath; +} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/ably.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/ably.yaml new file mode 100644 index 000000000..c549175f5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/ably.yaml @@ -0,0 +1,1306 @@ +openapi: 3.0.1 +servers: + - url: https://rest.ably.io +info: + x-ballerina-display: + label: Ably + iconPath: "icon.png" + contact: + email: support@ably.io + name: Ably Support + url: https://www.ably.io/contact + x-twitter: ablyrealtime + description: + This is a generated connector for [Ably REST API v1.1.0](https://ably.com/documentation/rest-api) OpenAPI specification. + + The [Ably REST API](https://www.ably.io/documentation/rest-api) provides a way for a wide range of server and client devices to communicate with the Ably service over REST. + + The REST API does not provide a realtime long-lived connection to Ably, but in all other respects is a simple subset of the full [realtime messaging API](https://ably.com/documentation/realtime). + title: Ably REST API + version: 1.1.0 + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Create an [Ably account](https://ably.com/) and obtain tokens following [this guide](https://ably.com/documentation/core-features/versions/v1.1/authentication). + x-apisguru-categories: + - cloud + x-logo: + url: https://twitter.com/ablyrealtime/profile_image?size=original + x-origin: + - converter: + url: https://github.com/mermade/oas-kit + version: 7.0.4 + format: openapi + url: https://raw.githubusercontent.com/ably/open-specs/main/swagger.yaml + version: "3.0" + x-providerName: ably.io +security: + - basicAuth: [] + - bearerAuth: [] +paths: + /channels: + get: + description: Enumerate all active channels of the application + operationId: getMetadataOfAllChannels + parameters: + - description: Optionally specifies the maximum number of results to return. A limit greater than 1000 is unsupported + in: query + name: limit + schema: + default: 100 + type: integer + - description: Optionally limits the query to only those channels whose name starts with the given prefix + in: query + name: prefix + schema: + type: string + - description: optionally specifies whether to return just channel names (by=id) or ChannelDetails (by=value) + in: query + name: by + schema: + enum: + - value + - id + type: string + responses: + 2XX: + content: + application/json: + schema: + oneOf: + - items: + $ref: "#/components/schemas/ChannelDetails" + type: array + - items: + type: string + type: array + application/x-msgpack: + schema: + oneOf: + - items: + $ref: "#/components/schemas/ChannelDetails" + type: array + - items: + type: string + type: array + text/html: + schema: + type: string + description: OK + headers: + link: + $ref: "#/components/headers/Link" + default: + $ref: "#/components/responses/Error" + summary: Enumerate all active channels of the application + tags: + - Status + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + "/channels/{channel_id}": + get: + description: Get metadata of a channel + operationId: getMetadataOfChannel + parameters: + - $ref: "#/components/parameters/channelId" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ChannelDetails" + description: OK + headers: + x-ably-serverid: + $ref: "#/components/headers/ServerId" + default: + $ref: "#/components/responses/Error" + summary: Get metadata of a channel + tags: + - Status + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + "/channels/{channel_id}/messages": + get: + description: Get message history for a channel + operationId: getMessagesByChannel + parameters: + - $ref: "#/components/parameters/channelId" + - $ref: "#/components/parameters/filterStart" + - $ref: "#/components/parameters/filterLimit" + - $ref: "#/components/parameters/filterEnd" + - $ref: "#/components/parameters/filterDirection" + responses: + 2XX: + content: + application/json: + schema: + items: + $ref: "#/components/schemas/Message" + type: array + application/x-msgpack: + schema: + items: + $ref: "#/components/schemas/Message" + type: array + text/html: + schema: + type: string + description: OK + headers: + link: + $ref: "#/components/headers/Link" + x-ably-serverid: + $ref: "#/components/headers/ServerId" + default: + description: Error + headers: + x-ably-errorcode: + $ref: "#/components/headers/ErrorCode" + x-ably-errormessage: + $ref: "#/components/headers/ErrorMessage" + x-ably-serverid: + $ref: "#/components/headers/ServerId" + summary: Get message history for a channel + tags: + - History + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + post: + description: Publish a message to the specified channel + operationId: publishMessagesToChannel + parameters: + - $ref: "#/components/parameters/channelId" + requestBody: + description: Message + content: + application/json: + schema: + $ref: "#/components/schemas/Message" + application/x-msgpack: + schema: + $ref: "#/components/schemas/Message" + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/Message" + responses: + 2XX: + content: + application/json: + schema: + properties: + channel: + type: string + messageId: + type: string + type: object + application/x-msgpack: + schema: + properties: + channel: + type: string + messageId: + type: string + type: object + text/html: + schema: + properties: + channel: + type: string + messageId: + type: string + type: object + description: OK + headers: + x-ably-serverid: + $ref: "#/components/headers/ServerId" + default: + $ref: "#/components/responses/Error" + summary: Publish a message to a channel + tags: + - Publishing + "/channels/{channel_id}/presence": + get: + description: Get presence on a channel + operationId: getPresenceOfChannel + parameters: + - $ref: "#/components/parameters/channelId" + - description: Optional filter to restrict members present with that clientId + in: query + name: clientId + schema: + type: string + - description: Optional filter to restrict members present with that connectionId + in: query + name: connectionId + schema: + type: string + - description: The maximum number of records to return. A limit greater than 1,000 is invalid. + in: query + name: limit + schema: + default: 100 + type: integer + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/PresenceMessage" + type: array + application/x-msgpack: + schema: + items: + $ref: "#/components/schemas/PresenceMessage" + type: array + text/html: + schema: + type: string + description: OK + headers: + link: + $ref: "#/components/headers/Link" + x-ably-serverid: + $ref: "#/components/headers/ServerId" + default: + $ref: "#/components/responses/Error" + summary: Get presence of a channel + tags: + - Status + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + "/channels/{channel_id}/presence/history": + get: + description: Get presence on a channel + operationId: getPresenceHistoryOfChannel + parameters: + - $ref: "#/components/parameters/channelId" + - $ref: "#/components/parameters/filterStart" + - $ref: "#/components/parameters/filterLimit" + - $ref: "#/components/parameters/filterEnd" + - $ref: "#/components/parameters/filterDirection" + responses: + 2XX: + content: + application/json: + schema: + items: + $ref: "#/components/schemas/PresenceMessage" + type: array + application/x-msgpack: + schema: + items: + $ref: "#/components/schemas/PresenceMessage" + type: array + text/html: + schema: + type: string + description: OK + headers: + link: + $ref: "#/components/headers/Link" + default: + $ref: "#/components/responses/Error" + summary: Get presence history of a channel + tags: + - History + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + "/keys/{keyName}/requestToken": + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + post: + description: This is the means by which clients obtain access tokens to use the service. You can see how to construct an Ably TokenRequest in the [Ably TokenRequest spec](https://www.ably.io/documentation/rest-api/token-request-spec) documentation, although we recommend you use an Ably SDK rather to create a TokenRequest, as the construction of a TokenRequest is complex. The resulting token response object contains the token properties as defined in Ably TokenRequest spec. Authentication is not required if using a Signed TokenRequest. + operationId: requestAccessToken + parameters: + - $ref: "#/components/parameters/key_name" + requestBody: + description: Request Body + content: + application/json: + example: + capability: + channel1: + - publish + - subscribe + wildcard:channels:*: + - publish + keyName: YourKey.Name + timestamp: "1559124196551" + schema: + oneOf: + - $ref: "#/components/schemas/TokenRequest" + - $ref: "#/components/schemas/SignedTokenRequest" + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/TokenDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/TokenDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: Request an access token + tags: + - Authentication + /push/channelSubscriptions: + delete: + description: Delete a device details object. + operationId: deletePushDeviceDetails + parameters: + - description: Filter to restrict to subscriptions associated with that channel. + in: query + name: channel + schema: + type: string + - description: Must be set when clientId is empty, cannot be used with clientId. + in: query + name: deviceId + schema: + type: string + - description: Must be set when deviceId is empty, cannot be used with deviceId. + in: query + name: clientId + schema: + type: string + responses: + 2XX: + description: OK + default: + $ref: "#/components/responses/Error" + summary: Delete a registered device's update token + tags: + - Push + get: + description: Get a list of push notification subscriptions to channels. + operationId: getPushSubscriptionsOnChannels + parameters: + - description: Filter to restrict to subscriptions associated with that channel. + in: query + name: channel + schema: + type: string + - description: Optional filter to restrict to devices associated with that deviceId. Cannot be used with clientId. + in: query + name: deviceId + schema: + type: string + - description: Optional filter to restrict to devices associated with that clientId. Cannot be used with deviceId. + in: query + name: clientId + schema: + type: string + - description: The maximum number of records to return. + in: query + name: limit + schema: + default: 100 + maximum: 1000 + type: integer + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: List channel subscriptions + tags: + - Push + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + post: + description: Subscribe either a single device or all devices associated with a client ID to receive push notifications from messages sent to a channel. + operationId: subscribePushDeviceToChannel + requestBody: + description: Request Body + content: + application/json: + example: + channel: my:channel + clientId: myClientId + schema: + oneOf: + - properties: + channel: + description: Channel name. + type: string + deviceId: + description: Must be set when clientId is empty, cannot be used with clientId. + type: string + type: object + - properties: + channel: + description: Channel name. + type: string + clientId: + description: Must be set when deviceId is empty, cannot be used with deviceId. + type: string + type: object + application/x-msgpack: + example: + channel: my:channel + clientId: myClientId + schema: + oneOf: + - properties: + channel: + description: Channel name. + type: string + deviceId: + description: Must be set when clientId is empty, cannot be used with clientId. + type: string + type: object + - properties: + channel: + description: Channel name. + type: string + clientId: + description: Must be set when deviceId is empty, cannot be used with deviceId. + type: string + type: object + application/x-www-form-urlencoded: + example: + channel: my:channel + clientId: myClientId + schema: + oneOf: + - properties: + channel: + description: Channel name. + type: string + deviceId: + description: Must be set when clientId is empty, cannot be used with clientId. + type: string + type: object + - properties: + channel: + description: Channel name. + type: string + clientId: + description: Must be set when deviceId is empty, cannot be used with deviceId. + type: string + type: object + responses: + 2XX: + description: OK + default: + $ref: "#/components/responses/Error" + summary: Subscribe a device to a channel + tags: + - Push + /push/channels: + get: + description: Returns a paginated response of channel names. + operationId: getChannelsWithPushSubscribers + responses: + 2XX: + content: + application/json: + schema: + items: + type: string + type: array + application/x-msgpack: + schema: + items: + type: string + type: array + text/html: + schema: + items: + type: string + type: array + description: OK + default: + $ref: "#/components/responses/Error" + summary: List all channels with at least one subscribed device + tags: + - Push + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + /push/deviceRegistrations: + delete: + description: Unregisters devices. All their subscriptions for receiving push notifications through channels will also be deleted. + operationId: unregisterAllPushDevices + parameters: + - description: Optional filter to restrict to devices associated with that deviceId. Cannot be used with clientId. + in: query + name: deviceId + schema: + type: string + - description: Optional filter to restrict to devices associated with that clientId. Cannot be used with deviceId. + in: query + name: clientId + schema: + type: string + responses: + 2XX: + description: OK + default: + $ref: "#/components/responses/Error" + summary: Unregister matching devices for push notifications + tags: + - Push + get: + description: List of device details of devices registed for push notifications. + operationId: getRegisteredPushDevices + parameters: + - description: Optional filter to restrict to devices associated with that deviceId. + in: query + name: deviceId + schema: + type: string + - description: Optional filter to restrict to devices associated with that clientId. + in: query + name: clientId + schema: + type: string + - description: The maximum number of records to return. + in: query + name: limit + schema: + default: 100 + maximum: 1000 + type: integer + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + text/html: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: List devices registered for receiving push notifications + tags: + - Push + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + post: + description: Register a device’s details, including the information necessary to deliver push notifications to it. Requires "push-admin" capability. + operationId: registerPushDevice + requestBody: + description: Device Details + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + text/html: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: Register a device for receiving push notifications + tags: + - Push + "/push/deviceRegistrations/{device_id}": + delete: + description: Unregisters a single device by its device ID. All its subscriptions for receiving push notifications through channels will also be deleted. + operationId: unregisterPushDevice + parameters: + - $ref: "#/components/parameters/deviceId" + responses: + 2XX: + description: OK + default: + $ref: "#/components/responses/Error" + summary: Unregister a single device for push notifications + tags: + - Push + get: + description: Get the full details of a device. + operationId: getPushDeviceDetails + parameters: + - $ref: "#/components/parameters/deviceId" + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + text/html: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: Get a device registration + tags: + - Push + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + patch: + description: Specific attributes of an existing registration can be updated. Only clientId, metadata and push.recipient are mutable. + operationId: patchPushDeviceDetails + parameters: + - $ref: "#/components/parameters/deviceId" + requestBody: + description: Device Details + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/DeviceDetails" + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + text/html: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: Update a device registration + tags: + - Push + put: + description: Device registrations can be upserted (the existing registration is replaced entirely) with a PUT operation. Only clientId, metadata and push.recipient are mutable. + operationId: putPushDeviceDetails + parameters: + - $ref: "#/components/parameters/deviceId" + requestBody: + description: Device Details + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/DeviceDetails" + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + text/html: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: Update a device registration + tags: + - Push + "/push/deviceRegistrations/{device_id}/resetUpdateToken": + get: + description: Gets an updated device details object. + operationId: updatePushDeviceDetails + parameters: + - $ref: "#/components/parameters/deviceId" + responses: + 2XX: + content: + application/json: + schema: + $ref: "#/components/schemas/DeviceDetails" + application/x-msgpack: + schema: + $ref: "#/components/schemas/DeviceDetails" + text/html: + schema: + $ref: "#/components/schemas/DeviceDetails" + description: OK + default: + $ref: "#/components/responses/Error" + summary: Reset a registered device's update token + tags: + - Push + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + /push/publish: + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + post: + description: A convenience endpoint to deliver a push notification payload to a single device or set of devices identified by their client identifier. + operationId: publishPushNotificationToDevices + requestBody: + description: Request Body + content: + application/json: + schema: + properties: + push: + $ref: "#/components/schemas/Push" + recipient: + $ref: "#/components/schemas/Recipient" + required: + - recipient + type: object + application/x-msgpack: + schema: + properties: + push: + $ref: "#/components/schemas/Push" + recipient: + $ref: "#/components/schemas/Recipient" + required: + - recipient + type: object + application/x-www-form-urlencoded: + schema: + properties: + push: + $ref: "#/components/schemas/Push" + recipient: + $ref: "#/components/schemas/Recipient" + required: + - recipient + type: object + responses: + 2XX: + description: OK + default: + $ref: "#/components/responses/Error" + summary: Publish a push notification to device(s) + tags: + - Push + /stats: + get: + description: The Ably system can be queried to obtain usage statistics for a given application, and results are provided aggregated across all channels in use in the application in the specified period. Stats may be used to track usage against account quotas. + operationId: getStats + parameters: + - $ref: "#/components/parameters/filterStart" + - $ref: "#/components/parameters/filterLimit" + - $ref: "#/components/parameters/filterEnd" + - $ref: "#/components/parameters/filterDirection" + - description: Specifies the unit of aggregation in the returned results. + in: query + name: unit + schema: + default: minute + enum: + - minute + - hour + - day + - month + type: string + responses: + 2XX: + content: + application/json: + schema: + type: object + description: OK + default: + $ref: "#/components/responses/Error" + summary: Retrieve usage statistics for an application + tags: + - Stats + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" + /time: + get: + description: This returns the service time in milliseconds since the epoch. + operationId: getTime + responses: + 2XX: + content: + application/json: + schema: + items: + type: integer + type: array + application/x-msgpack: + schema: + items: + type: integer + type: array + text/html: + schema: + type: string + description: OK + default: + $ref: "#/components/responses/Error" + security: [] + summary: Get the service time + tags: + - Stats + parameters: + - $ref: "#/components/parameters/versionHeader" + - $ref: "#/components/parameters/responseFormat" +components: + headers: + ErrorCode: + description: The error code. + schema: + type: integer + ErrorMessage: + description: The error message. + schema: + type: string + Link: + description: Links to related resources, in the format defined by [RFC 5988](https://tools.ietf.org/html/rfc5988#section-5). This will potentially include a link with relation type `next`, `first`, and `current`, where appropiate. + required: true + schema: + pattern: (<(.*)?>; rel=\"(first|current|last)?\",)*(<(.*)?>; rel=\"(first|current|last)?\")+ + type: string + ServerId: + description: The ID for the server communicated with. + required: true + schema: + type: string + parameters: + channelId: + description: The [Channel's ID](https://www.ably.io/documentation/rest/channels). + in: path + name: channel_id + required: true + schema: + type: string + deviceId: + description: Device's ID. + in: path + name: device_id + required: true + schema: + type: string + filterDirection: + description: The direction of this query. The direction determines the order of the returned result array, but also determines which end of the query interval is the start point for the search. For example, a forwards query uses start as the start point, whereas a backwards query uses end as the start point. + in: query + name: direction + schema: + default: backwards + enum: + - forwards + - backwards + type: string + filterEnd: + description: The end of the query interval as a time in milliseconds since the epoch. A message qualifies as a member of the result set if it was received at or before this time. + in: query + name: end + schema: + default: now + type: string + filterLimit: + description: The maximum number of records to return. A limit greater than 1,000 is invalid. + in: query + name: limit + schema: + default: "100" + type: integer + filterStart: + description: Beginning of time The start of the query interval as a time in milliseconds since the epoch. A message qualifies as a member of the result set if it was received at or after this time. + in: query + name: start + schema: + type: string + key_name: + description: The [key name](https://www.ably.io/documentation/rest-api/token-request-spec#api-key-format) comprises of the app ID and key ID of an API key. + in: path + name: keyName + required: true + schema: + type: string + responseFormat: + description: The response format you would like + in: query + name: format + schema: + enum: + - json + - jsonp + - msgpack + - html + type: string + versionHeader: + description: The version of the API you wish to use. + in: header + name: X-Ably-Version + schema: + type: string + responses: + Error: + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + application/x-msgpack: + schema: + $ref: "#/components/schemas/Error" + text/html: + schema: + $ref: "#/components/schemas/Error" + description: Error + headers: + x-ably-errorcode: + $ref: "#/components/headers/ErrorCode" + x-ably-errormessage: + $ref: "#/components/headers/ErrorMessage" + x-ably-serverid: + $ref: "#/components/headers/ServerId" + schemas: + ChannelDetails: + properties: + channelId: + description: The required name of the channel including any qualifier, if any. + type: string + isGlobalMaster: + description: In events relating to the activity of a channel in a specific region, this optionally identifies whether or not that region is responsible for global coordination of the channel. + type: boolean + region: + description: In events relating to the activity of a channel in a specific region, this optionally identifies the region. + type: string + status: + $ref: "#/components/schemas/ChannelStatus" + required: + - channelId + type: object + ChannelStatus: + description: A ChannelStatus instance. + properties: + isActive: + description: A required boolean value indicating whether the channel that is the subject of the event is active. For events indicating regional activity of a channel this indicates activity in that region, not global activity. + type: boolean + occupancy: + $ref: "#/components/schemas/Occupancy" + required: + - isActive + type: object + DeviceDetails: + properties: + clientId: + description: Optional trusted client identifier for the device. + type: string + deviceSecret: + description: Secret value for the device. + type: string + formFactor: + description: Form factor of the push device. + enum: + - phone + - tablet + - desktop + - tv + - watch + - car + - embedded + type: string + id: + description: Unique identifier for the device generated by the device itself. + type: string + metadata: + description: Optional metadata object for this device. The metadata for a device may only be set by clients with push-admin privileges and will be used more extensively in the future with smart notifications. + type: object + platform: + description: Platform of the push device. + enum: + - ios + - android + type: string + pushRecipient: + $ref: "#/components/schemas/Recipient" + pushState: + description: the current state of the push device. + enum: + - Active + - Failing + - Failed + readOnly: true + type: string + type: object + Error: + description: Returned error from failed REST. + properties: + code: + description: Error code. + type: integer + href: + description: Link to help with error. + type: string + message: + description: Message explaining the error's cause. + type: string + serverId: + description: Server ID with which error was encountered. + type: string + statusCode: + description: Status error code. + type: integer + type: object + Extras: + description: Extras object. Currently only allows for [push](https://www.ably.io/documentation/general/push/publish#channel-broadcast-example) extra. + properties: + push: + $ref: "#/components/schemas/Push" + type: object + Message: + description: Message object. + properties: + clientId: + description: The [client ID](https://www.ably.io/documentation/core-features/authentication#identified-clients) of the publisher of this message. + type: string + connectionId: + description: The connection ID of the publisher of this message. + type: string + data: + description: The string encoded payload, with the encoding specified below. + type: string + encoding: + description: This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload. + type: string + extras: + $ref: "#/components/schemas/Extras" + id: + description: A Unique ID that can be specified by the publisher for [idempotent publishing](https://www.ably.io/documentation/rest/messages#idempotent). + readOnly: true + type: string + name: + description: The event name, if provided. + type: string + timestamp: + description: Timestamp when the message was received by the Ably, as milliseconds since the epoch. + format: int64 + readOnly: true + type: integer + type: object + Notification: + description: Notification + properties: + body: + description: Text below title on the expanded notification. + type: string + collapseKey: + description: Platform-specific, used to group notifications together. + type: string + icon: + description: Platform-specific icon for the notification. + type: string + sound: + description: Platform-specific sound for the notification. + type: string + title: + description: Title to display at the notification. + type: string + type: object + Occupancy: + description: An Occupancy instance indicating the occupancy of a channel. For events indicating regional activity of a channel this indicates activity in that region, not global activity. + properties: + presenceConnections: + description: The number of connections that are authorised to enter members into the presence channel. + type: integer + presenceMembers: + description: The number of members currently entered into the presence channel. + type: integer + presenceSubscribers: + description: The number of connections that are authorised to subscribe to presence messages. + type: integer + publishers: + description: The number of connections attached to the channel that are authorised to publish. + type: integer + subscribers: + description: The number of connections attached that are authorised to subscribe to messages. + type: integer + type: object + PresenceMessage: + properties: + action: + description: The event signified by a PresenceMessage. + enum: + - ABSENT + - PRESENT + - ENTER + - LEAVE + - UPDATE + readOnly: true + type: string + clientId: + description: The client ID of the publisher of this presence update. + type: string + connectionId: + description: The connection ID of the publisher of this presence update. + type: string + data: + description: The presence update payload, if provided. + type: string + encoding: + description: This will typically be empty as all presence updates received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload. + type: string + extras: + $ref: "#/components/schemas/Extras" + id: + description: Unique ID assigned by Ably to this presence update. + readOnly: true + type: string + timestamp: + description: Timestamp when the presence update was received by Ably, as milliseconds since the epoch. + format: int64 + readOnly: true + type: integer + type: object + Push: + description: Push + properties: + apns: + description: Extends and overrides generic values when delivering via APNs. [See examples](https://www.ably.io/documentation/general/push/publish#payload-structure) + properties: + notification: + $ref: "#/components/schemas/Notification" + type: object + data: + description: Arbitrary [key-value string-to-string payload](https://www.ably.io/documentation/general/push/publish#channel-broadcast-example). + type: string + fcm: + description: Extends and overrides generic values when delivering via GCM/FCM. [See examples](https://www.ably.io/documentation/general/push/publish#payload-structure) + properties: + notification: + $ref: "#/components/schemas/Notification" + type: object + notification: + $ref: "#/components/schemas/Notification" + web: + description: Extends and overrides generic values when delivering via web. [See examples](https://www.ably.io/documentation/general/push/publish#payload-structure) + properties: + notification: + $ref: "#/components/schemas/Notification" + type: object + type: object + Recipient: + description: Push recipient details for a device. + properties: + clientId: + description: Client ID of recipient + type: string + writeOnly: true + deviceId: + description: Client ID of recipient + type: string + writeOnly: true + deviceToken: + description: when using APNs, specifies the required device token. + type: string + registrationToken: + description: when using GCM or FCM, specifies the required registration token. + type: string + transportType: + description: Defines which push platform is being used. + enum: + - apns + - fcm + - gcm + type: string + type: object + SignedTokenRequest: + allOf: + - $ref: "#/components/schemas/TokenRequest" + - properties: + mac: + description: A signature, generated as an HMAC of each of the above components, using the key secret value. + type: string + required: + - mac + type: object + TokenDetails: + properties: + capability: + description: Regular expression representation of the capabilities of the token. + type: string + expires: + description: Timestamp of token expiration. + type: integer + issued: + description: Timestamp of token creation. + type: integer + keyName: + description: Name of the key used to create the token + type: string + token: + description: The Ably Token. + type: string + type: object + TokenRequest: + properties: + capability: + description: The [capabilities](https://www.ably.io/documentation/core-features/authentication#capabilities-explained) (i.e. a set of channel names/namespaces and, for each, a set of operations) which should be a subset of the set of capabilities associated with the key specified in keyName. + example: + channel1: + - publish + - subscribe + type: object + clientId: + description: The [client ID](https://www.ably.io/documentation/core-features/authentication#identified-clients) to be assosciated with the token. Can be set to * to allow for any client ID to be used. + type: string + keyName: + description: Name of the key used for the TokenRequest. The keyName comprises of the app ID and key ID on an API Key. + example: xVLyHw.LMJZxw + type: string + nonce: + description: An unquoted, un-escaped random string of at least 16 characters. Used to ensure the Ably TokenRequest cannot be reused. + type: string + timestamp: + description: Time of creation of the Ably TokenRequest. + type: integer + required: + - keyName + - capability + - timestamp + - nonce + type: object + securitySchemes: + basicAuth: + description: Basic Authentication using an [API key](https://www.ably.io/documentation/core-features/authentication#basic-authentication). + scheme: basic + type: http + bearerAuth: + description: Token Authentication using an [Ably Token](https://www.ably.io/documentation/core-features/authentication#basic-authentication), or optionally an [Ably JWT](https://www.ably.io/documentation/core-features/authentication#ably-jwt-process). + scheme: bearer + type: http diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/azure.iot.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/azure.iot.yaml new file mode 100644 index 000000000..272d117d0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/azure.iot.yaml @@ -0,0 +1,4601 @@ +openapi: 3.0.1 +info: + x-ballerina-display: + label: Azure IoT Hub + iconPath: "icon.png" + title: Azure IoT Hub + description: > + This is a generated connector from [Azure IoT Hub API v1.0](https://docs.microsoft.com/en-us/rest/api/iothub/) OpenAPI specification. + + Azure IoT Hub is a service that offers programmatic access to the device, messaging, and job services, as well as the resource provider, in IoT Hub. + You can access messaging services from within an IoT service running in Azure, or directly over the Internet from any application that can send an HTTPS request and receive an HTTPS response. + + Use this API to manage the IoT hubs in your Azure subscription. + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Create an [Azure IoT Hub account](https://azure.microsoft.com/en-us/services/iot-hub/) and obtain OAuth tokens following [this guide](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security). + version: "2019-11-04" + x-apisguru-categories: + - cloud + x-logo: + url: https://assets.onestore.ms/cdnfiles/onestorerolling-1606-01000/shell/v3/images/logo/microsoft.png + x-ms-code-generation-settings: + header: MICROSOFT_MIT_NO_VERSION + x-origin: + - format: swagger + url: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/Microsoft.Devices/stable/2019-11-04/iothub.json + version: "2.0" + x-preferred: false + x-providerName: azure.com + x-serviceName: iothub + x-tags: + - Azure + - Microsoft +servers: + - url: https://management.azure.com/ +security: + - azure_auth: + - user_impersonation +paths: + /providers/Microsoft.Devices/operations: + get: + tags: + - Operations + description: Lists all of the available IoT Hub REST API operations. + operationId: Operations_List + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + responses: + 200: + description: OK. The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/OperationListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + x-ms-examples: + Operations_List: + parameters: + api-version: 2019-11-04 + responses: + 200: + body: + value: + - display: + description: Register the subscription for the IotHub resource + provider and enables the creation of IotHub resources + operation: Register Resource Provider + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/register/action + - display: + description: Gets the diagnostic setting for the resource + operation: Get Diagnostic Setting + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/IotHubs/diagnosticSettings/read + - display: + description: Creates or updates the diagnostic setting for the + resource + operation: Set Diagnostic Setting + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/IotHubs/diagnosticSettings/write + - display: + description: Gets the available metrics for the IotHub service + operation: Read IotHub service metric definitions + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/IotHubs/metricDefinitions/read + - display: + description: Gets the available log definitions for the IotHub + Service + operation: Read IotHub service log definitions + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/IotHubs/logDefinitions/read + - display: + description: Get All ResourceProvider Operations + operation: Get All ResourceProvider Operations + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/operations/Read + - display: + description: Check If IotHub name is available + operation: Check If IotHub name is available + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/checkNameAvailability/Action + - display: + description: Get subscription usage details for this provider. + operation: Get Subscription Usages + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/usages/Read + - display: + description: Gets the IotHub resource(s) + operation: Get IotHub(s) + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/Read + - display: + description: Create or update IotHub Resource + operation: Create or update IotHub Resource + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/Write + - display: + description: Delete IotHub Resource + operation: Delete IotHub Resource + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/Delete + - display: + description: Get IotHub Statistics + operation: Get IotHub Statistics + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/iotHubStats/Read + - display: + description: Get valid IotHub Skus + operation: Get valid IotHub Skus + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/skus/Read + - display: + description: Get all IotHub Keys + operation: Get all IotHub Keys + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/listkeys/Action + - display: + description: Get IotHub Key for the given name + operation: Get IotHub Key for the given name + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/iotHubKeys/listkeys/Action + - display: + description: Create EventHub Consumer Group + operation: Create EventHub Consumer Group + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/eventHubEndpoints/consumerGroups/Write + - display: + description: Get EventHub Consumer Group(s) + operation: Get EventHub Consumer Group(s) + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/eventHubEndpoints/consumerGroups/Read + - display: + description: Delete EventHub Consumer Group + operation: Delete EventHub Consumer Group + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/eventHubEndpoints/consumerGroups/Delete + - display: + description: Export Devices + operation: Export Devices + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/exportDevices/Action + - display: + description: Import Devices + operation: Import Devices + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/importDevices/Action + - display: + description: Get Job(s) details submitted on given IotHub + operation: Get the Job(s) on IotHub + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/jobs/Read + - display: + description: Get Quota Metrics + operation: Get Quota Metrics + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/quotaMetrics/Read + - display: + description: Test a message against all existing Routes + operation: Routing Rule Test All + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/routing/routes/$testall/Action + - display: + description: Test a message against a provided test Route + operation: Routing Rule Test Route + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/routing/routes/$testnew/Action + - display: + description: Gets the health of all routing Endpoints for an IotHub + operation: Get Endpoint Health + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/iotHubs/routingEndpointsHealth/Read + - display: + description: Gets the diagnostic setting for the resource + operation: Get Diagnostic Setting + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/ProvisioningServices/diagnosticSettings/read + - display: + description: Creates or updates the diagnostic setting for the + resource + operation: Set Diagnostic Setting + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/ProvisioningServices/diagnosticSettings/write + - display: + description: Gets the available metrics for the DPS service + operation: Read DPS service metric definitions + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/ProvisioningServices/metricDefinitions/read + - display: + description: Gets the available log definitions for the DPS Service + operation: Read DPS service log definitions + provider: Microsoft Devices + resource: IotHubs + name: Microsoft.Devices/ProvisioningServices/logDefinitions/read + - display: + description: Check If Provisioning Service name is available + operation: Check If Provisioning Service name is available + provider: Microsoft Devices + resource: ProvisioningServives + name: Microsoft.Devices/checkProvisioningServiceNameAvailability/Action + - display: + description: Get Provisioning Service resource + operation: Get Provisioning Service resource + provider: Microsoft Devices + resource: ProvisioningServices + name: Microsoft.Devices/provisioningServices/Read + - display: + description: Create Provisioning Service resource + operation: Create Provisioning Service resource + provider: Microsoft Devices + resource: ProvisioningServices + name: Microsoft.Devices/provisioningServices/Write + - display: + description: Delete Provisioning Service resource + operation: Delete Provisioning Service resource + provider: Microsoft Devices + resource: ProvisioningServices + name: Microsoft.Devices/provisioningServices/Delete + - display: + description: Delete Provisioning Service resource + operation: Delete Provisioning Service resource + provider: Microsoft Devices + resource: ProvisioningServices + name: Microsoft.Devices/provisioningServices/skus/Read + - display: + description: get security related metadata + operation: get security related metadata + provider: Microsoft Devices + resource: ProvisioningServices + name: Microsoft.Devices/provisioningServices/listkeys/Action + x-ms-pageable: + nextLinkName: nextLink + /subscriptions/{subscriptionId}/providers/Microsoft.Devices/IotHubs: + get: + tags: + - GET + summary: Get all the IoT hubs in a subscription + description: Get all the IoT hubs in a subscription. + operationId: IotHubResource_ListBySubscription + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + array of the metadata from all the IoT hubs in the subscription. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescriptionListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ListBySubscription: + parameters: + api-version: 2019-11-04 + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - etag: AAAAAAFD6M4= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + name: $fallback + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + x-ms-pageable: + nextLinkName: nextLink + /subscriptions/{subscriptionId}/providers/Microsoft.Devices/checkNameAvailability: + post: + tags: + - POST + summary: Check if an IoT hub name is available + description: Check if an IoT hub name is available. + operationId: IotHubResource_CheckNameAvailability + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + requestBody: + description: Set the name parameter in the OperationInputs structure to the + name of the IoT hub to check. + content: + application/json: + schema: + $ref: '#/components/schemas/OperationInputs' + required: true + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + response that specifies whether the IoT hub name is available. If the + name is not available, the body contains the reason. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubNameAvailabilityInfo' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_CheckNameAvailability: + parameters: + api-version: 2019-11-04 + operationInputs: + name: test-request + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + message: "" + nameAvailable: true + reason: Invalid + x-codegen-request-body-name: operationInputs + /subscriptions/{subscriptionId}/providers/Microsoft.Devices/usages: + get: + tags: + - GET + summary: Get the number of iot hubs in the subscription + description: Get the number of free and paid iot hubs in the subscription + operationId: ResourceProviderCommon_GetSubscriptionQuota + parameters: + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/UserSubscriptionQuotaListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + ResourceProviderCommon_GetSubscriptionQuota: + parameters: + api-version: 2019-11-04 + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - currentValue: 1 + id: /subscription/91d12660-3dec-467a-be2a-213b5544ddc0/providers/Microsoft.Devices/usages/freeHubCount + limit: 1 + name: + localizedValue: Free Hub Count + value: FreeHubCount + type: /subscription/91d12660-3dec-467a-be2a-213b5544ddc0/providers/Microsoft.Devices/usages + unit: count + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs: + get: + tags: + - GET + summary: Get all the IoT hubs in a resource group + description: Get all the IoT hubs in a resource group. + operationId: IotHubResource_ListByResourceGroup + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + array of the metadata from all the IoT hubs in the resource group. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescriptionListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ListByResourceGroup: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - etag: AAAAAAFD6M4= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + name: $fallback + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + x-ms-pageable: + nextLinkName: nextLink + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/failover: + post: + tags: + - POST + summary: Manually initiate a failover for the IoT Hub to its secondary region + description: Manually initiate a failover for the IoT Hub to its secondary region. + To learn more, see https://aka.ms/manualfailover + operationId: IotHub_ManualFailover + parameters: + - name: iotHubName + in: path + description: Name of the IoT hub to failover + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: Name of the resource group containing the IoT hub resource + required: true + schema: + type: string + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + requestBody: + description: Region to failover to. Must be the Azure paired region. Get the + value from the secondary location in the locations property. To learn more, + see https://aka.ms/manualfailover/region + content: + application/json: + schema: + $ref: '#/components/schemas/FailoverInput' + required: true + responses: + 200: + description: Long running manual failover operation for the IoT hub completed + content: {} + 202: + description: Manual failover initiated + content: {} + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + x-ms-examples: + IotHub_ManualFailover: + parameters: + api-version: 2019-11-04 + failoverInput: + failoverRegion: testHub + iotHubName: testHub + resourceGroupName: myResourceGroup + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: {} + 202: {} + x-ms-long-running-operation: true + x-codegen-request-body-name: failoverInput + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routing/routes/$testall + : post: + tags: + - POST + summary: Test all routes + description: Test all routes configured in this Iot Hub + operationId: IotHubResource_TestAllRoutes + parameters: + - name: iotHubName + in: path + description: IotHub to be tested + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: resource group which Iot Hub belongs to + required: true + schema: + type: string + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + requestBody: + description: Input for testing all routes + content: + application/json: + schema: + $ref: '#/components/schemas/TestAllRoutesInput' + required: true + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/TestAllRoutesResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_TestAllRoutes: + parameters: + api-version: 2019-11-04 + input: + message: + appProperties: + key1: value1 + body: Body of message + systemProperties: + key1: value1 + routingSource: DeviceMessages + iotHubName: testHub + resourceGroupName: myResourceGroup + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + routes: + - properties: + endpointNames: + - id1 + isEnabled: true + name: Routeid + source: DeviceMessages + x-codegen-request-body-name: input + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routing/routes/$testnew + : post: + tags: + - POST + summary: Test the new route + description: Test the new route for this Iot Hub + operationId: IotHubResource_TestRoute + parameters: + - name: iotHubName + in: path + description: IotHub to be tested + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: resource group which Iot Hub belongs to + required: true + schema: + type: string + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + requestBody: + description: Route that needs to be tested + content: + application/json: + schema: + $ref: '#/components/schemas/TestRouteInput' + required: true + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/TestRouteResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_TestRoute: + parameters: + api-version: 2019-11-04 + input: + message: + appProperties: + key1: value1 + body: Body of message + systemProperties: + key1: value1 + route: + endpointNames: + - id1 + isEnabled: true + name: Routeid + source: DeviceMessages + iotHubName: testHub + resourceGroupName: myResourceGroup + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + details: + compilationErrors: + - location: + end: + column: 24 + line: 12 + start: + column: 12 + line: 12 + message: string response + severity: error + result: "false" + x-codegen-request-body-name: input + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routingEndpointsHealth + : get: + tags: + - GET + summary: Get the health for routing endpoints + description: Get the health for routing endpoints. + operationId: IotHubResource_GetEndpointHealth + parameters: + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + required: true + schema: + type: string + - name: iotHubName + in: path + required: true + schema: + type: string + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/EndpointHealthDataListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_GetEndpointHealth: + parameters: + api-version: 2019-11-04 + iotHubName: testHub + resourceGroupName: myResourceGroup + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - endpointId: id1 + healthStatus: healthy + - endpointId: id2 + healthStatus: unknown + x-ms-pageable: + nextLinkName: nextLink + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}: + get: + tags: + - GET + summary: Get the non-security related metadata of an IoT hub + description: Get the non-security related metadata of an IoT hub. + operationId: IotHubResource_Get + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: The body contains all the non-security properties of the IoT + hub. Security-related properties are set to null. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_Get: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + locations: + - location: West US + role: primary + - location: East US + role: secondary + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + put: + tags: + - PUT + summary: Create or update the metadata of an IoT hub. + description: Create or update the metadata of an Iot hub. The usual pattern + to modify a property is to retrieve the IoT hub metadata and security metadata, + and then combine them with the modified values in a new body to update the + IoT hub. + operationId: IotHubResource_CreateOrUpdate + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: If-Match + in: header + description: ETag of the IoT Hub. Do not specify for creating a brand new + IoT Hub. Required to update an existing IoT Hub. + schema: + type: string + requestBody: + description: The IoT hub metadata and security metadata. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + required: true + responses: + 200: + description: This is returned as a response to the status polling request + for the create or update operation. The body contains the resource representation + that indicates a transitional provisioning state. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + 201: + description: This is a long running operation. The operation returns a 201 + if the validation is complete. The response includes an Azure-AsyncOperation + header that contains a status URL. Clients are expected to poll the status + URL for the status of the operation. If successful, the operation returns + HTTP status code of 201 (OK). + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_CreateOrUpdate: + parameters: + api-version: 2019-11-04 + iotHubDescription: + etag: AAAAAAFD6M4= + location: centraluseuap + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + partitionCount: 2 + retentionTimeInDays: 1 + features: None + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + name: $fallback + source: DeviceMessages + routes: [] + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tags: {} + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/ae24ff83-d2ca-4fc8-9717-05dae4bba489/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + name: $fallback + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + 201: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/ae24ff83-d2ca-4fc8-9717-05dae4bba489/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + name: $fallback + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + x-ms-long-running-operation: true + x-codegen-request-body-name: iotHubDescription + delete: + tags: + - DELETE + summary: Delete an IoT hub + description: Delete an IoT hub. + operationId: IotHubResource_Delete + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is returned as a response to the status polling request + for the delete operation. The body contains the resource representation + that indicates a transitional provisioning state. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + 202: + description: The Iot Hub resource provider always returns a 202 Accepted + status code with valid Location and Retry-After headers. The resource + provider also sets the Azure-AsyncOperation header with a URL that points + to the operation resource for this operation. Subsequent GET attempts + on the resource after a DELETE operation return a resource representation + that indicates a transitional provisioning state (such as Terminating). + To retrieve the status of the operation, a client can either poll the + URL returned in the Location header after the Retry-After interval, get + the IoT Hub service status directly, or query the operation resource. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + 204: + description: Once the long running delete operation completes successfully, + a 204 No Content status code is returned when the status polling request + finds the Iot hub metadata in the service and the status of the delete + operation is set to a completed state. + content: {} + 404: + description: After the long running delete operation completes successfully, + a 404 Not Found is returned when the status polling request no longer + finds the Iot hub metadata in the service. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_Delete: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + 202: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: {} + type: Microsoft.Devices/IotHubs + 204: {} + 404: + body: {} + x-ms-long-running-operation: true + patch: + tags: + - PATCH + summary: Update an existing IoT Hubs tags. + description: Update an existing IoT Hub tags. to update other fields use the + CreateOrUpdate method + operationId: IotHubResource_Update + parameters: + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: Resource group identifier. + required: true + schema: + type: string + - name: resourceName + in: path + description: Name of iot hub to update. + required: true + schema: + type: string + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + requestBody: + description: Updated tag information to set into the iot hub instance. + content: + application/json: + schema: + $ref: '#/components/schemas/TagsResource' + required: true + responses: + 200: + description: Iot Hub was successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubDescription' + x-ms-examples: + IotHubResource_Update: + parameters: + IotHubTags: + tags: + foo: bar + api-version: 2019-11-04 + location: East US + resourceGroupName: myResourceGroup + resourceName: myHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + type: Microsoft.Devices/IotHubs + responses: + 200: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/ae24ff83-d2ca-4fc8-9717-05dae4bba489/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/testHub + location: centraluseuap + name: testHub + properties: + cloudToDevice: + defaultTtlAsIso8601: PT1H + feedback: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + maxDeliveryCount: 10 + enableFileUploadNotifications: false + eventHubEndpoints: + events: + endpoint: sb://iothub-ns-iot-dps-ci-245306-76aca8e13b.servicebus.windows.net/ + partitionCount: 2 + partitionIds: + - "0" + - "1" + path: iot-dps-cit-hub-1 + retentionTimeInDays: 1 + features: None + hostName: iot-dps-cit-hub-1.azure-devices.net + ipFilterRules: [] + messagingEndpoints: + fileNotifications: + lockDurationAsIso8601: PT1M + maxDeliveryCount: 10 + ttlAsIso8601: PT1H + provisioningState: Succeeded + routing: + endpoints: + eventHubs: [] + serviceBusQueues: [] + serviceBusTopics: [] + storageContainers: [] + fallbackRoute: + condition: "true" + endpointNames: + - events + isEnabled: true + name: $fallback + source: DeviceMessages + routes: [] + state: Active + storageEndpoints: + $default: + connectionString: "" + containerName: "" + sasTtlAsIso8601: PT1H + sku: + capacity: 1 + name: S1 + tier: Standard + tags: + foo: bar + type: Microsoft.Devices/IotHubs + x-ms-long-running-operation: true + x-codegen-request-body-name: IotHubTags + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubKeys/{keyName}/listkeys + : post: + tags: + - POST + summary: 'Get a shared access policy by name from an IoT hub. For more information, + see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security' + description: 'Get a shared access policy by name from an IoT hub. For more information, + see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.' + operationId: IotHubResource_GetKeysForKeyName + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: keyName + in: path + description: The name of the shared access policy. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + shared access policy, including keys, that you can use to access one or + more IoT hub endpoints. + content: + application/json: + schema: + $ref: '#/components/schemas/SharedAccessSignatureAuthorizationRule' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_GetKeysForKeyName: + parameters: + api-version: 2019-11-04 + keyName: iothubowner + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + keyName: iothubowner + primaryKey: 2aWPrKloLLdcug12ZHNpA0e07yJmRRmYMXDLpEOTd/Y= + rights: RegistryWrite, ServiceConnect, DeviceConnect + secondaryKey: DLyFnDTGMDK0BU2QjT5TCkNBQ4h08mi20vOqWMC7TxU= + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubStats + : get: + tags: + - GET + summary: Get the statistics from an IoT hub + description: Get the statistics from an IoT hub. + operationId: IotHubResource_GetStats + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is a synchronous operation. The body contains JSON-serialized + statistics from the identity registry in the IoT hub. + content: + application/json: + schema: + $ref: '#/components/schemas/RegistryStatistics' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_GetStats: + parameters: + api-version: 2018-04-01 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + disabledDeviceCount: 0 + enabledDeviceCount: 0 + totalDeviceCount: 0 + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates + : get: + tags: + - Certificates + summary: Get the certificate list. + description: Returns the list of certificates. + operationId: Certificates_ListByIotHub + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: The body contains all the certificate list. + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateListDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + Certificates_ListByIotHub: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testhub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - etag: AAAAAAExpNs= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/andbuc-hub/certificates/cert + name: cert + properties: + created: Thu, 12 Oct 2017 19:23:50 GMT + expiry: Sat, 31 Dec 2039 23:59:59 GMT + isVerified: false + subject: CN=testdevice1 + thumbprint: 97388663832D0393C9246CAB4FBA2C8677185A25 + updated: Thu, 12 Oct 2017 19:23:50 GMT + type: Microsoft.Devices/IotHubs/Certificates + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName} + : get: + tags: + - Certificates + summary: Get the certificate. + description: Returns the certificate. + operationId: Certificates_Get + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: certificateName + in: path + description: The name of the certificate + required: true + schema: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: The body contains the certificate. + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + Certificates_Get: + parameters: + api-version: 2019-11-04 + certificateName: cert + resourceGroupName: myResourceGroup + resourceName: testhub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAExpNs= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/andbuc-hub/certificates/cert + name: cert + properties: + created: Thu, 12 Oct 2017 19:23:50 GMT + expiry: Sat, 31 Dec 2039 23:59:59 GMT + isVerified: false + subject: CN=testdevice1 + thumbprint: 97388663832D0393C9246CAB4FBA2C8677185A25 + updated: Thu, 12 Oct 2017 19:23:50 GMT + type: Microsoft.Devices/IotHubs/Certificates + put: + tags: + - Certificates + summary: Upload the certificate to the IoT hub. + description: Adds new or replaces existing certificate. + operationId: Certificates_CreateOrUpdate + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: certificateName + in: path + description: The name of the certificate + required: true + schema: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: If-Match + in: header + description: ETag of the Certificate. Do not specify for creating a brand + new certificate. Required to update an existing certificate. + schema: + type: string + requestBody: + description: The certificate body. + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateBodyDescription' + required: true + responses: + 200: + description: If certificate already exist and update was successful, the + operation returns HTTP status code of 201 (OK). + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateDescription' + 201: + description: If certificate didn't exist creation was successful, the operation + returns HTTP status code of 201 (OK). + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + Certificates_CreateOrUpdate: + parameters: + api-version: 2019-11-04 + certificateDescription: + certificate: '############################################' + certificateName: cert + resourceGroupName: myResourceGroup + resourceName: iothub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAExpNs= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/ProvisioningServives/myFirstProvisioningService/certificates/cert + name: cert + properties: + created: Thu, 12 Oct 2017 19:23:50 GMT + expiry: Sat, 31 Dec 2039 23:59:59 GMT + isVerified: false + subject: CN=testdevice1 + thumbprint: 97388663832D0393C9246CAB4FBA2C8677185A25 + updated: Thu, 12 Oct 2017 19:23:50 GMT + type: Microsoft.Devices/IotHubs/Certificates + 201: + body: + etag: AAAAAAExpNs= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/ProvisioningServives/myFirstProvisioningService/certificates/cert + name: cert + properties: + created: Thu, 12 Oct 2017 19:23:50 GMT + expiry: Sat, 31 Dec 2039 23:59:59 GMT + isVerified: false + subject: CN=testdevice1 + thumbprint: 97388663832D0393C9246CAB4FBA2C8677185A25 + updated: Thu, 12 Oct 2017 19:23:50 GMT + type: Microsoft.Devices/IotHubs/Certificates + x-codegen-request-body-name: certificateDescription + delete: + tags: + - Certificates + summary: Delete an X509 certificate. + description: Deletes an existing X509 certificate or does nothing if it does + not exist. + operationId: Certificates_Delete + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: certificateName + in: path + description: The name of the certificate + required: true + schema: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: If-Match + in: header + description: ETag of the Certificate. + required: true + schema: + type: string + responses: + 200: + description: Certificate has been deleted. + content: {} + 204: + description: Certificate does not exist. + content: {} + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + Certificates_Delete: + parameters: + If-Match: AAAAAAAADGk= + api-version: 2019-11-04 + certificateName: cert + resourceGroupName: myResourceGroup + resourceName: myhub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: {} + 204: {} + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}/generateVerificationCode + : post: + tags: + - Certificates + summary: Generate verification code for proof of possession flow. + description: Generates verification code for proof of possession flow. The verification + code will be used to generate a leaf certificate. + operationId: Certificates_GenerateVerificationCode + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: certificateName + in: path + description: The name of the certificate + required: true + schema: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: If-Match + in: header + description: ETag of the Certificate. + required: true + schema: + type: string + responses: + 200: + description: The body contains the certificate. + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateWithNonceDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + Certificates_GenerateVerificationCode: + parameters: + If-Match: AAAAAAAADGk= + api-version: 2019-11-04 + certificateName: cert + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + name: cert + properties: + created: Thu, 12 Oct 2017 19:23:50 GMT + expiry: Sat, 31 Dec 2039 23:59:59 GMT + isVerified: false + subject: CN=andbucdevice1 + thumbprint: '##############################' + updated: Thu, 12 Oct 2017 19:26:56 GMT + verificationCode: '##################################' + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/certificates/{certificateName}/verify + : post: + tags: + - Certificates + summary: Verify certificate's private key possession. + description: Verifies the certificate's private key possession by providing + the leaf cert issued by the verifying pre uploaded certificate. + operationId: Certificates_Verify + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: certificateName + in: path + description: The name of the certificate + required: true + schema: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: If-Match + in: header + description: ETag of the Certificate. + required: true + schema: + type: string + requestBody: + description: The name of the certificate + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateVerificationDescription' + required: true + responses: + 200: + description: The body contains the certificate. + content: + application/json: + schema: + $ref: '#/components/schemas/CertificateDescription' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + Certificates_Verify: + parameters: + If-Match: AAAAAAAADGk= + api-version: 2019-11-04 + certificateName: cert + certificateVerificationBody: + certificate: '#####################################' + resourceGroupName: myResourceGroup + resourceName: myFirstProvisioningService + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAExpTQ= + id: /subscriptions/91d12660-3dec-467a-be2a-213b5544ddc0/resourceGroups/myResourceGroup/providers/Microsoft.Devices/ProvisioningServices/myFirstProvisioningService/certificates/cert + name: cert + properties: + created: Thu, 12 Oct 2017 19:23:50 GMT + expiry: Sat, 31 Dec 2039 23:59:59 GMT + isVerified: true + subject: CN=andbucdevice1 + thumbprint: 97388663832D0393C9246CAB4FBA2C8677185A25 + updated: Thu, 12 Oct 2017 19:26:56 GMT + type: Microsoft.Devices/IotHubs/Certificates + x-codegen-request-body-name: certificateVerificationBody + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups + : get: + tags: + - GET + summary: Get a list of the consumer groups in the Event Hub-compatible device-to-cloud + endpoint in an IoT hub + description: Get a list of the consumer groups in the Event Hub-compatible device-to-cloud + endpoint in an IoT hub. + operationId: IotHubResource_ListEventHubConsumerGroups + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: eventHubEndpointName + in: path + description: The name of the Event Hub-compatible endpoint. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + list of the consumer groups in the Event Hub-compatible endpoint in this + IoT hub + content: + application/json: + schema: + $ref: '#/components/schemas/EventHubConsumerGroupsListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ListEventHubConsumerGroups: + parameters: + api-version: 2019-11-04 + eventHubEndpointName: events + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - etag: AAAAAAFD6M4= + id: /subscriptions/cmd-sub-1/resourceGroups/cmd-rg-1/providers/Microsoft.Devices/IotHubs/test-hub-2/eventHubEndpoints/events/ConsumerGroups/%24Default + name: $Default + properties: + created: Thu, 15 Jun 2017 19:20:58 GMT + type: Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups + x-ms-pageable: + nextLinkName: nextLink + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name} + : get: + tags: + - GET + summary: Get a consumer group from the Event Hub-compatible device-to-cloud + endpoint for an IoT hub + description: Get a consumer group from the Event Hub-compatible device-to-cloud + endpoint for an IoT hub. + operationId: IotHubResource_GetEventHubConsumerGroup + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: eventHubEndpointName + in: path + description: The name of the Event Hub-compatible endpoint in the IoT hub. + required: true + schema: + type: string + - name: name + in: path + description: The name of the consumer group to retrieve. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + consumer group. + content: + application/json: + schema: + $ref: '#/components/schemas/EventHubConsumerGroupInfo' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ListEventHubConsumerGroups: + parameters: + api-version: 2019-11-04 + eventHubEndpointName: events + name: test + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/cmd-sub-1/resourceGroups/cmd-rg-1/providers/Microsoft.Devices/IotHubs/test-hub-2/eventHubEndpoints/events/ConsumerGroups/%24Default + name: test + properties: + created: Thu, 15 Jun 2017 19:20:58 GMT + type: Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups + put: + tags: + - PUT + summary: Add a consumer group to an Event Hub-compatible endpoint in an IoT + hub + description: Add a consumer group to an Event Hub-compatible endpoint in an + IoT hub. + operationId: IotHubResource_CreateEventHubConsumerGroup + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: eventHubEndpointName + in: path + description: The name of the Event Hub-compatible endpoint in the IoT hub. + required: true + schema: + type: string + - name: name + in: path + description: The name of the consumer group to add. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. + content: + application/json: + schema: + $ref: '#/components/schemas/EventHubConsumerGroupInfo' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_CreateEventHubConsumerGroup: + parameters: + api-version: 2019-11-04 + eventHubEndpointName: events + name: test + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + etag: AAAAAAFD6M4= + id: /subscriptions/cmd-sub-1/resourceGroups/cmd-rg-1/providers/Microsoft.Devices/IotHubs/test-hub-2/eventHubEndpoints/events/ConsumerGroups/%24Default + name: test + properties: + created: Thu, 15 Jun 2017 19:20:58 GMT + type: Microsoft.Devices/IotHubs/EventHubEndpoints/ConsumerGroups + delete: + tags: + - DELETE + summary: Delete a consumer group from an Event Hub-compatible endpoint in an + IoT hub + description: Delete a consumer group from an Event Hub-compatible endpoint in + an IoT hub. + operationId: IotHubResource_DeleteEventHubConsumerGroup + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: eventHubEndpointName + in: path + description: The name of the Event Hub-compatible endpoint in the IoT hub. + required: true + schema: + type: string + - name: name + in: path + description: The name of the consumer group to delete. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. + content: {} + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_DeleteEventHubConsumerGroup: + parameters: + api-version: 2019-11-04 + eventHubEndpointName: events + name: test + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: {} + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/exportDevices + : post: + tags: + - POST + summary: 'Exports all the device identities in the IoT hub identity registry + to an Azure Storage blob container. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities' + description: 'Exports all the device identities in the IoT hub identity registry + to an Azure Storage blob container. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.' + operationId: IotHubResource_ExportDevices + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + requestBody: + description: The parameters that specify the export devices operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportDevicesRequest' + required: true + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/JobResponse' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ExportDevices: + parameters: + api-version: 2019-11-04 + exportDevicesParameters: + excludeKeys: true + exportBlobContainerUri: testBlob + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + endTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + jobId: test + startTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + status: unknown + type: unknown + x-codegen-request-body-name: exportDevicesParameters + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/importDevices + : post: + tags: + - POST + summary: 'Import, update, or delete device identities in the IoT hub identity + registry from a blob. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities' + description: 'Import, update, or delete device identities in the IoT hub identity + registry from a blob. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.' + operationId: IotHubResource_ImportDevices + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + requestBody: + description: The parameters that specify the import devices operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportDevicesRequest' + required: true + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/JobResponse' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ImportDevices: + parameters: + api-version: 2019-11-04 + importDevicesParameters: + inputBlobContainerUri: testBlob + outputBlobContainerUri: testBlob + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + endTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + jobId: test + startTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + status: unknown + type: unknown + x-codegen-request-body-name: importDevicesParameters + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs: + get: + tags: + - GET + summary: 'Get a list of all the jobs in an IoT hub. For more information, see: + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry' + description: 'Get a list of all the jobs in an IoT hub. For more information, + see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.' + operationId: IotHubResource_ListJobs + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is a synchronous operation. The response contains a JSON-serialized + array of all the jobs in the IoT hub. + content: + application/json: + schema: + $ref: '#/components/schemas/JobResponseListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ListJobs: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - endTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + jobId: test + startTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + status: unknown + type: unknown + x-ms-pageable: + nextLinkName: nextLink + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs/{jobId} + : get: + tags: + - GET + summary: 'Get the details of a job from an IoT hub. For more information, see: + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry' + description: 'Get the details of a job from an IoT hub. For more information, + see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.' + operationId: IotHubResource_GetJob + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: jobId + in: path + description: The job identifier. + required: true + schema: + type: string + responses: + 200: + description: This is a synchronous operation. The response contains a JSON-serialized + description of the job in the IoT hub. + content: + application/json: + schema: + $ref: '#/components/schemas/JobResponse' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_GetJob: + parameters: + api-version: 2019-11-04 + jobId: test + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + endTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + jobId: test + startTimeUtc: Thu, 15 Jun 2017 19:20:58 GMT + status: unknown + type: unknown + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/listkeys: + post: + tags: + - POST + summary: 'Get the security metadata for an IoT hub. For more information, see: + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security' + description: 'Get the security metadata for an IoT hub. For more information, + see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.' + operationId: IotHubResource_ListKeys + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + array of shared access policies, including keys, that you can use to access + the IoT hub endpoints. + content: + application/json: + schema: + $ref: '#/components/schemas/SharedAccessSignatureAuthorizationRuleListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_ListKeys: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - keyName: iothubowner + primaryKey: 2aWPrKloLLdcug12ZHNpA0e07yJmRRmYMXDLpEOTd/Y= + rights: RegistryWrite, ServiceConnect, DeviceConnect + secondaryKey: DLyFnDTGMDK0BU2QjT5TCkNBQ4h08mi20vOqWMC7TxU= + - keyName: service + primaryKey: DinqxWW+s814W2Pc3dLxleelksqSYGy8Jfymt8J7a4c= + rights: ServiceConnect + secondaryKey: 5G8KgJ9Wx2T0f6HRIn25TgYcFmJnBSivawNaHssiP9Y= + - keyName: device + primaryKey: o/9gPc0oD8LY/r2lRurgl9U/sKFcL2c/tmFLKAiz+e0= + rights: DeviceConnect + secondaryKey: YOeBMHnYP95vH+ykR8OeapnhS6W8raMsXOdNFwqg4lg= + - keyName: registryRead + primaryKey: h2d4mPxy6jPCWX6mO+katV9QPNJivzt4aFq0iGVc1A8= + rights: RegistryRead + secondaryKey: 3TdcalZNTB7BZHl88LGsG1Z5T6+ElEODunrs1vylwGg= + - keyName: registryReadWrite + primaryKey: tyNRcaI38fXL+gQTjCmrVZGTP4YFF7uACk7pppWLWzY= + rights: RegistryWrite + secondaryKey: 6P6DXOp0W3HO5/IotzcPS1kx7PHiOdesaND07Im5cYI= + x-ms-pageable: + nextLinkName: nextLink + ? /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/quotaMetrics + : get: + tags: + - GET + summary: Get the quota metrics for an IoT hub + description: Get the quota metrics for an IoT hub. + operationId: IotHubResource_GetQuotaMetrics + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is a synchronous operation. The response contains a JSON-serialized + array of the quota metrics for the IoT hub. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubQuotaMetricInfoListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_GetQuotaMetrics: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - currentValue: 0 + maxValue: 400000 + name: TotalMessages + - currentValue: 0 + maxValue: 500000 + name: TotalDeviceCount + x-ms-pageable: + nextLinkName: nextLink + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/skus: + get: + tags: + - GET + summary: Get the list of valid SKUs for an IoT hub + description: Get the list of valid SKUs for an IoT hub. + operationId: IotHubResource_GetValidSkus + parameters: + - name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + - name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + - name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + - name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + responses: + 200: + description: This is a synchronous operation. The body contains a JSON-serialized + array of the valid SKUs for this IoT hub. + content: + application/json: + schema: + $ref: '#/components/schemas/IotHubSkuDescriptionListResult' + default: + description: DefaultErrorResponse + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorDetails' + deprecated: false + x-ms-examples: + IotHubResource_GetValidSkus: + parameters: + api-version: 2019-11-04 + resourceGroupName: myResourceGroup + resourceName: testHub + subscriptionId: 91d12660-3dec-467a-be2a-213b5544ddc0 + responses: + 200: + body: + value: + - capacity: + default: 1 + scaleType: Manual + resourceType: Microsoft.Devices/IotHubs + sku: + name: S1 + tier: Standard + - capacity: + default: 1 + maximum: 200 + minimum: 1 + scaleType: Manual + resourceType: Microsoft.Devices/IotHubs + sku: + name: S2 + tier: Standard + - capacity: + default: 1 + maximum: 10 + minimum: 1 + scaleType: Manual + resourceType: Microsoft.Devices/IotHubs + sku: + name: S3 + tier: Standard + x-ms-pageable: + nextLinkName: nextLink +components: + schemas: + CertificateBodyDescription: + type: object + properties: + certificate: + type: string + description: base-64 representation of the X509 leaf certificate .cer file + or just .pem file content. + description: The JSON-serialized X509 Certificate. + CertificateDescription: + type: object + properties: + etag: + type: string + description: The entity tag. + readOnly: true + id: + type: string + description: The resource identifier. + readOnly: true + name: + type: string + description: The name of the certificate. + readOnly: true + properties: + $ref: '#/components/schemas/CertificateProperties' + type: + type: string + description: The resource type. + readOnly: true + description: The X509 Certificate. + x-ms-azure-resource: true + CertificateListDescription: + type: object + properties: + value: + type: array + description: The array of Certificate objects. + items: + $ref: '#/components/schemas/CertificateDescription' + description: The JSON-serialized array of Certificate objects. + CertificateProperties: + type: object + properties: + certificate: + type: string + description: The certificate content + created: + type: string + description: The certificate's create date and time. + format: date-time-rfc1123 + readOnly: true + expiry: + type: string + description: The certificate's expiration date and time. + format: date-time-rfc1123 + readOnly: true + isVerified: + type: boolean + description: Determines whether certificate has been verified. + readOnly: true + subject: + type: string + description: The certificate's subject name. + readOnly: true + thumbprint: + type: string + description: The certificate's thumbprint. + readOnly: true + updated: + type: string + description: The certificate's last update date and time. + format: date-time-rfc1123 + readOnly: true + description: The description of an X509 CA Certificate. + CertificatePropertiesWithNonce: + type: object + properties: + certificate: + type: string + description: The certificate content + readOnly: true + created: + type: string + description: The certificate's create date and time. + format: date-time-rfc1123 + readOnly: true + expiry: + type: string + description: The certificate's expiration date and time. + format: date-time-rfc1123 + readOnly: true + isVerified: + type: boolean + description: Determines whether certificate has been verified. + readOnly: true + subject: + type: string + description: The certificate's subject name. + readOnly: true + thumbprint: + type: string + description: The certificate's thumbprint. + readOnly: true + updated: + type: string + description: The certificate's last update date and time. + format: date-time-rfc1123 + readOnly: true + verificationCode: + type: string + description: The certificate's verification code that will be used for proof + of possession. + readOnly: true + description: The description of an X509 CA Certificate including the challenge + nonce issued for the Proof-Of-Possession flow. + CertificateVerificationDescription: + type: object + properties: + certificate: + type: string + description: base-64 representation of X509 certificate .cer file or just + .pem file content. + description: The JSON-serialized leaf certificate + CertificateWithNonceDescription: + type: object + properties: + etag: + type: string + description: The entity tag. + readOnly: true + id: + type: string + description: The resource identifier. + readOnly: true + name: + type: string + description: The name of the certificate. + readOnly: true + properties: + $ref: '#/components/schemas/CertificatePropertiesWithNonce' + type: + type: string + description: The resource type. + readOnly: true + description: The X509 Certificate. + x-ms-azure-resource: true + CloudToDeviceProperties: + type: object + properties: + defaultTtlAsIso8601: + type: string + description: 'The default time to live for cloud-to-device messages in the + device queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.' + format: duration + feedback: + $ref: '#/components/schemas/FeedbackProperties' + maxDeliveryCount: + maximum: 1E+2 + minimum: 1 + type: integer + description: 'The max delivery count for cloud-to-device messages in the + device queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.' + format: int32 + description: The IoT hub cloud-to-device messaging properties. + EndpointHealthData: + type: object + properties: + endpointId: + type: string + description: Id of the endpoint + healthStatus: + type: string + description: Health statuses have following meanings. The 'healthy' status + shows that the endpoint is accepting messages as expected. The 'unhealthy' + status shows that the endpoint is not accepting messages as expected and + IoT Hub is retrying to send data to this endpoint. The status of an unhealthy + endpoint will be updated to healthy when IoT Hub has established an eventually + consistent state of health. The 'dead' status shows that the endpoint + is not accepting messages, after IoT Hub retried sending messages for + the retrial period. See IoT Hub metrics to identify errors and monitor + issues with endpoints. The 'unknown' status shows that the IoT Hub has + not established a connection with the endpoint. No messages have been + delivered to or rejected from this endpoint + enum: + - unknown + - healthy + - unhealthy + - dead + x-ms-enum: + modelAsString: true + name: EndpointHealthStatus + description: The health data for an endpoint + EndpointHealthDataListResult: + type: object + properties: + nextLink: + type: string + description: Link to more results + readOnly: true + value: + type: array + description: JSON-serialized array of Endpoint health data + items: + $ref: '#/components/schemas/EndpointHealthData' + description: The JSON-serialized array of EndpointHealthData objects with a + next link. + EnrichmentProperties: + required: + - endpointNames + - key + - value + type: object + properties: + endpointNames: + minItems: 1 + type: array + description: The list of endpoints for which the enrichment is applied to + the message. + items: + type: string + key: + type: string + description: The key or name for the enrichment property. + value: + type: string + description: The value for the enrichment property. + description: The properties of an enrichment that your IoT hub applies to messages + delivered to endpoints. + ErrorDetails: + type: object + properties: + code: + type: string + description: The error code. + readOnly: true + details: + type: string + description: The error details. + readOnly: true + httpStatusCode: + type: string + description: The HTTP status code. + readOnly: true + message: + type: string + description: The error message. + readOnly: true + description: Error details. + EventHubConsumerGroupInfo: + type: object + properties: + etag: + type: string + description: The etag. + readOnly: true + id: + type: string + description: The Event Hub-compatible consumer group identifier. + readOnly: true + name: + type: string + description: The Event Hub-compatible consumer group name. + readOnly: true + properties: + type: object + additionalProperties: + type: string + description: The tags. + type: + type: string + description: the resource type. + readOnly: true + description: The properties of the EventHubConsumerGroupInfo object. + x-ms-azure-resource: true + EventHubConsumerGroupsListResult: + type: object + properties: + nextLink: + type: string + description: The next link. + readOnly: true + value: + type: array + description: List of consumer groups objects + items: + $ref: '#/components/schemas/EventHubConsumerGroupInfo' + description: The JSON-serialized array of Event Hub-compatible consumer group + names with a next link. + EventHubProperties: + type: object + properties: + endpoint: + type: string + description: The Event Hub-compatible endpoint. + readOnly: true + partitionCount: + type: integer + description: 'The number of partitions for receiving device-to-cloud messages + in the Event Hub-compatible endpoint. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#device-to-cloud-messages.' + format: int32 + partitionIds: + type: array + description: The partition ids in the Event Hub-compatible endpoint. + readOnly: true + items: + type: string + path: + type: string + description: The Event Hub-compatible name. + readOnly: true + retentionTimeInDays: + type: integer + description: 'The retention time for device-to-cloud messages in days. See: + https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#device-to-cloud-messages' + format: int64 + description: The properties of the provisioned Event Hub-compatible endpoint + used by the IoT hub. + ExportDevicesRequest: + required: + - excludeKeys + - exportBlobContainerUri + type: object + properties: + excludeKeys: + type: boolean + description: The value indicating whether keys should be excluded during + export. + exportBlobContainerUri: + type: string + description: The export blob container URI. + description: Use to provide parameters when requesting an export of all devices + in the IoT hub. + FailoverInput: + required: + - failoverRegion + type: object + properties: + failoverRegion: + type: string + description: Region the hub will be failed over to + description: Use to provide failover region when requesting manual Failover + for a hub. + FallbackRouteProperties: + required: + - endpointNames + - isEnabled + - source + type: object + properties: + condition: + type: string + description: 'The condition which is evaluated in order to apply the fallback + route. If the condition is not provided it will evaluate to true by default. + For grammar, See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language' + endpointNames: + maxItems: 1 + minItems: 1 + type: array + description: The list of endpoints to which the messages that satisfy the + condition are routed to. Currently only 1 endpoint is allowed. + items: + type: string + isEnabled: + type: boolean + description: Used to specify whether the fallback route is enabled. + name: + type: string + description: The name of the route. The name can only include alphanumeric + characters, periods, underscores, hyphens, has a maximum length of 64 + characters, and must be unique. + source: + type: string + description: The source to which the routing rule is to be applied to. For + example, DeviceMessages + enum: + - DeviceMessages + x-ms-enum: + modelAsString: true + name: RoutingSource + description: The properties of the fallback route. IoT Hub uses these properties + when it routes messages to the fallback endpoint. + FeedbackProperties: + type: object + properties: + lockDurationAsIso8601: + type: string + description: 'The lock duration for the feedback queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.' + format: duration + maxDeliveryCount: + maximum: 1E+2 + minimum: 1 + type: integer + description: 'The number of times the IoT hub attempts to deliver a message + on the feedback queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.' + format: int32 + ttlAsIso8601: + type: string + description: 'The period of time for which a message is available to consume + before it is expired by the IoT hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.' + format: duration + description: The properties of the feedback queue for cloud-to-device messages. + ImportDevicesRequest: + required: + - inputBlobContainerUri + - outputBlobContainerUri + type: object + properties: + inputBlobContainerUri: + type: string + description: The input blob container URI. + outputBlobContainerUri: + type: string + description: The output blob container URI. + description: Use to provide parameters when requesting an import of all devices + in the hub. + IotHubCapacity: + type: object + properties: + default: + type: integer + description: The default number of units. + format: int64 + readOnly: true + maximum: + type: integer + description: The maximum number of units. + format: int64 + readOnly: true + minimum: + maximum: 1 + minimum: 1 + type: integer + description: The minimum number of units. + format: int64 + readOnly: true + scaleType: + type: string + description: The type of the scaling enabled. + readOnly: true + enum: + - Automatic + - Manual + - None + x-ms-enum: + modelAsString: false + name: IotHubScaleType + description: IoT Hub capacity information. + IotHubDescription: + description: The description of the IoT hub. + allOf: + - $ref: '#/components/schemas/Resource' + IotHubDescriptionListResult: + type: object + properties: + nextLink: + type: string + description: The next link. + readOnly: true + value: + type: array + description: The array of IotHubDescription objects. + items: + $ref: '#/components/schemas/IotHubDescription' + description: The JSON-serialized array of IotHubDescription objects with a next + link. + IotHubLocationDescription: + type: object + properties: + location: + type: string + description: The name of the Azure region + role: + type: string + description: The role of the region, can be either primary or secondary. + The primary region is where the IoT hub is currently provisioned. The + secondary region is the Azure disaster recovery (DR) paired region and + also the region where the IoT hub can failover to. + enum: + - primary + - secondary + x-ms-enum: + modelAsString: true + name: IotHubReplicaRoleType + description: Public representation of one of the locations where a resource + is provisioned. + IotHubNameAvailabilityInfo: + type: object + properties: + message: + type: string + description: The detailed reason message. + nameAvailable: + type: boolean + description: The value which indicates whether the provided name is available. + readOnly: true + reason: + type: string + description: The reason for unavailability. + readOnly: true + enum: + - Invalid + - AlreadyExists + x-ms-enum: + modelAsString: false + name: IotHubNameUnavailabilityReason + description: The properties indicating whether a given IoT hub name is available. + IotHubProperties: + type: object + properties: + authorizationPolicies: + type: array + description: The shared access policies you can use to secure a connection + to the IoT hub. + items: + $ref: '#/components/schemas/SharedAccessSignatureAuthorizationRule' + cloudToDevice: + $ref: '#/components/schemas/CloudToDeviceProperties' + comments: + type: string + description: IoT hub comments. + enableFileUploadNotifications: + type: boolean + description: If True, file upload notifications are enabled. + eventHubEndpoints: + type: object + additionalProperties: + $ref: '#/components/schemas/EventHubProperties' + description: The Event Hub-compatible endpoint properties. The only possible + keys to this dictionary is events. This key has to be present in the dictionary + while making create or update calls for the IoT hub. + features: + type: string + description: The capabilities and features enabled for the IoT hub. + enum: + - None + - DeviceManagement + x-ms-enum: + modelAsString: true + name: Capabilities + hostName: + type: string + description: The name of the host. + readOnly: true + ipFilterRules: + type: array + description: The IP filter rules. + items: + $ref: '#/components/schemas/IpFilterRule' + locations: + type: array + description: Primary and secondary location for iot hub + readOnly: true + items: + $ref: '#/components/schemas/IotHubLocationDescription' + messagingEndpoints: + type: object + additionalProperties: + $ref: '#/components/schemas/MessagingEndpointProperties' + description: The messaging endpoint properties for the file upload notification + queue. + provisioningState: + type: string + description: The provisioning state. + readOnly: true + routing: + $ref: '#/components/schemas/RoutingProperties' + state: + type: string + description: The hub state. + readOnly: true + storageEndpoints: + type: object + additionalProperties: + $ref: '#/components/schemas/StorageEndpointProperties' + description: The list of Azure Storage endpoints where you can upload files. + Currently you can configure only one Azure Storage account and that MUST + have its key as $default. Specifying more than one storage account causes + an error to be thrown. Not specifying a value for this property when the + enableFileUploadNotifications property is set to True, causes an error + to be thrown. + description: The properties of an IoT hub. + IotHubQuotaMetricInfo: + type: object + properties: + currentValue: + type: integer + description: The current value for the quota metric. + format: int64 + readOnly: true + maxValue: + type: integer + description: The maximum value of the quota metric. + format: int64 + readOnly: true + name: + type: string + description: The name of the quota metric. + readOnly: true + description: Quota metrics properties. + IotHubQuotaMetricInfoListResult: + type: object + properties: + nextLink: + type: string + description: The next link. + readOnly: true + value: + type: array + description: The array of quota metrics objects. + items: + $ref: '#/components/schemas/IotHubQuotaMetricInfo' + description: The JSON-serialized array of IotHubQuotaMetricInfo objects with + a next link. + IotHubSkuDescription: + required: + - capacity + - sku + type: object + properties: + capacity: + $ref: '#/components/schemas/IotHubCapacity' + resourceType: + type: string + description: The type of the resource. + readOnly: true + sku: + $ref: '#/components/schemas/IotHubSkuInfo' + description: SKU properties. + IotHubSkuDescriptionListResult: + type: object + properties: + nextLink: + type: string + description: The next link. + readOnly: true + value: + type: array + description: The array of IotHubSkuDescription. + items: + $ref: '#/components/schemas/IotHubSkuDescription' + description: The JSON-serialized array of IotHubSkuDescription objects with + a next link. + IotHubSkuInfo: + required: + - name + type: object + properties: + capacity: + type: integer + description: 'The number of provisioned IoT Hub units. See: https://docs.microsoft.com/azure/azure-subscription-service-limits#iot-hub-limits.' + format: int64 + name: + type: string + description: The name of the SKU. + enum: + - F1 + - S1 + - S2 + - S3 + - B1 + - B2 + - B3 + x-ms-enum: + modelAsString: true + name: IotHubSku + tier: + type: string + description: The billing tier for the IoT hub. + readOnly: true + enum: + - Free + - Standard + - Basic + x-ms-enum: + modelAsString: false + name: IotHubSkuTier + description: Information about the SKU of the IoT hub. + IpFilterRule: + required: + - action + - filterName + - ipMask + type: object + properties: + action: + type: string + description: The desired action for requests captured by this rule. + enum: + - Accept + - Reject + x-ms-enum: + modelAsString: false + name: IpFilterActionType + filterName: + type: string + description: The name of the IP filter rule. + ipMask: + type: string + description: A string that contains the IP address range in CIDR notation + for the rule. + description: The IP filter rules for the IoT hub. + JobResponse: + type: object + properties: + endTimeUtc: + type: string + description: The time the job stopped processing. + format: date-time-rfc1123 + readOnly: true + failureReason: + type: string + description: If status == failed, this string containing the reason for + the failure. + readOnly: true + jobId: + type: string + description: The job identifier. + readOnly: true + parentJobId: + type: string + description: The job identifier of the parent job, if any. + readOnly: true + startTimeUtc: + type: string + description: The start time of the job. + format: date-time-rfc1123 + readOnly: true + status: + type: string + description: The status of the job. + readOnly: true + enum: + - unknown + - enqueued + - running + - completed + - failed + - cancelled + x-ms-enum: + modelAsString: false + name: JobStatus + statusMessage: + type: string + description: The status message for the job. + readOnly: true + type: + type: string + description: The type of the job. + readOnly: true + enum: + - unknown + - export + - import + - backup + - readDeviceProperties + - writeDeviceProperties + - updateDeviceConfiguration + - rebootDevice + - factoryResetDevice + - firmwareUpdate + x-ms-enum: + modelAsString: true + name: JobType + description: The properties of the Job Response object. + JobResponseListResult: + type: object + properties: + nextLink: + type: string + description: The next link. + readOnly: true + value: + type: array + description: The array of JobResponse objects. + items: + $ref: '#/components/schemas/JobResponse' + description: The JSON-serialized array of JobResponse objects with a next link. + MatchedRoute: + type: object + properties: + properties: + $ref: '#/components/schemas/RouteProperties' + description: Routes that matched + MessagingEndpointProperties: + type: object + properties: + lockDurationAsIso8601: + type: string + description: 'The lock duration. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload.' + format: duration + maxDeliveryCount: + maximum: 1E+2 + minimum: 1 + type: integer + description: 'The number of times the IoT hub attempts to deliver a message. + See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload.' + format: int32 + ttlAsIso8601: + type: string + description: 'The period of time for which a message is available to consume + before it is expired by the IoT hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload.' + format: duration + description: The properties of the messaging endpoints used by this IoT hub. + Name: + type: object + properties: + localizedValue: + type: string + description: Localized value of name + value: + type: string + description: IotHub type + description: Name of Iot Hub type + Operation: + type: object + properties: + display: + type: object + properties: + description: + type: string + description: Description of the operation + readOnly: true + operation: + type: string + description: Name of the operation + readOnly: true + provider: + type: string + description: 'Service provider: Microsoft Devices' + readOnly: true + resource: + type: string + description: 'Resource Type: IotHubs' + readOnly: true + description: The object that represents the operation. + name: + type: string + description: 'Operation name: {provider}/{resource}/{read | write | action + | delete}' + readOnly: true + description: IoT Hub REST API operation + OperationInputs: + required: + - name + type: object + properties: + name: + type: string + description: The name of the IoT hub to check. + description: Input values. + OperationListResult: + type: object + properties: + nextLink: + type: string + description: URL to get the next set of operation list results if there + are any. + readOnly: true + value: + type: array + description: List of IoT Hub operations supported by the Microsoft.Devices + resource provider. + readOnly: true + items: + $ref: '#/components/schemas/Operation' + description: Result of the request to list IoT Hub operations. It contains a + list of operations and a URL link to get the next set of results. + RegistryStatistics: + type: object + properties: + disabledDeviceCount: + type: integer + description: The count of disabled devices in the identity registry. + format: int64 + readOnly: true + enabledDeviceCount: + type: integer + description: The count of enabled devices in the identity registry. + format: int64 + readOnly: true + totalDeviceCount: + type: integer + description: The total count of devices in the identity registry. + format: int64 + readOnly: true + description: Identity registry statistics. + Resource: + required: + - location + type: object + properties: + id: + type: string + description: The resource identifier. + readOnly: true + location: + type: string + description: The resource location. + name: + pattern: ^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$ + type: string + description: The resource name. + readOnly: true + tags: + type: object + additionalProperties: + type: string + description: The resource tags. + type: + type: string + description: The resource type. + readOnly: true + description: The common properties of an Azure resource. + x-ms-azure-resource: true + RouteCompilationError: + type: object + properties: + location: + $ref: '#/components/schemas/RouteErrorRange' + message: + type: string + description: Route error message + severity: + type: string + description: Severity of the route error + enum: + - error + - warning + x-ms-enum: + modelAsString: true + name: RouteErrorSeverity + description: Compilation error when evaluating route + RouteErrorPosition: + type: object + properties: + column: + type: integer + description: Column where the route error happened + format: int32 + line: + type: integer + description: Line where the route error happened + format: int32 + description: Position where the route error happened + RouteErrorRange: + type: object + properties: + end: + $ref: '#/components/schemas/RouteErrorPosition' + start: + $ref: '#/components/schemas/RouteErrorPosition' + description: Range of route errors + RouteProperties: + required: + - endpointNames + - isEnabled + - name + - source + type: object + properties: + condition: + type: string + description: 'The condition that is evaluated to apply the routing rule. + If no condition is provided, it evaluates to true by default. For grammar, + see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language' + endpointNames: + maxItems: 1 + minItems: 1 + type: array + description: The list of endpoints to which messages that satisfy the condition + are routed. Currently only one endpoint is allowed. + items: + type: string + isEnabled: + type: boolean + description: Used to specify whether a route is enabled. + name: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + description: The name of the route. The name can only include alphanumeric + characters, periods, underscores, hyphens, has a maximum length of 64 + characters, and must be unique. + source: + type: string + description: The source that the routing rule is to be applied to, such + as DeviceMessages. + enum: + - Invalid + - DeviceMessages + - TwinChangeEvents + - DeviceLifecycleEvents + - DeviceJobLifecycleEvents + x-ms-enum: + modelAsString: true + name: RoutingSource + description: The properties of a routing rule that your IoT hub uses to route + messages to endpoints. + RoutingEndpoints: + type: object + properties: + eventHubs: + type: array + description: The list of Event Hubs endpoints that IoT hub routes messages + to, based on the routing rules. This list does not include the built-in + Event Hubs endpoint. + items: + $ref: '#/components/schemas/RoutingEventHubProperties' + serviceBusQueues: + type: array + description: The list of Service Bus queue endpoints that IoT hub routes + the messages to, based on the routing rules. + items: + $ref: '#/components/schemas/RoutingServiceBusQueueEndpointProperties' + serviceBusTopics: + type: array + description: The list of Service Bus topic endpoints that the IoT hub routes + the messages to, based on the routing rules. + items: + $ref: '#/components/schemas/RoutingServiceBusTopicEndpointProperties' + storageContainers: + type: array + description: The list of storage container endpoints that IoT hub routes + messages to, based on the routing rules. + items: + $ref: '#/components/schemas/RoutingStorageContainerProperties' + description: The properties related to the custom endpoints to which your IoT + hub routes messages based on the routing rules. A maximum of 10 custom endpoints + are allowed across all endpoint types for paid hubs and only 1 custom endpoint + is allowed across all endpoint types for free hubs. + RoutingEventHubProperties: + required: + - connectionString + - name + type: object + properties: + connectionString: + type: string + description: 'The connection string of the event hub endpoint. ' + name: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + description: 'The name that identifies this endpoint. The name can only + include alphanumeric characters, periods, underscores, hyphens and has + a maximum length of 64 characters. The following names are reserved: events, + fileNotifications, $default. Endpoint names must be unique across endpoint + types.' + resourceGroup: + type: string + description: The name of the resource group of the event hub endpoint. + subscriptionId: + type: string + description: The subscription identifier of the event hub endpoint. + description: The properties related to an event hub endpoint. + RoutingMessage: + type: object + properties: + appProperties: + type: object + additionalProperties: + type: string + description: App properties + body: + type: string + description: Body of routing message + systemProperties: + type: object + additionalProperties: + type: string + description: System properties + description: Routing message + RoutingProperties: + type: object + properties: + endpoints: + $ref: '#/components/schemas/RoutingEndpoints' + enrichments: + type: array + description: 'The list of user-provided enrichments that the IoT hub applies + to messages to be delivered to built-in and custom endpoints. See: https://aka.ms/telemetryoneventgrid' + items: + $ref: '#/components/schemas/EnrichmentProperties' + fallbackRoute: + $ref: '#/components/schemas/FallbackRouteProperties' + routes: + type: array + description: The list of user-provided routing rules that the IoT hub uses + to route messages to built-in and custom endpoints. A maximum of 100 routing + rules are allowed for paid hubs and a maximum of 5 routing rules are allowed + for free hubs. + items: + $ref: '#/components/schemas/RouteProperties' + description: 'The routing related properties of the IoT hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging' + RoutingServiceBusQueueEndpointProperties: + required: + - connectionString + - name + type: object + properties: + connectionString: + type: string + description: The connection string of the service bus queue endpoint. + name: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + description: 'The name that identifies this endpoint. The name can only + include alphanumeric characters, periods, underscores, hyphens and has + a maximum length of 64 characters. The following names are reserved: events, + fileNotifications, $default. Endpoint names must be unique across endpoint + types. The name need not be the same as the actual queue name.' + resourceGroup: + type: string + description: The name of the resource group of the service bus queue endpoint. + subscriptionId: + type: string + description: The subscription identifier of the service bus queue endpoint. + description: The properties related to service bus queue endpoint types. + RoutingServiceBusTopicEndpointProperties: + required: + - connectionString + - name + type: object + properties: + connectionString: + type: string + description: The connection string of the service bus topic endpoint. + name: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + description: 'The name that identifies this endpoint. The name can only + include alphanumeric characters, periods, underscores, hyphens and has + a maximum length of 64 characters. The following names are reserved: events, + fileNotifications, $default. Endpoint names must be unique across endpoint + types. The name need not be the same as the actual topic name.' + resourceGroup: + type: string + description: The name of the resource group of the service bus topic endpoint. + subscriptionId: + type: string + description: The subscription identifier of the service bus topic endpoint. + description: The properties related to service bus topic endpoint types. + RoutingStorageContainerProperties: + required: + - connectionString + - containerName + - name + type: object + properties: + batchFrequencyInSeconds: + maximum: 7.2E+2 + minimum: 6E+1 + type: integer + description: Time interval at which blobs are written to storage. Value + should be between 60 and 720 seconds. Default value is 300 seconds. + format: int32 + connectionString: + type: string + description: The connection string of the storage account. + containerName: + type: string + description: The name of storage container in the storage account. + encoding: + type: string + description: Encoding that is used to serialize messages to blobs. Supported + values are 'avro', 'avrodeflate', and 'JSON'. Default value is 'avro'. + enum: + - Avro + - AvroDeflate + - JSON + fileNameFormat: + type: string + description: File name format for the blob. Default format is {iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}. + All parameters are mandatory but can be reordered. + maxChunkSizeInBytes: + maximum: 5.24288E+8 + minimum: 1.048576E+7 + type: integer + description: Maximum number of bytes for each blob written to storage. Value + should be between 10485760(10MB) and 524288000(500MB). Default value is + 314572800(300MB). + format: int32 + name: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + description: 'The name that identifies this endpoint. The name can only + include alphanumeric characters, periods, underscores, hyphens and has + a maximum length of 64 characters. The following names are reserved: events, + fileNotifications, $default. Endpoint names must be unique across endpoint + types.' + resourceGroup: + type: string + description: The name of the resource group of the storage account. + subscriptionId: + type: string + description: The subscription identifier of the storage account. + description: The properties related to a storage container endpoint. + RoutingTwin: + type: object + properties: + properties: + type: object + properties: + desired: + type: object + properties: {} + description: Twin desired properties + reported: + type: object + properties: {} + description: Twin desired properties + tags: + type: object + properties: {} + description: Twin Tags + description: Twin reference input parameter. This is an optional parameter + SharedAccessSignatureAuthorizationRule: + required: + - keyName + - rights + type: object + properties: + keyName: + type: string + description: The name of the shared access policy. + primaryKey: + type: string + description: The primary key. + rights: + type: string + description: The permissions assigned to the shared access policy. + enum: + - RegistryRead + - RegistryWrite + - ServiceConnect + - DeviceConnect + - RegistryRead, RegistryWrite + - RegistryRead, ServiceConnect + - RegistryRead, DeviceConnect + - RegistryWrite, ServiceConnect + - RegistryWrite, DeviceConnect + - ServiceConnect, DeviceConnect + - RegistryRead, RegistryWrite, ServiceConnect + - RegistryRead, RegistryWrite, DeviceConnect + - RegistryRead, ServiceConnect, DeviceConnect + - RegistryWrite, ServiceConnect, DeviceConnect + - RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect + x-ms-enum: + modelAsString: false + name: AccessRights + secondaryKey: + type: string + description: The secondary key. + description: The properties of an IoT hub shared access policy. + SharedAccessSignatureAuthorizationRuleListResult: + type: object + properties: + nextLink: + type: string + description: The next link. + readOnly: true + value: + type: array + description: The list of shared access policies. + items: + $ref: '#/components/schemas/SharedAccessSignatureAuthorizationRule' + description: The list of shared access policies with a next link. + StorageEndpointProperties: + required: + - connectionString + - containerName + type: object + properties: + connectionString: + type: string + description: The connection string for the Azure Storage account to which + files are uploaded. + containerName: + type: string + description: The name of the root container where you upload files. The + container need not exist but should be creatable using the connectionString + specified. + sasTtlAsIso8601: + type: string + description: 'The period of time for which the SAS URI generated by IoT + Hub for file upload is valid. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload#file-upload-notification-configuration-options.' + format: duration + description: The properties of the Azure Storage endpoint for file upload. + TagsResource: + type: object + properties: + tags: + type: object + description: Resource tags + description: A container holding only the Tags for a resource, allowing the + user to update the tags on an IoT Hub instance. + TestAllRoutesInput: + type: object + properties: + message: + $ref: '#/components/schemas/RoutingMessage' + routingSource: + type: string + description: Routing source + enum: + - Invalid + - DeviceMessages + - TwinChangeEvents + - DeviceLifecycleEvents + - DeviceJobLifecycleEvents + x-ms-enum: + modelAsString: true + name: RoutingSource + twin: + $ref: '#/components/schemas/RoutingTwin' + description: Input for testing all routes + TestAllRoutesResult: + type: object + properties: + routes: + type: array + description: JSON-serialized array of matched routes + items: + $ref: '#/components/schemas/MatchedRoute' + description: Result of testing all routes + TestRouteInput: + required: + - route + type: object + properties: + message: + $ref: '#/components/schemas/RoutingMessage' + route: + $ref: '#/components/schemas/RouteProperties' + twin: + $ref: '#/components/schemas/RoutingTwin' + description: Input for testing route + TestRouteResult: + type: object + properties: + details: + $ref: '#/components/schemas/TestRouteResultDetails' + result: + type: string + description: Result of testing route + enum: + - undefined + - "false" + - "true" + x-ms-enum: + modelAsString: true + name: TestResultStatus + description: Result of testing one route + TestRouteResultDetails: + type: object + properties: + compilationErrors: + type: array + description: JSON-serialized list of route compilation errors + items: + $ref: '#/components/schemas/RouteCompilationError' + description: Detailed result of testing a route + UserSubscriptionQuota: + type: object + properties: + currentValue: + type: integer + description: Current number of IotHub type + format: int32 + id: + type: string + description: IotHub type id + limit: + type: integer + description: Numerical limit on IotHub type + format: int32 + name: + $ref: '#/components/schemas/Name' + type: + type: string + description: Response type + unit: + type: string + description: Unit of IotHub type + description: User subscription quota response + UserSubscriptionQuotaListResult: + type: object + properties: + nextLink: + type: string + readOnly: true + value: + type: array + items: + $ref: '#/components/schemas/UserSubscriptionQuota' + description: Json-serialized array of User subscription quota response + parameters: + api-version: + name: api-version + in: query + description: The version of the API. + required: true + schema: + type: string + certificateName: + name: certificateName + in: path + description: The name of the certificate + required: true + schema: + pattern: ^[A-Za-z0-9-._]{1,64}$ + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + resourceGroupName: + name: resourceGroupName + in: path + description: The name of the resource group that contains the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + resourceName: + name: resourceName + in: path + description: The name of the IoT hub. + required: true + schema: + type: string + x-ms-parameter-location: method + x-ms-parameter-location: method + subscriptionId: + name: subscriptionId + in: path + description: The subscription identifier. + required: true + schema: + type: string + securitySchemes: + azure_auth: + type: oauth2 + description: Azure Active Directory OAuth2 Flow + flows: + implicit: + authorizationUrl: https://login.microsoftonline.com/common/oauth2/authorize + scopes: + user_impersonation: impersonate your user account diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/beezup.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/beezup.yaml new file mode 100644 index 000000000..ec54758f5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/beezup.yaml @@ -0,0 +1,24163 @@ +openapi: 3.0.1 +info: + title: 'BeezUP Merchant API' + x-ballerina-display: + label: BeezUP Merchant + iconPath: icon.png + description: >- + This is a generated connector for [BeezUP Merchant API + v2.0](https://api-docs.beezup.com/swagger-ui/) OpenAPI + specification. + BeezUP Merchant API provides capability to read and write BeezUP data such as accounts, stores, product catalog, channel search etc. + + x-ballerina-init-description: >- + The connector initialization requires setting the API credentials. + + Create a [BeezUP account](www.beezup.com) and obtain tokens by following + [this guide](https://api-docs.beezup.com/swagger-ui/). + + contact: + email: help@beezup.com + license: + name: BeezUP + url: https://www.beezup.com/ + version: '2.0' + x-logo: + url: https://avatars0.githubusercontent.com/u/25665430 + backgroundColor: '#FFFFFF' +externalDocs: + description: Find the documentation for BeezUP's API here + url: https://api-docs.beezup.com/ +servers: + - url: https://api.beezup.com/ +security: + - api_key: [] +tags: + - name: Public - Security - Security + x-displayName: Security + - name: Public - Channels - Public Channels + x-displayName: Public Channels + - name: Public - List of Values - LOV + x-displayName: LOV + - name: User - List of Values - LOV + x-displayName: LOV + - name: Customer - Global + x-displayName: Global + - name: Customer - Account + x-displayName: Account + - name: Customer - Security + x-displayName: Security + - name: Customer - Stores + x-displayName: Stores + - name: Customer - Shares + x-displayName: Shares + - name: Customer - Alerts + x-displayName: Alerts + - name: Customer - Rights + x-displayName: Rights + - name: Customer - Friends + x-displayName: Friends + - name: Customer - Contracts + x-displayName: Contracts + - name: Customer - Invoices + x-displayName: Invoices + - name: Catalogs - Auto + x-displayName: Auto + - name: Catalogs - Global + x-displayName: Global + - name: Catalogs - Importation Process + x-displayName: Importation Process + - name: Catalogs - Importation Catalog Info + x-displayName: Importation Catalog Info + - name: Catalogs - Catalog + x-displayName: Catalog + - name: Channels - Channels Global + x-displayName: Channels Global + - name: Channel Catalogs - Global + x-displayName: Global + - name: Channel Catalogs - Settings + x-displayName: Settings + - name: Channel Catalogs - Column Mappings + x-displayName: Column Mappings + - name: Channel Catalogs - Categories + x-displayName: Categories + - name: Channel Catalogs - Exclusion Filters + x-displayName: Exclusion Filters + - name: Channel Catalogs - Products + x-displayName: Products + - name: Channel Catalogs - Products Overrides + x-displayName: Products Overrides + - name: Channel Catalogs - Products Optimisation + x-displayName: Products Optimisation + - name: Channel Catalogs - Exportations + x-displayName: Exportations + - name: Marketplaces - Channel catalogs - Global + x-displayName: Global + - name: Marketplaces - Channel catalogs - Publications + x-displayName: Publications + - name: Marketplaces - Channel catalogs - Settings + x-displayName: Settings + - name: Marketplaces - Orders - Global + x-displayName: Global + - name: Marketplaces - Orders - AutoTransitions + x-displayName: AutoTransitions + - name: Marketplaces - Orders - List + x-displayName: List + - name: Marketplaces - Orders - Order + x-displayName: Order + - name: Marketplaces - Orders - Batches + x-displayName: Batches + - name: Marketplaces - Orders - Exports + x-displayName: Exports + - name: Marketplaces - Orders V3 - Global + x-displayName: Global + - name: Marketplaces - Orders V3 - List + x-displayName: List + - name: Marketplaces - Orders V3 - Order + x-displayName: Order + - name: Marketplaces - Orders V3 - Batches + x-displayName: Batches + - name: Marketplaces - Orders - Subscriptions - Subscriptions + x-displayName: Subscriptions + - name: OM Invoice - API - Settings + x-displayName: Settings + - name: OM Invoice - API - Generation + x-displayName: Generation + - name: Analytics - Global + x-displayName: Global + - name: Analytics - Tracking + x-displayName: Tracking + - name: Analytics - Statistics + x-displayName: Statistics + - name: Analytics - Optimisations + x-displayName: Optimisations + - name: Analytics - Reports + x-displayName: Reports + - name: Analytics - Rules + x-displayName: Rules + - name: Channel Catalogs - Legacy Tracking - Global + x-displayName: Global +paths: + /v2/public/security/login: + post: + tags: + - Public - Security - Security + summary: Login + description: User Login - The login will give your tokens + operationId: Login + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/loginRequest' + required: true + responses: + '200': + description: Your tokens + content: + application/json: + schema: + $ref: '#/components/schemas/apiCredentials' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '403': + description: Invalid credentials + content: {} + '500': + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/public/security/register: + post: + tags: + - Public - Security - Security + summary: User Registration + description: User Registration - Create a new user on BeezUP + operationId: Register + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/registerRequest' + required: true + responses: + '204': + description: Customer registered + content: {} + '400': + description: Email or password is invalid. Disposable email are refused. + content: {} + '409': + description: Email already used + content: {} + '500': + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/public/security/lostpassword: + post: + tags: + - Public - Security - Security + summary: Lost password + description: Lost password - Your password will be regenerated and sent to your email + operationId: LostPassword + requestBody: + description: Your email + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_Email' + required: true + responses: + '204': + description: New password sent + content: {} + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Email not found + content: {} + '500': + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '502': + description: Problem with SMTP service + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: email + /v2/public/channels/: + get: + tags: + - Public - Channels - Public Channels + summary: Get public channel index + description: >- + Use this operation to get the correct link to the channels and to the + list of values + operationId: GetChannelsIndex + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Channel list regrouped by country and links to list of values + content: + application/json: + schema: + $ref: '#/components/schemas/publicChannelIndex' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/public/channels/{countryIsoCode}: + get: + tags: + - Public - Channels - Public Channels + summary: The channel list for one country + operationId: GetChannels + parameters: + - name: countryIsoCode + in: path + description: > + The country iso code alpha 3 based on this: + https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3#Decoding_table \ + + To know which country are available you have to use the operation: + GetChannelsByCountry + required: true + schema: + type: string + - name: Accept-Encoding + in: header + description: >- + Allows the client to indicate whether it accepts a compressed + encoding to reduce traffic size. + required: true + style: simple + explode: false + schema: + type: array + items: + type: string + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: The channel list for one country + content: + application/json: + schema: + $ref: '#/components/schemas/publicChannelInfoList' + example: + channels: + - name: Amazon Direct FRA + homeUrl: http://www.amazon.fr + logoUrl: >- + http://beezupcdn.blob.core.windows.net/comparators/Amazon%2520Direct%2520FRA.png + types: + - Marketplace + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Channel country not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/public/lov/: + get: + tags: + - Public - List of Values - LOV + summary: Get all list names + operationId: GetPublicLovIndex + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Get the list names + headers: + Cache-Control: + description: > + Indicates the directive around the caching mechanisms.\ + + For more information, please go to this link: + https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + schema: + type: array + items: + type: string + ETag: + description: The ETag corresponding to the LOV Index + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/publicLovIndex' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you can keep your version. + headers: + Cache-Control: + description: > + Indicates the directive around the caching mechanisms.\ + + For more information, please go to this link: + https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + schema: + type: array + items: + type: string + ETag: + description: The ETag corresponding to the LOV Index + schema: + type: string + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + # /v2/public/lov/{listName}: + # get: + # tags: + # - Public - List of Values - LOV + # summary: Get the list of values related to this list name + # operationId: GetPublicListOfValues + # parameters: + # - name: listName + # in: path + # description: The list of value name your want to get + # required: true + # schema: + # type: string + # - name: Accept-Language + # in: header + # description: Indicates that the client accepts the following languages. + # style: simple + # explode: false + # schema: + # type: array + # items: + # type: string + # - name: If-None-Match + # in: header + # description: > + # ETag value to identify the last known version of requested + # resource.\ + + # To avoid useless exchange, we recommend you to indicate the ETag you + # previously got from this operation.\ + + # If the ETag value does not match the response will be 200 to give + # you a new content, otherwise the response will be: 304 Not Modified, + # without any content.\ + + # For more details go to this link: + # http://tools.ietf.org/html/rfc7232#section-2.3 + # schema: + # type: string + # responses: + # '200': + # description: The list of values + # headers: + # Cache-Control: + # description: > + # Indicates the directive around the caching mechanisms.\ + + # For more information, please go to this link: + # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + # schema: + # type: array + # items: + # type: string + # ETag: + # description: The ETag corresponding to the LOV Index + # schema: + # type: string + # Content-Language: + # description: Indicates the language use in the response + # schema: + # type: array + # items: + # type: string + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/publicListOfValuesResponse' + # '304': + # description: >- + # The ETag sent in the http header If-None-Match did not change. So + # you can keep your version. + # headers: + # Cache-Control: + # description: > + # Indicates the directive around the caching mechanisms.\ + + # For more information, please go to this link: + # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + # schema: + # type: array + # items: + # type: string + # ETag: + # description: The ETag corresponding to the LOV Index + # schema: + # type: string + # content: {} + # '404': + # description: List not found + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + # default: + # description: Occurs when something goes wrong + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/lov/: + get: + tags: + - User - List of Values - LOV + summary: Get all list names + operationId: GetUserLovIndex + responses: + '200': + description: Get the list names + headers: + Cache-Control: + description: > + Indicates the directive around the caching mechanisms.\ + + For more information, please go to this link: + https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + schema: + type: array + items: + type: string + ETag: + description: The ETag corresponding to the LOV Index + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/userLovIndex' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you can keep your version. + headers: + Cache-Control: + description: > + Indicates the directive around the caching mechanisms.\ + + For more information, please go to this link: + https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + schema: + type: array + items: + type: string + ETag: + description: The ETag corresponding to the LOV Index + schema: + type: string + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + # /v2/user/lov/{listName}: + # get: + # tags: + # - User - List of Values - LOV + # summary: Get the list of values related to this list name + # operationId: GetUserListOfValues + # parameters: + # - name: listName + # in: path + # description: The list of value name your want to get + # required: true + # schema: + # type: string + # - name: Accept-Language + # in: header + # description: Indicates that the client accepts the following languages. + # style: simple + # explode: false + # schema: + # type: array + # items: + # type: string + # - name: If-None-Match + # in: header + # description: > + # ETag value to identify the last known version of requested + # resource.\ + + # To avoid useless exchange, we recommend you to indicate the ETag you + # previously got from this operation.\ + + # If the ETag value does not match the response will be 200 to give + # you a new content, otherwise the response will be: 304 Not Modified, + # without any content.\ + + # For more details go to this link: + # http://tools.ietf.org/html/rfc7232#section-2.3 + # schema: + # type: string + # responses: + # '200': + # description: The list of values + # headers: + # Cache-Control: + # description: > + # Indicates the directive around the caching mechanisms.\ + + # For more information, please go to this link: + # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + # schema: + # type: array + # items: + # type: string + # ETag: + # description: The ETag corresponding to the LOV Index + # schema: + # type: string + # Content-Language: + # description: Indicates the language use in the response + # schema: + # type: array + # items: + # type: string + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/userListOfValuesResponse' + # '304': + # description: >- + # The ETag sent in the http header If-None-Match did not change. So + # you can keep your version. + # headers: + # Cache-Control: + # description: > + # Indicates the directive around the caching mechanisms.\ + + # For more information, please go to this link: + # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + # schema: + # type: array + # items: + # type: string + # ETag: + # description: The ETag corresponding to the LOV Index + # schema: + # type: string + # content: {} + # '404': + # description: List not found + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + # default: + # description: Occurs when something goes wrong + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/: + get: + tags: + - Customer - Global + summary: The index of all operations and LOV + operationId: GetCustomerIndex + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/customerIndex' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/account: + get: + tags: + - Customer - Account + summary: Get user account information + operationId: GetUserAccountInfo + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: User account information + content: + application/json: + schema: + $ref: '#/components/schemas/accountInfo' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/account/resendEmailActivation: + post: + tags: + - Customer - Account + summary: Resend email activation + operationId: ResendEmailActivation + responses: + '204': + description: Email activation resent + content: {} + '400': + description: >- + Email activation not sent because of email problem. Ensure that your + email is the correct one. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Email activation not available because user account already + activated. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '429': + description: Email activation sent recently, must retry later. (One per hour) + headers: + Retry-After: + description: The duration in second to wait before making another request + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '502': + description: >- + Email activate send failed because of our email service. Ensure that + your email is the correct one otherwise please contact our support + if the problem persists. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/account/activate: + post: + tags: + - Customer - Account + summary: Activate the user account + operationId: ActivateUserAccount + requestBody: + description: The email activation id received by email. + content: + application/json: + schema: + type: string + format: guid + required: true + responses: + '204': + description: User account activated. + content: {} + '403': + description: Invalid email activation id + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: User account already activated. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: emailActivationId + /v2/user/customer/account/personalInfo: + put: + tags: + - Customer - Account + summary: Save user personal information + operationId: SavePersonalInfo + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/personalInfo' + required: true + responses: + '204': + description: User account information updated + content: {} + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/account/companyInfo: + put: + tags: + - Customer - Account + summary: Change company information + operationId: SaveCompanyInfo + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/companyInfo' + required: true + responses: + '204': + description: Company information saved + content: {} + '400': + description: Bad request or invalid VATNumber. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '403': + description: User not found or unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/account/profilePictureInfo: + get: + tags: + - Customer - Account + summary: Get profile picture information + operationId: GetProfilePictureInfo + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Profile picture information + content: + application/json: + schema: + $ref: '#/components/schemas/profilePictureInfoResponse' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - Customer - Account + summary: Change user picture information + operationId: SaveProfilePictureInfo + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/profilePictureInfo' + required: true + responses: + '204': + description: User profile picture information saved. + content: {} + '400': + description: BadRequest (Url invalid) + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '413': + description: The picture size is too large + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '415': + description: The content type of the image must be an image + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/account/creditCardInfo: + get: + tags: + - Customer - Account + summary: Get credit card information + operationId: GetCreditCardInfo + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: User credit card information + content: + application/json: + schema: + $ref: '#/components/schemas/creditCardInfoResponse' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Credit Card not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '503': + description: >- + We are unable to get your credit card info. This is a temporary + state. Please retry later + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - Customer - Account + summary: Save user credit card info + operationId: SaveCreditCardInfo + requestBody: + description: Credit card info + content: + application/json: + schema: + $ref: '#/components/schemas/creditCardInfo' + required: true + responses: + '202': + description: >- + The credit card information has been accepted for processing, the + authorization will be processed shortly. + content: {} + '400': + description: BadRequest + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '502': + description: Communication problem with our payment service + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/account/changeEmail: + post: + tags: + - Customer - Account + summary: Change user email + operationId: ChangeEmail + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeEmailRequest' + required: true + responses: + '204': + description: Email updated + content: {} + '400': + description: New email does not respect the emails's constraints + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/account/changePassword: + post: + tags: + - Customer - Account + summary: Change user password + operationId: ChangePassword + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changePasswordRequest' + required: true + responses: + '204': + description: Password updated + content: {} + '400': + description: >- + Old password is invalid or the new password does not respect the + password's constraints + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/security/logout: + post: + tags: + - Customer - Security + summary: Log out the current user from go2 + description: Log out the current user from go2 + operationId: Logout + responses: + '204': + description: User logout + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/zendeskToken: + get: + tags: + - Customer - Security + summary: Zendesk token + description: >- + Zendesk token - Generates a JWT token to access BeezUP restricted Help + Center in SSO as described here: + https://support.zendesk.com/hc/en-us/articles/222874768-Using-restricted-Help-Center-content-with-the-Web-Widget + operationId: ZendeskToken + responses: + '200': + description: A JWT token to connect the Zendesk Web Widget + content: + application/json: + schema: + $ref: '#/components/schemas/zendeskToken' + '500': + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/stores: + get: + tags: + - Customer - Stores + summary: Get store list + operationId: GetStores + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Store list + content: + application/json: + schema: + $ref: '#/components/schemas/storeList' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Customer - Stores + summary: Create a new store + operationId: CreateStore + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/createStoreRequest' + required: true + responses: + '201': + description: >- + The store has been created successfully. The http header Location + contains the new resource url. The body contains the link to the new + resource. + content: + application/json: + schema: + $ref: '#/components/schemas/links.getStoreLink' + '402': + description: >- + The maximum amount of store has been reached. Please upgrade your + contract. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessagePaymentRequired' + '409': + description: The customer has a store with the same name + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/stores/{storeId}: + get: + tags: + - Customer - Stores + summary: Get store's information + operationId: GetStore + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: The store information + content: + application/json: + schema: + $ref: '#/components/schemas/store' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Store not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + delete: + tags: + - Customer - Stores + summary: Delete a store + operationId: DeleteStore + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Store deleted + content: {} + '404': + description: Store not found or customer not the owner + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + patch: + tags: + - Customer - Stores + summary: Update some store's information. + description: | + Update some store's information. FYI, you cannot change the country. + operationId: UpdateStore + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/updateStoreRequest' + required: true + responses: + '204': + description: Store updated + content: {} + '404': + description: Store not found or customer not the owner + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: The store name already used + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/stores/{storeId}/rights: + get: + tags: + - Customer - Rights + summary: Get store's rights + operationId: GetRights + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: The store's rights + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/functionalityRightInfo' + '404': + description: Store not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/stores/{storeId}/alerts: + get: + tags: + - Customer - Alerts + summary: Get store's alerts + operationId: GetStoreAlerts + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: User account alerts information + content: + application/json: + schema: + $ref: '#/components/schemas/storeAlerts' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Store not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Customer - Alerts + summary: Save store alerts + description: >- + You just have to send the alert you want to update, does not need all + alerts. (PARTIAL UPDATE ACCEPTED) + operationId: SaveStoreAlerts + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/saveStoreAlertsRequest' + required: true + responses: + '204': + description: Store alerts saved + content: {} + '400': + description: BadRequest + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/stores/{storeId}/shares: + get: + tags: + - Customer - Shares + summary: Get shares related to this store + operationId: GetStoreShares + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: The sharing list of the store + content: + application/json: + schema: + $ref: '#/components/schemas/storeShares' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Store not found or customer not the owner + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Customer - Shares + summary: Share a store to another user + operationId: ShareStore + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + description: Your friend's email + content: + application/json: + schema: + $ref: '#/components/schemas/friendEmail' + required: true + responses: + '204': + description: Store shared + content: {} + '402': + description: Free offer is not allowed to share store. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessagePaymentRequired' + '404': + description: >- + Only the owner of the store can make this operation or user not + found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: email + /v2/user/customer/stores/{storeId}/shares/{userId}: + delete: + tags: + - Customer - Shares + summary: Delete a share of a store to another user + operationId: DeleteStoreShare + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: userId + in: path + description: The friend user id + required: true + schema: + type: string + format: guid + responses: + '204': + description: Share deleted + content: {} + '404': + description: Store not found or customer not the owner + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/friends/{userId}: + get: + tags: + - Customer - Friends + summary: Get friend information + operationId: GetFriendInfo + parameters: + - name: userId + in: path + description: Your friend user id + required: true + schema: + type: string + format: guid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Get friend info + content: + application/json: + schema: + $ref: '#/components/schemas/userFriendInfo' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: User not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/billingPeriods: + get: + tags: + - Customer - Contracts + summary: Get billing periods conditions + operationId: GetBillingPeriods + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Get the billing periods conditions + content: + application/json: + schema: + $ref: '#/components/schemas/billingPeriodList' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/offers: + get: + tags: + - Customer - Contracts + summary: Get all standard offers + operationId: GetStandardOffers + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Get all standard offers + content: + application/json: + schema: + $ref: '#/components/schemas/standardOffers' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Customer - Contracts + summary: Get offer pricing + description: > + Get the offer pricing then you can create your contract with the same + request parameters. /v2/user/customer/contracts + operationId: GetOffer + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/offerRequest' + required: true + responses: + '200': + description: Get the offer proposal considering your current contract + content: + application/json: + schema: + $ref: '#/components/schemas/offer' + '400': + description: >- + Bad request. (Invalid billing period, invalid offer, etc.). You + cannot get a pricing for a free offer. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '403': + description: You current contract is not modifiable. Please choose another offer. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/contracts: + get: + tags: + - Customer - Contracts + summary: Get contract list + operationId: GetContracts + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Contract list + content: + application/json: + schema: + $ref: '#/components/schemas/contracts' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Customer - Contracts + summary: Create a new contract + description: > + Now you are ready to create your contract. Before that, please ensure + that you check the offer with the same request parameterts. /offers + operationId: CreateContract + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/createContract' + required: true + responses: + '200': + description: >- + New contract has been created. Some warnings can be present in + response. + content: + application/json: + schema: + $ref: '#/components/schemas/createContractResponse' + '400': + description: Bad request. (Invalid billing period, invalid offer, etc.) + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '403': + description: >- + The contract is not modifiable or the coupon offer has been already + used + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/contracts/current/disableAutoRenewal: + post: + tags: + - Customer - Contracts + summary: >- + Schedule termination of your current contract at the end of the + commitment. + description: >- + By default your contract are automatically renew. By calling this + operation you can disable the auto renewal. + operationId: TerminateCurrentContract + requestBody: + description: Indicate the termination reason + content: + application/json: + schema: + $ref: '#/components/schemas/terminateContract' + required: true + responses: + '204': + description: Your current contract termination has been scheduled + content: {} + '400': + description: Invalid reason type + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: No current contract + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/customer/contracts/current/reenableAutoRenewal: + post: + tags: + - Customer - Contracts + summary: Reactivate your terminated contract. + description: By calling this operation you can re-enable the auto renewal. + operationId: ReactivateCurrentContract + responses: + '204': + description: Your current contract has been resumed + content: {} + '404': + description: No current contract + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/contracts/next: + delete: + tags: + - Customer - Contracts + summary: Delete your next contract + operationId: DeleteNextContract + responses: + '204': + description: Next contract has been deleted + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/customer/invoices: + get: + tags: + - Customer - Invoices + summary: Get all your invoices + operationId: GetInvoices + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Get all invoices of a customer + content: + application/json: + schema: + $ref: '#/components/schemas/invoiceList' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/: + get: + tags: + - Catalogs - Global + summary: Get the index of the catalog API + description: >- + The operation will give you all the operations you will be able to do + and all the LOV used in this API. + operationId: CatalogIndex + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/catalogIndex' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/beezupColumns: + get: + tags: + - Catalogs - Global + summary: Get the BeezUP columns + description: >- + Get the BeezUP columns, this columns are used for mapping during the + manual catalog importation process. + operationId: Catalog_GetBeezUPColumns + responses: + '200': + description: The catalog API index + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/beezUPColumnConfiguration' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}: + get: + tags: + - Catalogs - Catalog + summary: Get the index of the catalog API for this store + description: >- + The operation will give you all the operations you will be able to do on + this store for this API. + operationId: CatalogStoreIndex + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: The catalog index + content: + application/json: + schema: + $ref: '#/components/schemas/catalogStoreIndex' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/inputConfiguration: + get: + tags: + - Catalogs - Catalog + summary: Get the last input configuration + operationId: Importation_GetManualUpdateLastInputConfig + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/lastManualImportInputConfiguration' + '404': + description: StoreId or Manual Update last configuration not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/catalogColumns: + get: + tags: + - Catalogs - Catalog + summary: Get catalog column list + operationId: Catalog_GetCatalogColumns + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Catalog column list + content: + application/json: + schema: + $ref: '#/components/schemas/catalogColumnList' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/catalogColumns/{columnId}/rename: + post: + tags: + - Catalogs - Catalog + summary: Change Catalog Column User Name + operationId: Catalog_ChangeCatalogColumnUserName + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The catalog column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeUserColumnNameRequest' + required: true + responses: + '204': + description: Catalog column user name changed + content: {} + '400': + description: When a user column name is duplicate. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: A catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/importAlreadyInProgressResponse' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/customColumns: + get: + tags: + - Catalogs - Catalog + summary: Get custom column list + operationId: Catalog_GetCustomColumns + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Custom column list + content: + application/json: + schema: + $ref: '#/components/schemas/customColumnList' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/customColumns/{columnId}: + put: + tags: + - Catalogs - Catalog + summary: Create or replace a custom column + operationId: Catalog_SaveCustomColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/createCustomColumnRequest' + required: true + responses: + '204': + description: Custom column saved + content: {} + '400': + description: >- + Occurs when a catalog custom column id is already used by a catalog + column. + + When the catalog custom column count limit has been reached. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: {} + '409': + description: A catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/importAlreadyInProgressResponse' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + delete: + tags: + - Catalogs - Catalog + summary: Delete custom column + operationId: Catalog_DeleteCustomColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Custom column deleted + content: {} + '403': + description: Occurs when the parent category is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: When a catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/customColumns/{columnId}/rename: + post: + tags: + - Catalogs - Catalog + summary: Change Custom Column User Name + operationId: Catalog_ChangeCustomColumnUserName + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeUserColumnNameRequest' + required: true + responses: + '204': + description: Custom column renamed + content: {} + '400': + description: When a user column name is duplicate. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: A catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/importAlreadyInProgressResponse' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/customColumns/{columnId}/expression: + get: + tags: + - Catalogs - Catalog + summary: Get the encrypted custom column expression + operationId: Catalog_GetCustomColumnExpression + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Encrypted expression + content: + application/json: + schema: + type: string + example: zlkzjkzjlzlknzklnzlknaklnaklanlknaklan + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when a catalog custom column is not found. + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - Catalogs - Catalog + summary: Change custom column expression + operationId: Catalog_ChangeCustomColumnExpression + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeCustomColumnExpressionRequest' + required: true + responses: + '204': + description: Custom column expression saved + content: {} + '403': + description: >- + Occurs when the user try to change a custom column related to a + Category. If you want to change this custom column expression you + have to make a new manual importation. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when a catalog custom column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: A catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/importAlreadyInProgressResponse' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/customColumns/computeExpression: + post: + tags: + - Catalogs - Catalog + summary: Compute the expression for this catalog. + operationId: Catalog_ComputeExpression + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/computeExpressionRequest' + required: true + responses: + '200': + description: Compute an expression + content: + application/json: + schema: + type: string + '400': + description: Occurs when the expression cannot be computed + content: + application/json: + schema: + type: string + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/categories: + get: + tags: + - Catalogs - Catalog + summary: Get category list + operationId: Catalog_GetCategories + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: Accept-Encoding + in: header + description: >- + Indicates that the client accepts that the response will be + compressed to reduce traffic size. + required: true + style: simple + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Categories + headers: + Content-Encoding: + description: Indicates the compression use in the response + schema: + type: array + items: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/categoryList' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/products/list: + post: + tags: + - Catalogs - Catalog + summary: Get product list + operationId: Catalog_GetProducts + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/getProductsRequest' + required: true + responses: + '200': + description: Product list + content: + application/json: + schema: + $ref: '#/components/schemas/productList' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/products/random: + get: + tags: + - Catalogs - Catalog + summary: Get random product list + description: We will return 10 products randomly selected with all product values + operationId: Catalog_GetRandomProducts + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Random product list + content: + application/json: + schema: + $ref: '#/components/schemas/randomProductList' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/products/{productId}: + get: + tags: + - Catalogs - Catalog + summary: Get product by ProductId + operationId: Catalog_GetProductByProductId + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier you want to get + required: true + schema: + type: string + format: guid + responses: + '200': + description: Product + content: + application/json: + schema: + $ref: '#/components/schemas/product' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/products: + get: + tags: + - Catalogs - Catalog + summary: Get product by Sku + operationId: Catalog_GetProductBySku + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: sku + in: query + description: The product sku you want to get + required: true + schema: + type: string + responses: + '200': + description: Product + content: + application/json: + schema: + $ref: '#/components/schemas/product' + '404': + description: StoreId or Product not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/importations: + get: + tags: + - Catalogs - Importation Process + summary: Get the latest catalog importation reporting for all your stores + operationId: Importation_GetReportingsAllStores + responses: + '200': + description: The last importation reportings + content: + application/json: + schema: + $ref: '#/components/schemas/importationsPerStoreResponse' + '404': + description: UserId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations: + get: + tags: + - Catalogs - Importation Process + summary: Get the latest catalog importation reporting + operationId: Importation_GetReportings + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: The last importation reportings + content: + application/json: + schema: + $ref: '#/components/schemas/importationsResponse' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/start: + post: + tags: + - Catalogs - Importation Process + summary: Start Manual Import + operationId: Importation_StartManualUpdate + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/startManualImportRequest' + required: true + responses: + '202': + description: Catalog importation started + headers: + Retry-After: + description: The duration in second to wait before polling this resource + schema: + minimum: 5 + type: integer + Location: + description: The location of the new resource to poll + schema: + type: string + content: + application/json: + schema: + $ref: >- + #/components/schemas/links.Importation_GetImportationMonitoringLink + '400': + description: >- + Missing Input configuration in the request + + Occurs when there is a duplicate file number in the input + configuration + + Occurs when there is a duplicate file Uri in the input configuration + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: StoreId not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: A catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/importAlreadyInProgressResponse' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/importations/{executionId}: + get: + tags: + - Catalogs - Importation Process + summary: Get the importation status + operationId: Importation_GetImportationMonitoring + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/importationMonitoring' + '404': + description: >- + ExecutionId not found or not yet synchronized. If not synchronized + within 30 sec after the import has been started, please contact our + support + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/cancel: + post: + tags: + - Catalogs - Importation Process + summary: Cancel importation + operationId: Importation_Cancel + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '204': + description: Catalog importation canceled + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/technicalProgression: + get: + tags: + - Catalogs - Importation Process + summary: Get technical progression + operationId: Importation_TechnicalProgression + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '200': + description: When the technical progression is correctly retrived + content: + application/json: + schema: + $ref: '#/components/schemas/importationTechnicalProgression' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/configureRemainingCatalogColumns: + post: + tags: + - Catalogs - Importation Process + summary: Configure remaining catalog columns + description: >- + This operation should be used after you have mapped the required BeezUP + Columns + operationId: Importation_ConfigureRemainingCatalogColumns + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '204': + description: >- + Remaining catalog columns have been configured. This operation has + no impact on the current catalog until you commit the catalog + importation. + content: {} + '400': + description: >- + When a user column name is duplicate. + + When the catalog column name are duplicate. + + When the BeezUP column have duplicate mapping. + + Occurs when the required beezup column is not mapped to any column. + + Occurs when the category hierarchy is not correctly mapped. + + Occurs when the duplicate strategy on {catalogColumnName} is not + found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/commitColumns: + post: + tags: + - Catalogs - Importation Process + summary: Commit columns + operationId: Importation_CommitColumns + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '204': + description: >- + Columns configuration have been committed. This operation has no + impact on the current catalog until you commit the catalog + importation. + content: {} + '400': + description: |- + When a user column name is duplicate. + When the catalog column name are duplicate. + When the BeezUP column have duplicate mapping. + Occurs when the required beezup column is not mapped to any column. + Occurs when the category hierarchy is not correctly mapped. + When the catalog column count limit has been reached. + When the catalog custom column count limit has been reached. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/commit: + post: + tags: + - Catalogs - Importation Process + summary: Commit Importation + operationId: Importation_Commit + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '204': + description: Catalog importation committed + content: {} + '400': + description: '' + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/productSamples/{productSampleIndex}: + get: + tags: + - Catalogs - Importation Catalog Info + summary: >- + Get the product sample related to this importation with all columns + (catalog and custom) + operationId: Importation_GetProductSample + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: productSampleIndex + in: path + description: Index of the product sample. Starting from 0 to 99. + required: true + schema: + maximum: 99 + minimum: 0 + type: integer + format: int32 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/productSample' + '404': + description: >- + ExecutionId not found or not yet synchronized. If not synchronized + within 30 sec, please contact our support + schema: + $ref: + 'https://api.beezup.com/swaggerhub/domains/BeezUP/api.beezup.com/v2#/definitions/BeezUP_Common_ErrorResponseMessage' + content: {} + '409': + description: >- + Catalog preparation read step is not completed. Please refer to the + reporting of this execution for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/productSamples/{productSampleIndex}/customColumns/{columnId}: + get: + tags: + - Catalogs - Importation Catalog Info + summary: Get product sample custom column value related to this importation. + description: >- + /!\ Use this operation only when you just changed the custom column + expression and you want to get a precise the property value. Otherwise + use the operation Importation_GetProductSample which will give you all + property values + operationId: Importation_GetProductSampleCustomColumnValue + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: productSampleIndex + in: path + description: Index of the product sample. Starting from 0 to 99. + required: true + schema: + maximum: 99 + minimum: 0 + type: integer + format: int32 + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Product sample custom column value + content: + application/json: + schema: + type: string + example: A value computed from a expression + '404': + description: >- + ExecutionId not found or not yet synchronized. If not synchronized + within 30 sec, please contact our support + headers: + Retry-After: + description: The duration in second to wait before polling this resource + schema: + minimum: 5 + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Catalog preparation read step is not completed. Please refer to the + reporting of this execution for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/catalogColumns: + get: + tags: + - Catalogs - Importation Catalog Info + summary: Get detected catalog columns during this importation. + operationId: Importation_GetDetectedCatalogColumns + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/detectedCatalogColumnList' + '404': + description: >- + ExecutionId not found or not yet synchronized. If not synchronized + within 30 sec, please contact our support + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Catalog preparation read step is not completed. Please refer to the + reporting of this execution for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/catalogColumns/{columnId}: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Configure catalog column + operationId: Importation_ConfigureCatalogColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/configureCatalogColumnCatalogRequest' + required: true + responses: + '204': + description: >- + Catalog column configured. This operation has no impact on the + current catalog until you commit the catalog importation. + content: {} + '400': + description: |- + + When the catalog column name is not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/importations/{executionId}/catalogColumns/{columnId}/ignore: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Ignore Column + operationId: Importation_IgnoreColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: >- + Catalog column ignored. This operation has no impact on the current + catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/catalogColumns/{columnId}/reattend: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Reattend Column + operationId: Importation_ReattendColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: >- + Catalog column reattended. This operation has no impact on the + current catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/catalogColumns/{columnId}/map: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Map catalog column to a BeezUP column + operationId: Importation_MapCatalogColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The catalog column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/mapBeezUPColumnRequest' + required: true + responses: + '204': + description: >- + Catalog column mapped. This operation has no impact on the current + catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/importations/{executionId}/catalogColumns/{columnId}/unmap: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Unmap catalog column + operationId: Importation_UnmapCatalogColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The catalog column identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: >- + Catalog Column unmapped. This operation has no impact on the current + catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/customColumns: + get: + tags: + - Catalogs - Importation Catalog Info + summary: Get custom columns currently place in this importation + operationId: Importation_GetCustomColumns + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '200': + description: Custom columns of current Importation successfully retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/importationCustomColumnList' + '404': + description: >- + ExecutionId not found or not yet synchronized. If not synchronized + within 30 sec, please contact our support + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Catalog preparation read step is not completed. Please refer to the + reporting of this execution for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/customColumns/{columnId}/expression: + get: + tags: + - Catalogs - Importation Catalog Info + summary: Get the encrypted custom column expression in this importation + operationId: Importation_GetCustomColumnExpression + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Encrypted expression + content: + application/json: + schema: + type: string + example: zlkzjkzjlzlknzklnzlknaklnaklanlknaklan + '404': + description: >- + ExecutionId not found or not yet synchronized. If not synchronized + within 30 sec, please contact our support + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Catalog preparation read step is not completed. Please refer to the + reporting of this execution for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/customColumns/{columnId}: + put: + tags: + - Catalogs - Importation Catalog Info + summary: Create or replace a custom column + operationId: Importation_SaveCustomColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeCustomColumnRequest' + required: true + responses: + '204': + description: >- + Custom column configured. This operation has no impact on the + current catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + delete: + tags: + - Catalogs - Importation Catalog Info + summary: Delete Custom Column + operationId: Importation_DeleteCustomColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: When the custom column for this importation is correctly deleted + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/customColumns/{columnId}/map: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Map custom column to a BeezUP column + operationId: Importation_MapCustomColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/mapBeezUPColumnRequest' + required: true + responses: + '204': + description: >- + Custom column mapped. This operation has no impact on the current + catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/importations/{executionId}/customColumns/{columnId}/unmap: + post: + tags: + - Catalogs - Importation Catalog Info + summary: Unmap custom column + operationId: Importation_UnmapCustomColumn + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + - name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: >- + Custom column unmapped. This operation has no impact on the current + catalog until you commit the catalog importation. + content: {} + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + Occurs when a catalog column is not found. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Occurs when this importation is already finished. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/importations/{executionId}/products/list: + post: + tags: + - Catalogs - Importation Process + summary: Importation Get Products Report + operationId: Importation_GetProductsReport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/getImportationProductsReportRequest' + required: true + responses: + '200': + description: Get Products Report Response + content: + application/json: + schema: + $ref: '#/components/schemas/getImportationProductsReportResponse' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: {} + '409': + description: Report Not ready Yet. Please retry in a few minutes. + content: {} + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/importations/{executionId}/report: + get: + tags: + - Catalogs - Importation Process + summary: Importation Get Report + operationId: Importation_GetReport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + responses: + '200': + description: Get Report Response + content: + application/json: + schema: + $ref: '#/components/schemas/getImportationReportResponse' + '404': + description: |- + Occurs when a user tries to work on the wrong store. + Occurs when the message concerns the wrong execution. + content: {} + '409': + description: Report Not ready Yet. Please retry in a few minutes. + content: {} + /v2/user/catalogs/{storeId}/autoImport/activate: + post: + tags: + - Catalogs - Auto + summary: >- + Activate the auto importation of the last successful manual catalog + importation. + description: >- + Once you have made your fist manual catalog importation with success, + you can call this operation to import it automatically. No parameter + required, we know which one it is. + operationId: Importation_ActivateAutoImport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Auto import activated + content: {} + '400': + description: Occurs when the user tries to auto import a local file. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: When a catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/autoImport: + get: + tags: + - Catalogs - Auto + summary: Get the auto import configuration + operationId: Auto_GetAutoImportConfiguration + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Auto import configuration + content: + application/json: + schema: + $ref: '#/components/schemas/autoImportConfiguration' + '404': + description: StoreId or Auto Import configuration not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + delete: + tags: + - Catalogs - Auto + summary: Delete Auto Import + operationId: Auto_DeleteAutoImport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Auto import deleted + content: {} + '400': + description: Occurs when the catalog auto import is not configured. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/autoImport/start: + post: + tags: + - Catalogs - Auto + summary: Start Auto Import Manually + operationId: Auto_StartAutoImport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '202': + description: Catalog importation started + headers: + Retry-After: + description: The duration in second to wait before polling this resource + schema: + minimum: 5 + type: integer + Location: + description: The location of the new resource to poll + schema: + type: string + content: + application/json: + schema: + $ref: >- + #/components/schemas/links.Importation_GetImportationMonitoringLink + '400': + description: >- + Occurs when the catalog auto import is not configured. + + When a user column name is duplicate. + + When the catalog column name are duplicate. + + When the BeezUP column have duplicate mapping. + + Occurs when the required beezup column is not mapped to any column. + + Occurs when the category hierarchy is not correctly mapped. + + Occurs when the duplicate strategy on {catalogColumnName} is not + found. + + When the user tries to import to ofen the catalog file to download + count max limit has been reached. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: An importation is already in progress + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/autoImport/pause: + post: + tags: + - Catalogs - Auto + summary: Pause Auto Import + operationId: Auto_PauseAutoImport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Auto import paused + content: {} + '400': + description: Occurs when the catalog auto import is not configured. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/autoImport/resume: + post: + tags: + - Catalogs - Auto + summary: Resume Auto Import + operationId: Auto_ResumeAutoImport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Auto import resumed + content: {} + '400': + description: Occurs when the catalog auto import is not configured. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/catalogs/{storeId}/autoImport/scheduling/interval: + post: + tags: + - Catalogs - Auto + summary: Configure Auto Import Interval + operationId: Auto_ConfigureAutoImportInterval + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/configureAutoImportIntervalRequest' + required: true + responses: + '204': + description: Auto import scheduling interval saved + content: {} + '400': + description: >- + + When the min catalog Auto Import scheduling interval delay has been + reached. + + When the max catalog Auto Import count has been reached. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/catalogs/{storeId}/autoImport/scheduling/schedules: + post: + tags: + - Catalogs - Auto + summary: Configure Auto Import Schedules + operationId: Auto_ScheduleAutoImport + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/scheduleAutoImportRequest' + required: true + responses: + '204': + description: Auto import scheduling saved + content: {} + '400': + description: >- + + When the max catalog Auto Import count has been reached. + + When the min catalog Auto Import scheduling interval delay has been + reached. + + When the max catalog Auto Import count has been reached. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Occurs when a user tries to work on the wrong store. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channels/: + get: + tags: + - Channels - Channels Global + summary: List all available channel for this store + operationId: GetAvailableChannels + parameters: + - name: storeId + in: query + description: The store identifier + required: true + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + responses: + '200': + description: Available channel list for this store + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/channelHeader' + /v2/user/channels/{channelId}: + get: + tags: + - Channels - Channels Global + summary: Get channel information + operationId: GetChannelInfo + parameters: + - name: channelId + in: path + description: The channel identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel information + content: + application/json: + schema: + $ref: '#/components/schemas/channelInfo' + /v2/user/channels/{channelId}/categories: + get: + tags: + - Channels - Channels Global + summary: Get channel categories + operationId: GetChannelCategories + parameters: + - name: channelId + in: path + description: The channel identifier + required: true + schema: + type: string + format: guid + - name: Accept-Encoding + in: header + description: >- + Indicates that the client accepts that the response will be + compressed to reduce traffic size. + required: true + style: simple + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Channel categories + headers: + Content-Encoding: + description: Indicates the compression use in the response + schema: + type: array + items: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/channelRootCategory' + /v2/user/channels/{channelId}/columns: + post: + tags: + - Channels - Channels Global + summary: Get channel columns + operationId: GetChannelColumns + parameters: + - name: channelId + in: path + description: The channel identifier + required: true + schema: + type: string + format: guid + - name: Accept-Encoding + in: header + description: >- + Indicates that the client accepts that the response will be + compressed to reduce traffic size. + required: true + style: simple + explode: false + schema: + type: array + items: + type: string + requestBody: + description: >- + Allow you to filter the channel column identifier list your want to + get + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnId' + required: false + responses: + '200': + description: Channel columns + headers: + Content-Encoding: + description: Indicates the compression use in the response + schema: + type: array + items: + type: string + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/channelColumn' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/: + get: + tags: + - Channel Catalogs - Global + summary: List all your current channel catalogs + operationId: GetChannelCatalogs + parameters: + - name: storeId + in: query + description: The store identifier + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogList' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Channel Catalogs - Global + summary: Add a new channel catalog + operationId: AddChannelCatalog + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/addChannelCatalogRequest' + required: true + responses: + '201': + description: When the channel has been successfully added for this store + headers: + Retry-After: + description: The duration in second to wait before polling this resource + schema: + minimum: 5 + type: integer + Location: + description: The new location + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/links.GetChannelCatalogLink' + '404': + description: StoreId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}: + get: + tags: + - Channel Catalogs - Global + summary: Get the channel catalog information + operationId: GetChannelCatalog + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalog' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + delete: + tags: + - Channel Catalogs - Global + summary: Delete the channel catalog + operationId: DeleteChannelCatalog + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog deleted + content: {} + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/filterOperators: + get: + tags: + - Channel Catalogs - Global + summary: Get channel catalog filter operators + operationId: GetChannelCatalogFilterOperators + responses: + '200': + description: Channel catalog filter operator list + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/filterOperator' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/enable: + post: + tags: + - Channel Catalogs - Settings + summary: Enable a channel catalog + operationId: EnableChannelCatalog + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog enabled + content: {} + '402': + description: You have to upgrade your offer to activate this channel catalog + content: + application/json: + schema: + $ref: '#/components/schemas/upgradeOfferRequired' + '404': + description: Occurs when a user tries to work on the wrong ChanelCatalogId. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/disable: + post: + tags: + - Channel Catalogs - Settings + summary: Disable a channel catalog + operationId: DisableChannelCatalog + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog disabled + content: {} + '404': + description: Occurs when a user tries to work on the wrong ChanelCatalogId. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/settings/general: + put: + tags: + - Channel Catalogs - Settings + summary: Configure channel catalog general settings + operationId: ConfigureChannelCatalogGeneralSettings + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/generalSettings' + required: true + responses: + '204': + description: Channel catalog general settings configured + content: {} + '404': + description: Occurs when a user tries to work on the wrong ChanelCatalogId. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/settings/cost: + put: + tags: + - Channel Catalogs - Settings + summary: Configure channel catalog cost settings + operationId: ConfigureChannelCatalogCostSettings + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/costSettings' + required: true + responses: + '204': + description: Channel catalog cost settings configured + content: {} + '404': + description: Occurs when a user tries to work on the wrong ChanelCatalogId. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/columnMappings: + put: + tags: + - Channel Catalogs - Column Mappings + summary: Configure channel catalog column mappings + operationId: ConfigureChannelCatalogColumnMappings + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogColumnMappingList' + required: true + responses: + '204': + description: Channel catalog column mappings configured + content: {} + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/categories: + get: + tags: + - Channel Catalogs - Categories + summary: Get channel catalog categories + operationId: GetChannelCatalogCategories + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog category mappings + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogCategoryConfigurationList' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/categories/disableMapping: + post: + tags: + - Channel Catalogs - Categories + summary: Disable a channel catalog category mapping + operationId: DisableChannelCatalogCategoryMapping + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog category mapping disabled + content: {} + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/categories/reenableMapping: + post: + tags: + - Channel Catalogs - Categories + summary: Reenable a channel catalog category mapping + operationId: ReenableChannelCatalogCategoryMapping + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog category mapping reenabled + content: {} + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/categories/configure: + post: + tags: + - Channel Catalogs - Categories + summary: Configure channel catalog category + operationId: ConfigureChannelCatalogCategory + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/configureCategoryRequest' + required: true + responses: + '204': + description: Channel catalog category configured + content: {} + '400': + description: BadRequest. See Error Response for more details + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/exclusionFilters: + get: + tags: + - Channel Catalogs - Exclusion Filters + summary: Get channel catalog exclusion filters + operationId: GetChannelCatalogExclusionFilters + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog exclusion filter list + content: + application/json: + schema: + $ref: '#/components/schemas/exclusionFiltersResponse' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - Channel Catalogs - Exclusion Filters + summary: Configure channel catalog exclusion filters + operationId: ConfigureChannelCatalogExclusionFilters + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/exclusionFilters' + required: true + responses: + '204': + description: Channel catalog exclusion filter list configured + content: {} + '400': + description: BadRequest. See Error Response for more details + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/products: + post: + tags: + - Channel Catalogs - Products + summary: Get channel catalog product information list + operationId: GetChannelCatalogProductInfoList + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + requestBody: + description: The channel catalog product list filter + content: + application/json: + schema: + $ref: '#/components/schemas/getChannelCatalogProductInfoListRequest' + required: true + responses: + '200': + description: Channel catalog product information + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogProductInfoList' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/products/export: + post: + tags: + - Channel Catalogs - Products + summary: Export channel catalog product information list + operationId: ExportChannelCatalogProductInfoList + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: format + in: query + description: The file type of the exportation + required: true + schema: + type: string + enum: + - xlsx + - csv + requestBody: + description: The channel catalog product list filter + content: + application/json: + schema: + $ref: '#/components/schemas/getChannelCatalogProductInfoListRequest' + required: true + responses: + '200': + description: Channel catalog product information list exported + headers: + Location: + description: > + To indicate the url of the export file + + Example: + https://beezupchannel.blob.core.windows.net/reports/exports/Excel_Products.xslx + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_Link3' + example: + href: >- + https://beezupchannel.blob.core.windows.net/reports/exports/Excel_Products.xslx + method: GET + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/products/counters: + get: + tags: + - Channel Catalogs - Products + summary: Get channel catalog products' counters + operationId: GetChannelCatalogProductsCounters + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog products' counters + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogProductsCounters' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/products: + post: + tags: + - Channel Catalogs - Products + summary: Get channel catalog products related to these channel catalogs + operationId: GetChannelCatalogProductByChannelCatalog + requestBody: + content: + application/json: + schema: + $ref: >- + #/components/schemas/channelCatalogProductByChannelCatalogRequest + required: true + responses: + '200': + description: The channel catalog product by channel catalog + content: + application/json: + schema: + $ref: >- + #/components/schemas/channelCatalogProductByChannelCatalogResponse + '404': + description: ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/products/{productId}: + get: + tags: + - Channel Catalogs - Products + summary: Get channel catalog product information + operationId: GetChannelCatalogProductInfo + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog product information + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogProductInfo' + '404': + description: ChannelCatalog or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/products/{productId}/overrides: + put: + tags: + - Channel Catalogs - Products Overrides + summary: Override channel catalog product values + operationId: OverrideChannelCatalogProductValues + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/productOverrides' + required: true + responses: + '204': + description: Channel catalog product overriden + content: {} + '400': + description: BadRequest. See Error Response for more details + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: ChannelCatalogId or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/channelCatalogs/{channelCatalogId}/products/{productId}/overrides/{channelColumnId}: + delete: + tags: + - Channel Catalogs - Products Overrides + summary: Delete a specific channel catalog product value override + operationId: DeleteChannelCatalogProductValueOverride + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + - name: channelColumnId + in: path + description: The channel column identifier + required: true + schema: + type: string + format: guid + example: 8a76f06a-fefc-4c0d-bcfe-b210f1482977 + responses: + '204': + description: Channel catalog product value override deleted + content: {} + '404': + description: ChannelCatalogId or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/products/{productId}/overrides/copy: + get: + tags: + - Channel Catalogs - Products Overrides + summary: Get channel catalog product value override compatibilities status + operationId: GetChannelCatalogProductValueOverrideCopy + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: placeholder. will be completed soon. + content: {} + '404': + description: ChannelCatalog or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Channel Catalogs - Products Overrides + summary: Copy channel catalog product value override + operationId: ConfigureChannelCatalogProductValueOverrideCopy + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog product value override deleted + content: {} + '404': + description: ChannelCatalogId or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/products/{productId}/disable: + post: + tags: + - Channel Catalogs - Products Optimisation + summary: Disable channel catalog product + description: > + By default a all your catalog products are exposed to the channel. + + You can disable a product by using this operation. + + /!\ In case of massive optimisation we recommand you to use the + analytics api + operationId: DisableChannelCatalogProduct + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog product disabled + content: {} + '404': + description: ChannelCatalogId Or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/products/{productId}/reenable: + post: + tags: + - Channel Catalogs - Products Optimisation + summary: Reenable channel catalog product + description: > + By default a all your catalog products are exposed to the channel. + + You can reenable a product by using this operation. + + /!\ In case of massive optimisation we recommand you to use the + analytics api + operationId: ReenableChannelCatalogProduct + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog product reenabled + content: {} + '404': + description: ChannelCatalogId or ProductId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/exportations/cache: + get: + tags: + - Channel Catalogs - Exportations + summary: Get the exportation cache information + operationId: GetChannelCatalogExportationCacheInfo + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog exportation cache information + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogExportCacheInfoResponse' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/exportations/cache/clear: + post: + tags: + - Channel Catalogs - Exportations + summary: Clear the exportation cache + operationId: ClearChannelCatalogExportationCache + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog exportation cache cleared + content: {} + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/channelCatalogs/{channelCatalogId}/exportations/history: + get: + tags: + - Channel Catalogs - Exportations + summary: Get the exportation history + operationId: GetChannelCatalogExportationHistory + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + - name: pageNumber + in: query + description: The page number you want to get + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: pageSize + in: query + description: The entry count you want to get + required: true + schema: + maximum: 100 + minimum: 25 + type: integer + format: int32 + responses: + '200': + description: Channel catalog exportation history + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogExportationHistory' + '404': + description: ChannelCatalogId not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/marketplaces/channelcatalogs/: + get: + tags: + - Marketplaces - Channel catalogs - Global + summary: Get your marketplace channel catalog list + operationId: GetMarketplaceChannelCatalogs + parameters: + - name: storeId + in: query + description: The StoreId to filter by + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + responses: + '200': + description: Marketplace channel catalog list + content: + application/json: + schema: + $ref: '#/components/schemas/marketplaceChannelCatalogList' + '404': + description: Store not found + content: {} + /v2/user/marketplaces/channelcatalogs/publications/{marketplaceTechnicalCode}/{accountId}/publish: + post: + tags: + - Marketplaces - Channel catalogs - Publications + summary: '[PREVIEW] Launch a publication of the catalog to the marketplace' + operationId: PublishCatalogToMarketplace + parameters: + - name: marketplaceTechnicalCode + in: path + description: Marketplace Technical Code to query (required) + required: true + schema: + type: string + x-lov: MarketplaceTechnicalCode + x-lov: MarketplaceTechnicalCode + - name: accountId + in: path + description: Account Id to query (required) + required: true + schema: + type: integer + format: int32 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/publishCatalogToMarketplaceRequest' + required: true + responses: + '202': + description: Publication request accepted + content: {} + '400': + description: >- + One or more channel catalog marketplace property keys or values are + invalid for requested marketplace channel catalog. See response for + details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: >- + Requested account, marketplace or authorization for current user not + found + content: {} + '503': + description: >- + The marketplace configuration related to this channel catalog is + currently in progress. Please retry later. + headers: + Retry-After: + description: Indicate the duration to before the next retry in second. + schema: + type: integer + format: int32 + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-releaseStatus: PREVIEW + x-codegen-request-body-name: request + /v2/user/marketplaces/channelcatalogs/publications/{marketplaceTechnicalCode}/{accountId}/history: + get: + tags: + - Marketplaces - Channel catalogs - Publications + summary: >- + Fetch the publication history for an account, sorted by descending start + date + operationId: GetPublications + parameters: + - name: marketplaceTechnicalCode + in: path + description: Marketplace Technical Code to query (required) + required: true + schema: + type: string + x-lov: MarketplaceTechnicalCode + x-lov: MarketplaceTechnicalCode + - name: accountId + in: path + description: Account Id to query (required) + required: true + schema: + type: integer + format: int32 + - name: channelCatalogId + in: query + description: Channel Catalog Id by which to filter (optional) + schema: + type: string + format: guid + - name: count + in: query + description: Amount of entries to fetch (optional, default set to 10) + schema: + maximum: 100 + minimum: 10 + type: integer + format: int32 + default: 10 + - name: publicationTypes + in: query + description: Publication types by which to filter (optional) + required: true + style: form + explode: false + schema: + type: array + items: + type: string + format: publicationType + enum: + - PublishProducts + - PublishOffers + - Unpublish + x-lov: MarketplacePublicationType + x-lov: MarketplacePublicationType + responses: + '200': + description: Successfully fetched channel catalog settings + content: + application/json: + schema: + $ref: '#/components/schemas/accountPublications' + '400': + description: >- + Feature only available for Amazon, Ebay, CDiscount and Mirakl + marketplaces + content: {} + '404': + description: >- + Requested account, marketplace or authorization for current user not + found + content: {} + '503': + description: >- + The marketplace configuration related to this channel catalog is + currently in progress. Please retry later. + headers: + Retry-After: + description: Indicate the duration to before the next retry in second. + schema: + type: integer + format: int32 + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + # /v2/user/marketplaces/channelcatalogs/{channelCatalogId}/properties: + # get: + # tags: + # - Marketplaces - Channel catalogs - Settings + # summary: Get the marketplace properties for a channel catalog + # operationId: GetChannelCatalogMarketplaceProperties + # parameters: + # - name: channelCatalogId + # in: path + # required: true + # schema: + # type: string + # format: guid + # - name: redirectionPageUrl + # in: query + # required: true + # schema: + # type: string + # format: uri + # - name: Accept-Language + # in: header + # description: Indicates that the client accepts the following languages. + # style: simple + # explode: false + # schema: + # type: array + # items: + # type: string + # responses: + # '200': + # description: Successfully fetched channel catalog properties + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/channelCatalogMarketplaceProperties' + # '404': + # description: Marketplace channel Catalog not found + # content: {} + # '503': + # description: >- + # The marketplace configuration related to this channel catalog is + # currently in progress. Please retry later. + # headers: + # Retry-After: + # description: Indicate the duration to before the next retry in second. + # schema: + # type: integer + # format: int32 + # content: {} + # default: + # description: Occurs when something goes wrong + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/marketplaces/channelcatalogs/{channelCatalogId}/settings: + get: + tags: + - Marketplaces - Channel catalogs - Settings + summary: Get the marketplace settings for a channel catalog + operationId: GetChannelCatalogMarketplaceSettings + parameters: + - name: channelCatalogId + in: path + description: Channel Catalog Id to query (required) + required: true + schema: + type: string + format: guid + responses: + '200': + description: Successfully fetched channel catalog settings + content: + application/json: + schema: + $ref: '#/components/schemas/channelCatalogMarketplaceSettings' + '404': + description: Marketplace channel catalog not found + content: {} + '503': + description: >- + The marketplace configuration related to this channel catalog is + currently in progress. Please retry later. + headers: + Retry-After: + description: Indicate the duration to before the next retry in second. + schema: + type: integer + format: int32 + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Marketplaces - Channel catalogs - Settings + summary: Save new marketplace settings for a channel catalog + description: | + Allow you to configure your marketplace settings. + Partial update accepted. + operationId: SetChannelCatalogMarketplaceSettings + parameters: + - name: channelCatalogId + in: path + description: Channel Catalog Id to query + required: true + schema: + type: string + format: guid + requestBody: + description: Settings to save + content: + application/json: + schema: + $ref: '#/components/schemas/setChannelCatalogMarketplaceSettingsRequest' + required: true + responses: + '204': + description: Successfully saved channel catalog marketplace settings + content: {} + '400': + description: >- + One or more channel catalog marketplace property keys or values are + invalid for requested marketplace channel catalog. See response for + details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Marketplace channel catalog not found + content: {} + '503': + description: >- + The marketplace configuration related to this channel catalog is + currently in progress. Please retry later. + headers: + Retry-After: + description: Indicate the duration to before the next retry in second. + schema: + type: integer + format: int32 + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: model + /v2/user/marketplaces/orders/: + get: + tags: + - Marketplaces - Orders - Global + summary: '[DEPRECATED] Get all actions you can do on the order API' + operationId: GetOrderIndex + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Order index + content: + application/json: + schema: + $ref: '#/components/schemas/orderIndex' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-tagGroups: Martketplaces Orders + /v2/user/marketplaces/orders/status: + get: + tags: + - Marketplaces - Orders - Global + summary: >- + [DEPRECATED] Get current synchronization status between your + marketplaces and BeezUP accounts + description: Use /orders/v3 + operationId: GetMarketplaceAccountsSynchronization + parameters: + - name: storeId + in: query + description: The StoreId to filter by + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched current synchronization status + content: + application/json: + schema: + $ref: '#/components/schemas/accountSynchronizationList' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Store could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-tagGroups: Martketplaces Orders + /v2/user/marketplaces/orders/harvest: + post: + tags: + - Marketplaces - Orders - Global + summary: '[DEPRECATED] Send harvest request to all your marketplaces' + operationId: HarvestAll + parameters: + - name: storeId + in: query + description: The StoreId to filter by + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + responses: + '202': + description: Successfully sent harvest request to all marketplaces + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: {} + '404': + description: Requested Store could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Failed to send harvest request because allowed rate limits have been + exceeded + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + /v2/user/marketplaces/orders/automaticTransitions: + get: + tags: + - Marketplaces - Orders - AutoTransitions + summary: Get list of configured automatic Order status transitions + operationId: GetAutomaticTransitions + parameters: + - name: storeId + in: query + description: The StoreId to filter by + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: >- + Successfully fetched list of configured automatic Order status + transitions + content: + application/json: + schema: + $ref: '#/components/schemas/automaticTransitionInfoList' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Store could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + post: + tags: + - Marketplaces - Orders - AutoTransitions + summary: Configure new or existing automatic Order status transition + operationId: ConfigureAutomaticTransitions + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/configureAutomaticTransitionRequest' + required: true + responses: + '204': + description: >- + Successfully confirugred new or existing automatic Order status + transition + content: {} + '400': + description: Requested automatic Order status transition could not be configured + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/list/full: + post: + tags: + - Marketplaces - Orders - List + summary: >- + [DEPRECATED] Get a paginated list of all Orders with all Order and Order + Item(s) properties + description: > + DEPRECATED - Use /orders/v3 instead + + The purpose of this operation is to reduce the amount of request to the + API.\ + + \ + + Previous implmentation of this feature only returned a partial (light) + version of the Orders. The purpose of this API is to reduce the number + of incoming requests by returning the complete (full) Order and Order + Item(s) properties. + operationId: GetOrderListFull + parameters: + - name: Accept-Encoding + in: header + description: >- + Allows the client to indicate wether it accepts a compressed + encoding to reduce traffic size + required: true + style: simple + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderListRequest' + required: true + responses: + '200': + description: Successfully fetched the full list of Orders + content: + application/json: + schema: + $ref: '#/components/schemas/orderListFull' + '400': + description: >- + Could not process request for given parameters values. Please check + error message for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/list/light: + post: + tags: + - Marketplaces - Orders - List + summary: '[DEPRECATED] Get a paginated list of all Orders without details' + description: Use /orders/v3 instead + operationId: GetOrderListLight + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderListRequest' + required: true + responses: + '200': + description: Successfully fetched the list of Orders + content: + application/json: + schema: + $ref: '#/components/schemas/orderListLight' + '400': + description: >- + Could not process request for given parameters values. Please check + error message for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/exportations: + get: + tags: + - Marketplaces - Orders - Exports + summary: Get a paginated list of Order report exportations + operationId: GetOrderExportations + parameters: + - name: pageNumber + in: query + description: The page number you want to get + required: true + schema: + minimum: 1 + type: integer + format: int32 + - name: pageSize + in: query + description: The entry count you want to get + required: true + schema: + maximum: 100 + minimum: 25 + type: integer + format: int32 + - name: storeId + in: query + description: The store identifier to regroup the order exportations + required: true + schema: + type: string + format: guid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched the list of Order report exportations + content: + application/json: + schema: + $ref: '#/components/schemas/orderExportations' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '400': + description: >- + Could not process request for given parameters values. Please check + error message for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + post: + tags: + - Marketplaces - Orders - Exports + summary: Request a new Order report exportation to be generated + description: >- + A new file will be generated containing a summary of all the Orders + matching the requested filter settings. + operationId: ExportOrders + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/exportOrderListRequest' + required: true + responses: + '202': + description: Successfully requested new Order report exportation generation + content: {} + '400': + description: >- + Could not process request for given parameters values. Please check + error message for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: No orders have been found for this request. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/batches/setMerchantOrderInfos: + post: + tags: + - Marketplaces - Orders - Batches + summary: >- + [DEPRECATED] Send a batch of operations to set an Order's merchant + information (max 100 items per call) + description: >- + The purpose of this operation is to reduce the amount of request to the + API. + operationId: SetMerchantOrderInfoList + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/setMerchantOrderInfoListRequest' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/batches/clearMerchantOrderInfos: + post: + tags: + - Marketplaces - Orders - Batches + summary: >- + [DEPRECATED] Send a batch of operations to clear an Order's merchant + information (max 100 items per call) + description: >- + The purpose of this operation is to reduce the amount of request to the + API. + operationId: ClearMerchantOrderInfoList + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/clearMerchantOrderInfoListRequest' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/batches/changeOrders/{changeOrderType}: + post: + tags: + - Marketplaces - Orders - Batches + summary: >- + [DEPRECATED] Send a batch of operations to change your marketplace Order + information: accept, ship, etc. (max 100 items per call) + description: > + The purpose of this operation is to reduce the amount of request to the + API. + + Max 100 items per call. + operationId: ChangeOrderList + parameters: + - name: changeOrderType + in: path + description: The Order change type + required: true + schema: + type: string + x-lov: OrderChangeBusinessOperationType + x-lov: OrderChangeBusinessOperationType + - name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as + user associated with the current subscription key. We recommend + providing your application's user login. + required: true + schema: + type: string + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeOrderListRequest' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}: + get: + tags: + - Marketplaces - Orders - Order + summary: '[DEPRECATED] DEPRECATED - Get full Order and Order Item(s) properties' + description: DEPRECATED - Use /orders/v3 instead + operationId: GetOrder + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched Order and Order Item(s) properties + headers: + ETag: + description: > + ETag value to identify the current version of requested Order\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the order\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: + application/json: + schema: + $ref: '#/components/schemas/order' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + head: + tags: + - Marketplaces - Orders - Order + summary: >- + [DEPRECATED] DEPRECATED - Get the meta information about the order + (ETag, Last-Modified) + description: > + DEPRECATED - Use /orders/v3 instead + + The purpose of this operation is to reduce the bandwith usage by getting + just the meta information about the order (ETag, Last-Modified) with the + body. + + This could be useful + operationId: HeadOrder + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched Order and Order Item(s) properties + headers: + ETag: + description: > + ETag value to identify the current version of requested Order\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the order\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + /v2/user/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/history: + get: + tags: + - Marketplaces - Orders - Order + summary: '[DEPRECATED] Get an Order''s harvest and change history' + operationId: GetOrderHistory + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched Order history + content: + application/json: + schema: + $ref: '#/components/schemas/orderHistory' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + /v2/user/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/harvest: + post: + tags: + - Marketplaces - Orders - Order + summary: '[DEPRECATED] Send harvest request for a single Order' + operationId: HarvestOrder + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + responses: + '202': + description: Successfully sent Order harvest request + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: >- + Failed to send harvest request because allowed rate limits have been + exceeded + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + /v2/user/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/setMerchantOrderInfo: + post: + tags: + - Marketplaces - Orders - Order + summary: '[DEPRECATED] Set an Order''s merchant information' + operationId: SetMerchantOrderInfo + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/setMerchantOrderInfoRequest' + required: true + responses: + '204': + description: Successfully set Order merchant order info set + content: {} + '400': + description: >- + Could not update Order merchant information. Please see body for + more information. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/clearMerchantOrderInfo: + post: + tags: + - Marketplaces - Orders - Order + summary: '[DEPRECATED] Clear an Order''s merchant information' + operationId: ClearMerchantOrderInfo + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + responses: + '204': + description: Successfully cleared Order merchant order info set + content: {} + '400': + description: >- + Could not update Order merchant information. Please see body for + more information. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + /v2/user/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/{changeOrderType}: + post: + tags: + - Marketplaces - Orders - Order + summary: >- + [DEPRECATED] Change your marketplace Order Information (accept, ship, + etc.) + operationId: ChangeOrder + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: changeOrderType + in: path + description: The Order change type + required: true + schema: + type: string + x-lov: OrderChangeBusinessOperationType + x-lov: OrderChangeBusinessOperationType + - name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as + user associated with the current subscription key. We recommend + providing your application's user login. + required: true + schema: + type: string + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + - name: If-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To ensure that you are making a change on the lastest version of the + resource.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeOrderRequest' + required: false + responses: + '202': + description: Order change request accepted + content: {} + '400': + description: >- + Invalid order change request, could not be send to the marketplace. + Please check the body of this request. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: | + Already processing a change request for this Order.\ + Please refresh your clients Order information and retry later. + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '412': + description: >- + The ETag sent in the http header If-Match did not match with the + current version. Please refresh the information related to this + resource. + headers: + ETag: + description: > + The ETag value to identify the resource.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: true + x-releaseStatus: DEPRECATED + x-codegen-request-body-name: request + # /orders/v3/lov/orderManagementReadyMarketplaceBusinessCode: + # get: + # tags: + # - Marketplaces - Orders V3 - Global + # description: Get the list of MarketplaceBusinessCode ready for Order Management + # operationId: GetOrderManagementReadyMarketplaceBusinessCode + # parameters: + # - name: Accept-Language + # in: header + # description: Indicates that the client accepts the following languages. + # style: simple + # explode: false + # schema: + # type: array + # items: + # type: string + # - name: storeIds + # in: query + # description: StoredIds to filter + # style: form + # explode: false + # schema: + # type: array + # items: + # type: string + # responses: + # '200': + # description: Successfully fetched current synchronization status + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/oMReadyMarketplaceBusinessCodeResponse' + # '304': + # description: >- + # The ETag sent in the http header If-None-Match did not change. So + # you are up to date ! + # headers: + # ETag: + # description: > + # ETag value to identify the current version of the resource\ + + # For more details go to this link: + # http://tools.ietf.org/html/rfc7232#section-2.3 + # schema: + # type: string + # Last-Modified: + # description: > + # Last modification UTC date of the resource\ + + # For more details go to this link: + # https://tools.ietf.org/html/rfc7232#section-2.2 + # schema: + # type: string + # format: date-time + # content: {} + # '404': + # description: Requested Store could not be found + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/errorResponseMessage' + # default: + # description: Occurs when something goes wrong + # content: + # application/json: + # schema: + # $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /orders/v3/status: + get: + tags: + - Marketplaces - Orders V3 - Global + description: >- + Get current synchronization status between your marketplaces and BeezUP + accounts + operationId: GetMarketplaceAccountsSynchronizationV3 + parameters: + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + - name: storeIds + in: query + description: StoredIds to filter + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: >- + Successfully fetched the list of MarketplaceBusinessCode ready for + Order Management + content: + application/json: + schema: + $ref: '#/components/schemas/accountSynchronizationList' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '400': + description: Invalid store id + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /orders/v3/harvest: + post: + tags: + - Marketplaces - Orders V3 - Global + summary: Send harvest request to all your marketplaces + operationId: HarvestAllV3 + parameters: + - name: storeId + in: query + description: The StoreId to filter by + schema: + type: string + format: StoreId + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + responses: + '202': + description: Successfully sent harvest request to all marketplaces + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: {} + '404': + description: Requested Store could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '409': + description: >- + Failed to send harvest request because allowed rate limits have been + exceeded + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + /orders/v3/list/full: + post: + tags: + - Marketplaces - Orders V3 - List + summary: >- + Get a paginated list of all Orders with all Order and Order Item(s) + properties + description: > + The purpose of this operation is to reduce the amount of request to the + API.\ + + \ + + Previous implmentation of this feature only returned a partial (light) + version of the Orders. The purpose of this API is to reduce the number + of incoming requests by returning the complete (full) Order and Order + Item(s) properties. + operationId: GetOrderListFullV3 + parameters: + - name: Accept-Encoding + in: header + description: >- + Allows the client to indicate wether it accepts a compressed + encoding to reduce traffic size + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderListRequest' + required: true + responses: + '200': + description: Successfully fetched the full list of Orders + content: + application/json: + schema: + $ref: '#/components/schemas/orderListFullWithLinks' + '400': + description: >- + Could not process request for given parameters values. Please check + error message for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /orders/v3/list/light: + post: + tags: + - Marketplaces - Orders V3 - List + summary: Get a paginated list of all Orders without details + operationId: GetOrderListLightV3 + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderListRequest' + required: true + responses: + '200': + description: Successfully fetched the list of Orders + content: + application/json: + schema: + $ref: '#/components/schemas/orderListLightWithLinks' + '400': + description: >- + Could not process request for given parameters values. Please check + error message for more details. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}: + get: + tags: + - Marketplaces - Orders V3 - Order + summary: Get full Order and Order Item(s) properties + operationId: GetOrderV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched Order and Order Item(s) properties + headers: + ETag: + description: > + ETag value to identify the current version of requested Order\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the order\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: + application/json: + schema: + $ref: '#/components/schemas/orderWithLinks' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + head: + tags: + - Marketplaces - Orders V3 - Order + summary: Get the meta information about the order (ETag, Last-Modified) + description: > + The purpose of this operation is to reduce the bandwith usage by getting + just the meta information about the order (ETag, Last-Modified) with the + body. + + This could be useful + operationId: HeadOrderV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested + resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give + you a new content, otherwise the response will be: 304 Not Modified, + without any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + responses: + '200': + description: Successfully fetched Order and Order Item(s) properties + headers: + ETag: + description: > + ETag value to identify the current version of requested Order\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the order\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/{changeOrderType}: + post: + tags: + - Marketplaces - Orders V3 - Order + summary: Change your marketplace Order Information (accept, ship, etc.) + operationId: ChangeOrderV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: changeOrderType + in: path + description: The Order change type + required: true + schema: + type: string + x-lov: OrderChangeBusinessOperationType + x-lov: OrderChangeBusinessOperationType + - name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as + user associated with the current subscription key. We recommend + providing your application's user login. + required: true + schema: + type: string + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeOrderRequest' + required: false + responses: + '202': + description: Order change request accepted + headers: + Location: + description: >- + Indicate the address you should follow to know the status of + your order change operation + schema: + type: string + content: {} + '400': + description: >- + Invalid order change request, could not be send to the marketplace. + Please check the body of this request. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '409': + description: | + Already processing a change request for this Order.\ + Please refresh your clients Order information and retry later. + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + Location: + description: >- + Indicate the address you should follow to know the status of the + existing order change operation + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '412': + description: >- + The ETag sent in the http header If-Match did not match with the + current version. Please refresh the information related to this + resource. + headers: + ETag: + description: > + The ETag value to identify the resource.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + content: {} + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/history: + get: + tags: + - Marketplaces - Orders V3 - Order + summary: Get an Order's harvest and change history + operationId: GetOrderHistoryV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + responses: + '200': + description: Successfully fetched Order history + content: + application/json: + schema: + $ref: '#/components/schemas/orderHistory' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/harvest: + post: + tags: + - Marketplaces - Orders V3 - Order + summary: Send harvest request for a single Order + operationId: HarvestOrderV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + responses: + '202': + description: Successfully sent Order harvest request + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '409': + description: >- + Failed to send harvest request because allowed rate limits have been + exceeded + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-validation: + - validatorName: userAuthorized + statusCode: '401' + - validatorName: orderExists + statusCode: '404' + /orders/v3/{marketplaceTechnicalCode}/{accountId}/harvest: + post: + tags: + - Marketplaces - Orders V3 - Order + summary: Send harvest request for an Account + operationId: HarvestAccount + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: marketplaceOrderId + in: query + schema: + type: string + - name: beezUPOrderId + in: query + schema: + type: string + responses: + '202': + description: Successfully sent Order harvest request + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: {} + '404': + description: Requested Account Or beezUPOrderId could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '409': + description: >- + Failed to send harvest request because allowed rate limits have been + exceeded + headers: + Retry-After: + description: >- + Indicates the duration in seconds to wait to be able to make + this request again + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-validation: + - validatorName: userAuthorized + statusCode: '401' + - validatorName: accountExists + statusCode: '404' + - validatorName: beezUPOrderIdExists + statusCode: '404' + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/history/{orderChangeExecutionUUID}: + get: + tags: + - Marketplaces - Orders V3 - Order + summary: Get the order change reporting + description: >- + This operation will help you to know the status of your order change + operation + operationId: GetOrderChangeReportingV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: orderChangeExecutionUUID + in: path + description: The order change execution id + required: true + schema: + type: string + responses: + '200': + description: Successfully fetched Order change reporting + content: + application/json: + schema: + $ref: '#/components/schemas/changeOrderReporting' + '304': + description: >- + The ETag sent in the http header If-None-Match did not change. So + you are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/setMerchantOrderInfo: + post: + tags: + - Marketplaces - Orders V3 - Order + summary: Set an Order's merchant information + operationId: SetMerchantOrderInfoV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/setMerchantOrderInfoRequest' + required: true + responses: + '202': + description: Set Order merchant order info accepted + content: {} + '400': + description: >- + Could not update Order merchant information. Please see body for + more information. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /orders/v3/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId}/clearMerchantOrderInfo: + post: + tags: + - Marketplaces - Orders V3 - Order + summary: Clear an Order's merchant information + operationId: ClearMerchantOrderInfoV3 + parameters: + - name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + - name: accountId + in: path + required: true + schema: + type: integer + format: int32 + - name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + responses: + '202': + description: Clear Order merchant order info accepted + content: {} + '400': + description: >- + Could not update Order merchant information. Please see body for + more information. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '404': + description: Requested Order could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + /orders/v3/batches/setMerchantOrderInfos: + post: + tags: + - Marketplaces - Orders V3 - Batches + summary: >- + Send a batch of operations to set an Order's merchant information (max + 100 items per call) + description: >- + The purpose of this operation is to reduce the amount of request to the + API. + operationId: SetMerchantOrderInfoListV3 + parameters: + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/setMerchantOrderInfoListRequest' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /orders/v3/batches/clearMerchantOrderInfos: + post: + tags: + - Marketplaces - Orders V3 - Batches + summary: >- + Send a batch of operations to clear an Order's merchant information (max + 100 items per call) + description: >- + The purpose of this operation is to reduce the amount of request to the + API. + operationId: ClearMerchantOrderInfoListV3 + parameters: + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/clearMerchantOrderInfoListRequest' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /orders/v3/batches/changeOrders/{changeOrderType}: + post: + tags: + - Marketplaces - Orders V3 - Batches + summary: >- + Send a batch of operations to change your marketplace Order information: + accept, ship, etc. (max 100 items per call) + description: > + The purpose of this operation is to reduce the amount of request to the + API. + + Max 100 items per call. + operationId: ChangeOrderListV2 + parameters: + - name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as + user associated with the current subscription key. We recommend + providing your application's user login. + required: true + schema: + type: string + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + - name: changeOrderType + in: path + description: The Order change type + required: true + schema: + type: string + x-lov: OrderChangeBusinessOperationType + x-lov: OrderChangeBusinessOperationType + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeOrderListRequestV2' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /orders/v3/batches/changeOrders: + post: + tags: + - Marketplaces - Orders V3 - Batches + summary: >- + Send a batch of operations to change your marketplace Order information: + accept, ship, etc. (max 100 items per call) + description: > + The purpose of this operation is to reduce the amount of request to the + API. + + Max 100 items per call. + operationId: ChangeOrderListV3 + parameters: + - name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as + user associated with the current subscription key. We recommend + providing your application's user login. + required: true + schema: + type: string + - name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/changeOrderListRequest' + required: true + responses: + '202': + description: >- + Succesfully received and processed batched operations. Please check + response to see the status per operation. + content: + application/json: + schema: + $ref: '#/components/schemas/batchOrderOperationResponse' + '400': + description: Requested too many batch operations + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/subscriptions/: + get: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Get the subscription list + operationId: GetSubscriptionList + responses: + '200': + description: The subscription list + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/subscriptionIndex' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + x-basePath: /v2/user/marketplaces/orders/subscriptions + /v2/user/marketplaces/orders/subscriptions/{id}: + get: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Get a subscription to the orders + operationId: GetSubscription + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + responses: + '200': + description: Subscription info + content: + application/json: + schema: + $ref: '#/components/schemas/subscriptionIndex' + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Creates a subscription to the orders + description: >- + Please take a look at this sequence diagram to understand the + subscription process to follow + [here](https://www.websequencediagrams.com/files/render?link=SBYbeIc8NGshk6ooCbmjoBLIMl4fIGO1xjJbPBQAglBo0n6BwEReh7NXQiPSjOTX) + operationId: CreateSubscription + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/createSubscriptionRequest' + required: true + responses: + '202': + description: Subscription creation accepted + content: {} + '400': + description: Invalid subscription request. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + '409': + description: The subscription id is already used. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionAlreadyExistsException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + delete: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Delete a subscription to the orders + operationId: DeleteSubscription + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + responses: + '202': + description: Subscription deletion accepted + content: {} + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + deprecated: false + /v2/user/marketplaces/orders/subscriptions/{id}/reporting: + get: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Get the push reporting related to this subscription + operationId: GetSubscriptionPushReporting + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + - name: pageNumber + in: query + schema: + minimum: 1 + type: integer + format: PageNumber + - name: pageSize + in: query + schema: + maximum: 100 + minimum: 1 + type: integer + format: PageSize + responses: + '200': + description: Subscription push reporting info + headers: + X-Total-Count: + description: The total item count related to this query + schema: + type: integer + Link: + description: >- + Based on the RFC 5988 - Web Linking, the page navigation will be + indicated here with the rel=next, rel=previous, rel=first, + rel=last, the pageNumber and the pageSize will be indicated in + the link param + schema: + type: array + items: + type: string + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/subscriptionPushReporting' + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/marketplaces/orders/subscriptions/{id}/activate: + post: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Activate a subscription to the orders + description: > + At this moment, BeezUP will ensure that your callback url is respecting + this specification: + + - + https://app.swaggerhub.com/apis/BeezUP/public_marketplaces_orders_subscriptions_consumer-dev/1.0#/Subscriptions/Verification + + + After that we will send you the orders related to your subscription, + respecting this specification: + + - + https://app.swaggerhub.com/apis/BeezUP/public_marketplaces_orders_subscriptions_consumer-dev/1.0#/Subscriptions/PushOrders + operationId: ActivateSubscription + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/activateSubscriptionRequest' + required: false + responses: + '202': + description: Subscription activation accepted + content: {} + '400': + description: Activation subscription request is invalid + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + '503': + description: The target url is not available + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionTargetNotAvailableException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/subscriptions/{id}/deactivate: + post: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Deactivate a subscription to the orders + operationId: DeactivateSubscription + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + responses: + '202': + description: Subscription deactivation accepted + content: {} + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/marketplaces/orders/subscriptions/{id}/retry: + post: + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + summary: Force retry push orders immediatly + description: >- + In case your subscription consumption is unavailable and your + subscription is still active you can ask to retry immediatly to push + orders instead of waiting the next scheduled retry date + operationId: RetryPushOrders + parameters: + - name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + responses: + '202': + description: Retry push orders request accepted + content: {} + '404': + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + '409': + description: >- + The subscription is deactivated or your subscription consumption + availability status is available. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionRetryRejectedException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/marketplaces/orders/invoices/settings/general: + get: + tags: + - OM Invoice - API - Settings + summary: Get Order Invoice general settings + operationId: GetOrderInvoiceGeneralSettings + responses: + '200': + description: Settings successfully retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/getOrderInvoiceGeneralSettingsResponse' + '403': + description: The ownerId is not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + '404': + description: | + The order invoice general settings are not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceGeneralSettingsNotFoundException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - OM Invoice - API - Settings + summary: Save Order Invoice general settings + operationId: SaveOrderInvoiceGeneralSettings + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderInvoiceGeneralSettings' + required: true + responses: + '204': + description: General Settings successfully saved + content: {} + '400': + description: | + The settingsgeneral did not pass the validation + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceGeneralSettingsValidationFailedException + '403': + description: The ownerId is not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/invoices/settings/design: + get: + tags: + - OM Invoice - API - Settings + summary: Get Order Invoice design settings + operationId: GetOrderInvoiceDesignSettings + responses: + '200': + description: Design successfully retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/orderInvoiceDesignSettings' + '403': + description: The ownerId is not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + '404': + description: | + The order invoice design is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceDesignSettingsNotFoundException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - OM Invoice - API - Settings + summary: Save Order Invoice design settings + operationId: SaveOrderInvoiceDesignSettings + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderInvoiceDesignSettings' + required: true + responses: + '204': + description: Design successfully saved + content: {} + '400': + description: | + The design did not pass the validation + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceDesignSettingsValidationFailedException + '403': + description: The ownerId is not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/invoices/settings/design/preview: + post: + tags: + - OM Invoice - API - Settings + summary: View a preview an Order Invoice using custom design settings + operationId: GetOrderInvoiceDesignSettingsPreview + parameters: + - name: Accept-Encoding + in: header + description: >- + Allows the client to indicate wether it accepts a compressed + encoding to reduce traffic size + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/orderInvoiceDesignSettings' + required: true + responses: + '200': + description: Design Preview successfully retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/getOrderInvoiceDesignPreviewResponse' + '403': + description: The ownerId is not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/invoices/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderUUID}/generate: + post: + tags: + - OM Invoice - API - Generation + summary: Generate an Order Invoice + operationId: GenerateOrderInvoice + parameters: + - name: marketplaceTechnicalCode + in: path + description: The Marketplace Technical Code + required: true + schema: + type: string + format: MarketplaceTechnicalCode + - name: accountId + in: path + description: The Account Identifier + required: true + schema: + type: string + format: MarketplaceAccountId + - name: beezUPOrderUUID + in: path + description: The BeezUP Order UUID + required: true + schema: + type: string + format: BeezUPOrderUUID + - name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as + user associated with the current subscription key. We recommend + providing your application's user login. + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/generateOrderInvoiceRequest' + required: true + responses: + '202': + description: Request Accepted. + headers: + Location: + description: >- + The location of the generated invoice. Might take a few seconds + to be available + schema: + type: string + content: {} + '403': + description: | + OwnerId not authorized + The required order invoice settings have not been set + BeezUPOrderStatus forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + - OrderInvoiceDesignSettingsNotFoundException + - OrderInvoiceGeneralSettingsNotFoundException + - OrderInvoiceGenerationBeezUPOrderStatusForbiddenException + '404': + description: | + The order cannot be retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderNotFoundException + '409': + description: | + The InvoiceNumber is already used + There is already an invoice for this order + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceNumberAlreadyUsedException + - OrderAlreadyHasInvoiceException + '429': + description: | + Too many Requests. Please retry in a few seconds + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceTooManyRequestsException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/invoices/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderUUID}/preview: + post: + tags: + - OM Invoice - API - Generation + summary: View a preview an Order Invoice + operationId: GetOrderInvoicePreview + parameters: + - name: marketplaceTechnicalCode + in: path + description: The Marketplace Technical Code + required: true + schema: + type: string + format: MarketplaceTechnicalCode + - name: accountId + in: path + description: The Account Identifier + required: true + schema: + type: string + format: MarketplaceAccountId + - name: beezUPOrderUUID + in: path + description: The BeezUP Order UUID + required: true + schema: + type: string + format: BeezUPOrderUUID + - name: Accept-Encoding + in: header + description: >- + Allows the client to indicate wether it accepts a compressed + encoding to reduce traffic size + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/previewOrderInvoiceRequest' + required: true + responses: + '200': + description: Order Invoice preview successfully returned. + content: + application/json: + schema: + $ref: '#/components/schemas/previewOrderInvoiceResponse' + '403': + description: | + OwnerId not authorized + The required order invoice settings have not been set + BeezUPOrderStatus forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + - OrderInvoiceDesignSettingsNotFoundException + - OrderInvoiceGeneralSettingsNotFoundException + - OrderInvoiceGenerationBeezUPOrderStatusForbiddenException + '404': + description: | + The order cannot be retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderNotFoundException + '409': + description: | + The InvoiceNumber is already used + There is already an invoice for this order + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceNumberAlreadyUsedException + - OrderAlreadyHasInvoiceException + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/marketplaces/orders/invoices/getPdfInvoice: + post: + tags: + - OM Invoice - API - Generation + summary: Returns the PDF version of the invoice + operationId: GetOrderInvoicePdf + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/getOrderInvoicePdfFromHtmlInvoiceUrlRequest' + required: true + responses: + '200': + description: The PDF version of the HTML invoice URL in the request + content: + application/pdf: + schema: + type: string + format: binary + '403': + description: The ownerId is not found or not authorized + content: + application/pdf: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + '404': + description: | + The order invoice does not exist + content: + application/pdf: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceNotFoundException + default: + description: Occurs when something goes wrong + content: + application/pdf: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/: + get: + tags: + - Analytics - Global + summary: Get the Analytics API operation index + operationId: AnalyticsIndex + responses: + '200': + description: Analytics API operation index + content: + application/json: + schema: + $ref: '#/components/schemas/analyticsIndex' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}: + get: + tags: + - Analytics - Global + summary: Get the Analytics API operation index for one store + operationId: AnalyticsStoreIndex + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Analytics API operation index for one store + content: + application/json: + schema: + $ref: '#/components/schemas/analyticsStoreIndex' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/tracking/status: + get: + tags: + - Analytics - Tracking + summary: Get the global synchronization status of clicks and orders + description: | + Clicks and orders are eventually consistent. \ + This operation gets the current global state of projections. + operationId: GetTrackingStatus + responses: + '200': + description: The tracking status informations + content: + application/json: + schema: + $ref: '#/components/schemas/trackingStatus' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/tracking/status: + get: + tags: + - Analytics - Tracking + summary: Get the synchronization status of clicks and orders of a store + description: | + Clicks and orders are eventually consistent. \ + This operation gets the current state of projections for a store. + operationId: GetStoreTrackingStatus + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Store Tracking Status + content: + application/json: + schema: + $ref: '#/components/schemas/storeTrackingStatus' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/tracking/clicks: + get: + tags: + - Analytics - Tracking + summary: Get the latest tracked clicks + operationId: GetStoreTrackedClicks + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: count + in: query + description: The amount of clicks to retrieve + schema: + maximum: 100 + minimum: 5 + type: integer + default: 100 + responses: + '200': + description: Click list + content: + application/json: + schema: + $ref: '#/components/schemas/trackedClicks' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/tracking/orders: + get: + tags: + - Analytics - Tracking + summary: Get the latest tracked orders + operationId: GetStoreTrackedOrders + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: count + in: query + description: The amount of orders to retrieve + schema: + maximum: 100 + minimum: 5 + type: integer + default: 100 + responses: + '200': + description: Order list + content: + application/json: + schema: + $ref: '#/components/schemas/trackedOrders' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/tracking/externalorders: + get: + tags: + - Analytics - Tracking + summary: Get the latest tracked external orders + operationId: GetStoreTrackedExternalOrders + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: count + in: query + description: The amount of external orders to retrieve + schema: + maximum: 100 + minimum: 5 + type: integer + default: 100 + responses: + '200': + description: External Order list + content: + application/json: + schema: + $ref: '#/components/schemas/trackedExternalOrders' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/reports/byday: + post: + tags: + - Analytics - Statistics + summary: Get the report by day for a StoreId + description: Get the report by day for a StoreId + operationId: GetStoreReportByDayPerStore + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/reportByDayRequest' + required: true + responses: + '200': + description: Your reporting by day + content: + application/json: + schema: + $ref: '#/components/schemas/reportByDayPerStoreResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/reports/byday: + post: + tags: + - Analytics - Statistics + summary: Get the report by day for a StoreId + description: Get the report by day for a StoreId + operationId: GetStoreReportByDay + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/reportByDayRequest' + required: true + responses: + '200': + description: Your reporting by day + content: + application/json: + schema: + $ref: '#/components/schemas/reportByDayResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/reports/bychannel: + post: + tags: + - Analytics - Statistics + summary: Get the report by channel + description: Get the report by channel + operationId: GetStoreReportByChannel + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/reportByChannelRequest' + required: true + responses: + '200': + description: Your reporting by channel + content: + application/json: + schema: + $ref: '#/components/schemas/reportByChannelResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/reports/bycategory: + post: + tags: + - Analytics - Statistics + summary: Get the report by category + description: Get the report by category + operationId: GetStoreReportByCategory + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/reportByCategoryRequest' + required: true + responses: + '200': + description: Your reporting by channel + content: + application/json: + schema: + $ref: '#/components/schemas/reportByCategoryResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/reports/byproduct: + post: + tags: + - Analytics - Statistics + summary: Get the report by product + description: Get the report by product + operationId: GetStoreReportByProduct + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/reportByProductRequest' + required: true + responses: + '200': + description: Your reporting by product + content: + application/json: + schema: + $ref: '#/components/schemas/reportByProductResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/optimisations/all/{actionName}: + post: + tags: + - Analytics - Optimisations + summary: Optimise all products + description: | + /!\ WARNING /!\ \ + Apply the operation on every product related to this request. \ + This operation is used at the bottom of the analytics page result. + operationId: OptimiseAll + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: actionName + in: path + required: true + schema: + type: string + format: optimisationActionName + enum: + - reenable + - disable + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/optimiseAllRequest' + required: true + responses: + '204': + description: Products optimisatized + content: {} + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/optimisations/{actionName}: + post: + tags: + - Analytics - Optimisations + summary: Optimise products by page + description: | + /!\ WARNING /!\ \ + Apply the operation on every product related to this request. \ + This operation is used at the bottom of the analytics page result. + operationId: Optimise + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: actionName + in: path + required: true + schema: + type: string + format: optimisationActionName + enum: + - reenable + - disable + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/optimiseRequest' + required: true + responses: + '204': + description: Products optimisatized + content: {} + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/optimisations/bychannel/{channelId}/{actionName}: + post: + tags: + - Analytics - Optimisations + summary: Optimise products by channel + description: | + /!\ WARNING /!\ \ + Apply the operation on every product on this channel. + operationId: OptimiseByChannel + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: channelId + in: path + description: The channel identifier concerned by this optimisation + required: true + schema: + type: string + format: guid + - name: actionName + in: path + required: true + schema: + type: string + format: optimisationActionName + enum: + - reenable + - disable + responses: + '204': + description: Products optimisatized + content: {} + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/optimisations/bycategory/{catalogCategoryId}/{actionName}: + post: + tags: + - Analytics - Optimisations + summary: Optimise products by category + description: > + /!\ WARNING /!\ \ + + This operation will reenable or disable products's category for every + channel indicated in the body. + operationId: OptimiseByCategory + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: catalogCategoryId + in: path + description: The category identifier concerned by this optimisation + required: true + schema: + type: string + format: guid + - name: actionName + in: path + required: true + schema: + type: string + format: optimisationActionName + enum: + - reenable + - disable + requestBody: + description: The channel identifier list concerned by this optimisation + content: + application/json: + schema: + maxItems: 1 + minItems: 1 + type: array + example: + - a2d38563-50f0-43f1-be2b-b16e7ec4f007 + items: + type: string + format: guid + required: false + responses: + '204': + description: Products optimisatized + content: {} + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/optimisations/byproduct/{productId}/{actionName}: + post: + tags: + - Analytics - Optimisations + summary: Optimise product + description: > + /!\ WARNING /!\ \ + + This operation will reenable or disable this product for every channel + indicated in the body. + operationId: OptimiseByProduct + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: productId + in: path + description: The product identifier concerned by this optimisation + required: true + schema: + type: string + format: guid + - name: actionName + in: path + required: true + schema: + type: string + format: optimisationActionName + enum: + - reenable + - disable + requestBody: + description: The channel identifier list concerned by this optimisation + content: + application/json: + schema: + maxItems: 1 + minItems: 1 + type: array + example: + - a2d38563-50f0-43f1-be2b-b16e7ec4f007 + items: + type: string + format: guid + required: false + responses: + '204': + description: Product(s) optimisatized + content: {} + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/optimisations/copy: + post: + tags: + - Analytics - Optimisations + summary: Copy product optimisations between 2 channels + operationId: CopyOptimisation + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/copyOptimisationRequest' + required: true + responses: + '200': + description: Products optimisatisation copied + content: + application/json: + schema: + $ref: '#/components/schemas/copyOptimisationResponse' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/reports/filters: + get: + tags: + - Analytics - Reports + summary: Get report filter list for the given store + operationId: GetReportFilters + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Report filter list + content: + application/json: + schema: + $ref: '#/components/schemas/reportFilterList' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/reports/filters/{reportFilterId}: + get: + tags: + - Analytics - Reports + summary: Get the report filter description + operationId: GetReportFilter + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: reportFilterId + in: path + description: Your report filter identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Report filter + content: + application/json: + schema: + $ref: '#/components/schemas/reportFilter' + '404': + description: Report filter not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + put: + tags: + - Analytics - Reports + summary: Save the report filter + operationId: SaveReportFilter + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: reportFilterId + in: path + description: Your report filter identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/saveReportFilterRequest' + required: true + responses: + '204': + description: Report filter saved + content: {} + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '401': + description: >- + This report filter is used by rule. In the error message you will + find the rule identifier. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '403': + description: >- + This report filter identifier is already used by another store, + please check your identifiers. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Report filter name already exists + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: reportFilter + delete: + tags: + - Analytics - Reports + summary: Delete the report filter + operationId: DeleteReportFilter + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: reportFilterId + in: path + description: Your report filter identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Report filter deleted + content: {} + '401': + description: >- + This report filter is used by rule. In the error message you will + find the rule identifier. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Report filter not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules: + get: + tags: + - Analytics - Rules + summary: Gets the list of rules for a given store + operationId: GetRules + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Rule list + content: + application/json: + schema: + $ref: '#/components/schemas/ruleList' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + post: + tags: + - Analytics - Rules + summary: Rule creation + operationId: CreateRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/createRuleRequest' + required: true + responses: + '204': + description: Rule created + content: {} + '400': + description: Period on filter cannot be custom or filter does not exist + content: + '*/*': + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '401': + description: >- + Store not allowed to use rules. Please upgrade your offer or contact + us. + content: + '*/*': + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '403': + description: >- + Reached the maximum amount of rules allowed for your offer. Please + upgrade your offer or contact us. + content: + '*/*': + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + '*/*': + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + '*/*': + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/rules/{ruleId}: + get: + tags: + - Analytics - Rules + summary: Gets the rule + operationId: GetRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Get Rule + content: + application/json: + schema: + $ref: '#/components/schemas/rule' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + delete: + tags: + - Analytics - Rules + summary: Delete Rule + operationId: DeleteRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Rule deleted + content: {} + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + patch: + tags: + - Analytics - Rules + summary: Update Rule + operationId: UpdateRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/updateRuleRequest' + required: true + responses: + '204': + description: Rule updated + content: {} + '400': + description: Filter does not exist or period on filter cannot be custom + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '401': + description: >- + Store not allowed to use rules. Please upgrade your offer or contact + us. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + x-codegen-request-body-name: request + /v2/user/analytics/{storeId}/rules/{ruleId}/moveup: + post: + tags: + - Analytics - Rules + summary: Move the rule up + operationId: MoveUpRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Rule moved up + content: {} + '400': + description: Priority can only be changed when more than one rule is defined + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules/{ruleId}/movedown: + post: + tags: + - Analytics - Rules + summary: Move the rule down + operationId: MoveDownRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Rule moved down + content: {} + '400': + description: Priority can only be changed when more than one rule is defined + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules/{ruleId}/enable: + post: + tags: + - Analytics - Rules + summary: Enable rule + operationId: EnableRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Rune enabled + content: {} + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules/{ruleId}/disable: + post: + tags: + - Analytics - Rules + summary: Disable rule + operationId: DisableRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Rule disabled + content: {} + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules/run: + post: + tags: + - Analytics - Rules + summary: Run all rules for this store + operationId: RunRules + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: All rules executed. + content: {} + '401': + description: >- + Store not allowed to use rules. Please upgrade your offer or contact + us. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules/{ruleId}/run: + post: + tags: + - Analytics - Rules + summary: Run rule + operationId: RunRule + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Rule executed + content: {} + '400': + description: Rule is not enabled. Please enable this run before trying to run it. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '401': + description: >- + Store not allowed to use rules. Please upgrade your offer or contact + us. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '409': + description: Rules for this store are currently running. Please try again later. + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/analytics/{storeId}/rules/executions: + get: + tags: + - Analytics - Rules + summary: Get the rules execution history + operationId: GetRulesExecutions + parameters: + - name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + - name: pageNumber + in: query + description: The page to retrieve + required: true + schema: + minimum: 1 + type: integer + default: 1 + - name: pageSize + in: query + description: The count of rule history to retrieve + required: true + schema: + maximum: 100 + minimum: 10 + type: integer + default: 10 + responses: + '200': + description: Rules executions list + content: + application/json: + schema: + $ref: '#/components/schemas/ruleExecutionReportings' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + '404': + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/legacyTracking/channelCatalogs/: + get: + tags: + - Channel Catalogs - Legacy Tracking - Global + summary: >- + List all your current channel catalogs configured to use legacy tracking + format + operationId: GetLegacyTrackingChannelCatalogs + parameters: + - name: storeId + in: query + description: The store identifier + schema: + type: string + format: guid + example: 04730364-9826-4ff3-92e4-51fccd02bf10 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/legacyTrackingChannelCatalogList' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/legacyTracking/channelCatalogs/{channelCatalogId}: + get: + tags: + - Channel Catalogs - Legacy Tracking - Global + summary: >- + Get the channel catalog configured to use legacy tracking format + information + operationId: GetLegacyTrackingChannelCatalog + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '200': + description: Channel catalog configured to use legacy tracking format + content: + application/json: + schema: + $ref: '#/components/schemas/legacyTrackingChannelCatalog' + '404': + description: Channel catalog not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + /v2/user/legacyTracking/channelCatalogs/{channelCatalogId}/migrate: + post: + tags: + - Channel Catalogs - Legacy Tracking - Global + summary: Migrate a channel catalog to current tracking format + operationId: MigrateLegacyTrackingChannelCatalog + parameters: + - name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + responses: + '204': + description: Channel catalog migrated + content: {} + '404': + description: Channel catalog not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + default: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' +components: + schemas: + loginRequest: + required: + - login + - password + type: object + properties: + login: + $ref: '#/components/schemas/BeezUP_Common_Email' + password: + type: string + description: Your password + format: password + example: I@mW0nder$Full + apiCredentials: + type: object + properties: + credentials: + type: array + description: Your API credential list + example: + - productName: UserApi + primaryToken: 3b22980d8d1143c6ba7adf4e55b9a153 + secondaryToken: 162ae17fd52044c38cce3388ea5b0c91 + items: + $ref: '#/components/schemas/apiCredential' + apiCredential: + type: object + properties: + productName: + type: string + description: The product name related to this credential + example: UserAPI + primaryToken: + type: string + description: The primary token to be used in the next call in the user scope API + example: 3b22980d8d1143c6ba7adf4e55b9a153 + secondaryToken: + type: string + description: >- + The secondary token. Could be usefull if you want to share your + access with someone else. + example: 162ae17fd52044c38cce3388ea5b0c91 + description: Your api credential + registerRequest: + required: + - email + - password + type: object + properties: + email: + type: string + description: Your email. We refuse disposable email. + example: myemail@mycompany.com + password: + type: string + description: > + The password you want to use for your new account. \ + + The password length must be greater or equals to 6 and lower or + equals to 128. \ + + The password must contains at least one number and one special + character + example: I@mW0nder$Full + cultureName: + type: string + description: > + Can be null. Default: en-GB. The culture name you want to use. FYI. + \ + + The email activation will use this culture. + example: en-GB + commercialOwnerUserId: + type: string + description: The user id of your commercial in BeezUP. + format: uuid + example: 47ea14ab-195d-4f9a-a24e-32c329ee40f6 + BeezUP_Common_ErrorResponseMessage: + required: + - errors + type: object + properties: + errors: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_UserErrorMessage' + BeezUP_Common_Email: + pattern: ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$ + type: string + description: The email + format: email + example: paulsimon@mysupercompany.com + BeezUP_Common_UserErrorMessage: + required: + - code + - message + type: object + properties: + docUrl: + $ref: '#/components/schemas/BeezUP_Common_DocUrl' + code: + type: string + description: >- + the error code. The error code can be a pattern containing the + argument's name + example: >- + CatalogImportationAlreadyInProgress(ExecutionId + currentCatalogImportationId) + message: + type: string + description: The error message + example: > + There is already an importation in progress: + b24d0dd8-a561-478a-9b26-34f573f03527 + cultureName: + type: string + description: If the error is translated, the culture name will be indicated + example: en + x-lov: Go2CultureName + arguments: + type: array + description: a dictionary string/object + items: + required: + - name + - value + type: object + properties: + name: + type: string + description: The key of the parameter + example: currentCatalogImportationId + value: + type: object + properties: {} + description: The value of the parameter. Depending to the type. + BeezUP_Common_DocUrl: + type: string + description: The documentation related to this operation. + format: uri + example: https://api-docs.beezup.com/#operation/EnableChannelCatalog + publicChannelIndex: + type: object + properties: + channels: + type: object + additionalProperties: + $ref: '#/components/schemas/links.GetChannelsLink' + description: The key is the country iso code + example: + FRA: + href: /v2/public/channels/FRA + method: GET + DEU: + href: /v2/public/channels/DEU + method: GET + ESP: + href: /v2/public/channels/ESP' + method: GET + ITA: + href: /v2/public/channels/ITA + method: GET + GBR: + href: /v2/public/channels/GBR + method: GET + links: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelsIndexLink' + channelCountryLov: + $ref: '#/components/schemas/links.GetPublicListOfValuesLink' + channelTypeLov: + $ref: '#/components/schemas/links.GetPublicListOfValuesLink' + sectorLov: + $ref: '#/components/schemas/links.GetPublicListOfValuesLink' + example: + self: + href: /v2/public/channels + method: GET + channelCountryLov: + href: /v2/public/lov/www_ChannelCountry + method: GET + channelTypeLov: + href: /v2/public/lov/ChannelType + method: GET + sectorLov: + href: /v2/public/lov/ParamSector + method: GET + links.GetPublicListOfValuesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/public/lov/ChannelType + method: GET + links.GetChannelsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/public/channels/FRA + method: GET + links.GetChannelsIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/public/channels + method: GET + publicChannelInfoList: + type: object + properties: + links: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelsLink' + channels: + type: array + items: + $ref: '#/components/schemas/publicChannelInfo' + publicChannelInfo: + required: + - homeUrl + - logoUrl + - name + - types + type: object + properties: + name: + type: string + description: The channel name + example: Amazon Direct FRA + homeUrl: + type: string + description: The channel home url + format: uri + example: http://www.amazon.fr + logoUrl: + type: string + description: The channel logo url + format: uri + example: >- + http://beezupcdn.blob.core.windows.net/comparators/Amazon%2520Direct%2520FRA.png + types: + type: array + description: The type list related to a channel + example: + - Marketplace + items: + type: string + sectors: + type: array + description: The sector list related to a channel + example: + - BRICOLAGE + - INFO + - GENERALIST + items: + type: string + BeezUP_Common_Link3: + required: + - href + type: object + properties: + label: + type: string + description: >- + The label corresponding to the link. This label is automatically + translated based on the Accept-Language http header. + example: The translated label + docUrl: + $ref: '#/components/schemas/BeezUP_Common_DocUrl' + description: + type: string + description: The description of the link + example: This is a description link + href: + $ref: '#/components/schemas/BeezUP_Common_Href' + operationId: + $ref: '#/components/schemas/BeezUP_Common_OperationId' + method: + $ref: '#/components/schemas/BeezUP_Common_HttpMethod' + parameters: + type: object + additionalProperties: + $ref: '#/components/schemas/BeezUP_Common_LinkParameter3' + urlTemplated: + type: boolean + description: indicates whether the href is templated or not + allRequiredParamsProvided: + type: boolean + description: indicates whether all required params have been provided + allOptionalParamsProvided: + type: boolean + description: indicates whether all optionals params have been provided + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + BeezUP_Common_Href: + type: string + description: Indicate the relative uri for this link + example: >- + /v2/marketplaces/orders/{marketplaceTechnicalCode}/{accountId}/{beezUPOrderId} + BeezUP_Common_OperationId: + type: string + description: The operationId to call. + example: GetOrder + BeezUP_Common_HttpMethod: + type: string + description: Indicate the http method to use on this link + example: GET + default: GET + enum: + - GET + - POST + - PATCH + - DELETE + - PUT + - HEAD + BeezUP_Common_LinkParameter3: + required: + - in + type: object + properties: + label: + type: string + description: >- + The label corresponding to the link parameter. This label is + automatically translated based on the Accept-Language http header. + example: The translated label + value: + type: object + properties: {} + description: >- + The value of the parameter. It can be an integer a string or an + object. + required: + type: boolean + example: true + default: false + in: + $ref: '#/components/schemas/BeezUP_Common_ParameterIn' + type: + $ref: '#/components/schemas/BeezUP_Common_ParameterType' + lovLink: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + lovRequired: + type: boolean + description: >- + If true, you MUST indicate a value from the list of values otherwise + it's a freetext + example: true + description: + type: string + description: description of the parameter + example: the store identifier + schema: + type: string + description: schema of the parameter + example: orderListRequest + properties: + type: object + additionalProperties: + $ref: '#/components/schemas/BeezUP_Common_LinkParameterProperty3' + description: >- + If the parameter is an object with flexible properties + (additionProperties/dictionary), we will describe the properties of + the object. + example: + shipOrder: + type: string + BeezUP_Common_InfoSummaries: + type: object + properties: + successes: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_SuccessSummary' + errors: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_ErrorSummary' + warnings: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_WarningSummary' + informations: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_InfoSummary' + BeezUP_Common_ParameterIn: + type: string + description: | + * path: if the parameter must be pass in the path uri + * header: if the parameter must be passed in http header + * query: if the parameter must be passed in querystring + * body: if the paramter must be passed in the body + example: path + enum: + - path + - header + - query + - body + BeezUP_Common_ParameterType: + type: string + description: The value type of the parameter + example: string + default: string + enum: + - string + - integer + - number + - boolean + - object + - array + - date + - date-time + BeezUP_Common_LOVLink3: + required: + - href + type: object + properties: + href: + type: string + description: Indicate the uri to the list of value + format: uri + example: /v2/public/Go2CultureName + method: + $ref: '#/components/schemas/BeezUP_Common_HttpMethod' + description: Describe the way you have to follow to get access to the LOV + BeezUP_Common_LinkParameterProperty3: + required: + - type + type: object + properties: + label: + type: string + description: >- + The label corresponding to the link parameter property. This label + is automatically translated based on the Accept-Language http + header. + example: The translated label + value: + type: object + properties: {} + description: >- + The value of the parameter. It can be an integer a string or an + object. + required: + type: boolean + example: true + type: + $ref: '#/components/schemas/BeezUP_Common_ParameterType' + lovLink: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + lovRequired: + type: boolean + description: >- + If true, you MUST use indicate a value from the list of values + otherwise it's a freetext + example: true + description: + type: string + description: description of the parameter + example: the store identifier + schema: + type: string + description: schema of the parameter + example: orderListRequest + BeezUP_Common_SuccessSummary: + type: object + properties: + successCode: + type: string + successMessage: + type: string + successArguments: + type: object + additionalProperties: + type: string + propertyName: + type: string + propertyValue: + type: string + objectName: + type: string + BeezUP_Common_ErrorSummary: + type: object + properties: + utcDate: + type: string + format: date-time + errorGuid: + type: string + format: uuid + errorCode: + type: string + errorMessage: + type: string + technicalErrorMessage: + type: string + exceptionDetail: + $ref: '#/components/schemas/BeezUP_Common_ExceptionDetail' + errorArguments: + type: object + additionalProperties: + type: string + propertyName: + type: string + propertyValue: + type: string + objectName: + type: string + source: + type: string + BeezUP_Common_WarningSummary: + type: object + properties: + technicalErrorMessage: + type: string + warningMessage: + type: string + warningCode: + type: string + warningArguments: + type: object + additionalProperties: + type: string + BeezUP_Common_InfoSummary: + type: object + properties: + informationCode: + type: string + informationMessage: + type: string + informationArguments: + type: object + additionalProperties: + type: string + propertyName: + type: string + propertyValue: + type: string + objectName: + type: string + BeezUP_Common_ExceptionDetail: + type: object + properties: + helpLink: + type: string + message: + type: string + stackTrace: + type: string + type: + type: string + publicLovIndex: + type: object + properties: + links: + $ref: '#/components/schemas/publicLovIndexLinks' + publicLovIndexLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetPublicLovIndexLink' + lists: + $ref: '#/components/schemas/publicLovLinks' + publicLovLinks: + type: object + additionalProperties: + $ref: '#/components/schemas/links.GetPublicListOfValuesLink' + description: List of lov link. The key is the list name. + links.GetPublicLovIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/public/lov + method: GET + publicListOfValuesResponse: + type: object + properties: + links: + $ref: '#/components/schemas/publicListOfValuesResponseLinks' + items: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_ListOfValueItem' + publicListOfValuesResponseLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetPublicListOfValuesLink' + BeezUP_Common_ListOfValueItem: + required: + - codeIdentifier + - intIdentifier + type: object + properties: + position: + type: integer + format: int32 + example: 1 + codeIdentifier: + type: string + example: FRA + translationText: + type: string + example: France + intIdentifier: + type: integer + format: int32 + example: 1 + description: This object is used by LOV apis + userLovIndex: + type: object + properties: + links: + $ref: '#/components/schemas/userLovIndexLinks' + userLovIndexLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetUserLovIndexLink' + lists: + $ref: '#/components/schemas/userLovLinks' + userLovLinks: + type: object + additionalProperties: + $ref: '#/components/schemas/links.GetUserListOfValuesLink' + description: List of lov link. The key is the list name. + links.GetUserListOfValuesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/lov/Go2CultureName + method: GET + links.GetUserLovIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/lov + method: GET + userListOfValuesResponse: + type: object + properties: + links: + $ref: '#/components/schemas/userListOfValuesResponseLinks' + items: + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_ListOfValueItem' + userListOfValuesResponseLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetUserListOfValuesLink' + links.logoutLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/security/logout + method: POST + links.getFriendInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/friends/{userId} + method: GET + parameters: + userId: + in: path + type: string + required: true + links.getStandardOffersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/offers + method: GET + links.getOfferLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/offers + method: POST + parameters: + request: + in: body + required: true + type: object + schema: offerRequest + links.getBillingPeriodsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/billingPeriods + method: GET + links.getInvoicesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/invoices + method: GET + links.getUserAccountInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account + method: GET + links.shareStoreLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/customer/stores/51afae05-277e-4902-8b17-5a811a23a2c6/shares + method: POST + parameters: + email: + type: string + in: body + required: true + links.deleteStoreShareLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/stores/51afae05-277e-4902-8b17-5a811a23a2c6/shares/277596c1-a5a9-4cce-9f34-b5906451a98f + method: DELETE + links.getStoresLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/stores + method: GET + links.createStoreLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/stores + method: POST + links.getStoreLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/stores/51afae05-277e-4902-8b17-5a811a23a2c6 + method: GET + links.deleteStoreLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/stores/51afae05-277e-4902-8b17-5a811a23a2c6 + method: DELETE + links.updateStoreLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/stores/51afae05-277e-4902-8b17-5a811a23a2c6 + method: PATCH + links.getStoreSharesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/customer/stores/51afae05-277e-4902-8b17-5a811a23a2c6/shares + method: GET + links.createContractLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/contracts + method: POST + parameters: + request: + in: body + type: object + value: + offerId: '1' + storeCount: '1' + couponDiscountCode: I-LOVE-BEEZUP + couponOfferCode: 04efc310-bc25-4710-a83a-faf200284fe5 + billingPeriodInMonth: '12' + links.saveCreditCardInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/creditCardInfo + method: PUT + links.saveStoreAlertsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/customer/stores/51afae05-277e-4902-8b17-5a811a23a2c6/alerts + method: POST + links.savePersonalInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/personalInfo + method: PUT + links.changeEmailLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/changeEmail + method: POST + links.changePasswordLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/changePassword + method: POST + links.saveCompanyInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/companyInfo + method: PUT + links.saveProfilePictureInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/profilePictureInfo + method: PUT + links.getCreditCardInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/creditCardInfo + method: GET + links.getContractsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/contracts + method: GET + links.reactivateCurrentContractLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/contracts/current/reenableAutoRenewal + method: POST + links.terminateCurrentContractLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/contracts/current/disableAutoRenewal + method: POST + links.deleteNextContractLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/contracts/next + method: DELETE + links.activateUserAccountLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/activate + method: POST + links.getProfilePictureInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer/account/profilePictureInfo + method: GET + links.GetCustomerIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/customer + method: GET + errorResponseMessagePaymentRequiredLinks: + required: + - offer + type: object + properties: + offer: + $ref: '#/components/schemas/links.getOfferLink' + errorResponseMessagePaymentRequired: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + - required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/errorResponseMessagePaymentRequiredLinks' + customerIndex: + required: + - links + - lovLinks + type: object + properties: + links: + $ref: '#/components/schemas/customerIndexLinks' + lovLinks: + $ref: '#/components/schemas/customerIndexLovLinks' + description: The index of the customer API + customerIndexLinks: + required: + - accountInfo + - billingPeriods + - friendInfo + - self + - standardOffers + type: object + properties: + self: + $ref: '#/components/schemas/links.GetCustomerIndexLink' + accountInfo: + $ref: '#/components/schemas/links.getUserAccountInfoLink' + friendInfo: + $ref: '#/components/schemas/links.getFriendInfoLink' + logout: + $ref: '#/components/schemas/links.logoutLink' + stores: + $ref: '#/components/schemas/links.getStoresLink' + billingPeriods: + $ref: '#/components/schemas/links.getBillingPeriodsLink' + standardOffers: + $ref: '#/components/schemas/links.getStandardOffersLink' + getOffer: + $ref: '#/components/schemas/links.getOfferLink' + invoices: + $ref: '#/components/schemas/links.getInvoicesLink' + contracts: + $ref: '#/components/schemas/links.getContractsLink' + description: Gives you want you can do on this API + customerIndexLovLinks: + type: object + properties: + offerLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + activeOfferLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + customerStatusLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + beezUPTimeZoneLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + storeCountryLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + storeSectorLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + countryLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + contractTerminationReasonLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + invoicePaymentStatusLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + storeShares: + required: + - links + - shares + type: object + properties: + links: + $ref: '#/components/schemas/storeSharesLinks' + shares: + type: array + items: + $ref: '#/components/schemas/storeShare' + storeSharesLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.getStoreSharesLink' + share: + $ref: '#/components/schemas/links.shareStoreLink' + storeShare: + required: + - links + - userId + - userRole + type: object + properties: + userId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + userRole: + $ref: '#/components/schemas/storeUserRole' + links: + $ref: '#/components/schemas/storeShareLinks' + storeShareLinks: + type: object + properties: + deleteShare: + $ref: '#/components/schemas/links.deleteStoreShareLink' + description: The different actions you can make on this store share + storeListLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.getStoresLink' + createStore: + $ref: '#/components/schemas/links.createStoreLink' + description: The action links you can do globally on stores + storeList: + required: + - links + - stores + type: object + properties: + links: + $ref: '#/components/schemas/storeListLinks' + stores: + type: array + items: + $ref: '#/components/schemas/store' + storeUserRole: + type: string + description: | + Indicates the role can have a user on a store. + * Owner: Indicates that you are the owner of this store + * User: Indicates that you are a simple user on this store + example: User + enum: + - Owner + - User + storeStatus: + type: string + description: | + The store status + * Active: When the store is active + * SystemBlocked: When the store is blocked by the system + * UserBlocked: When the store is blocked on GO not on the system + example: Active + enum: + - Active + - SystemBlocked + - UserBlocked + accountStatus: + type: string + description: > + The account status + + * Active: When the account is active + + * SystemBlocked: When all stores on the account are blocked by the + system + + * UserBlocked: When all stores on the account are blocked on GO not on + the system + + * NotActivated: When the email is not verified + example: Active + enum: + - Active + - SystemBlocked + - UserBlocked + - NotActivated + store: + required: + - countryIsoCodeAlpha3 + - creationUtcDate + - currencyCode + - goVersion + - isTest + - links + - name + - offerId + - offerName + - ownerUserId + - sectors + - shareCount + - status + - storeId + - url + - userRole + type: object + properties: + storeId: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + name: + $ref: '#/components/schemas/storeName' + url: + $ref: '#/components/schemas/storeUrl' + countryIsoCodeAlpha3: + $ref: '#/components/schemas/storeCountryIsoCodeAlpha3' + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + sectors: + $ref: '#/components/schemas/storeSectors' + userRole: + $ref: '#/components/schemas/storeUserRole' + status: + $ref: '#/components/schemas/storeStatus' + ownerUserId: + type: string + description: The user id of the owner of the store + format: guid + example: 00000000-0000-0000-0000-000000000000 + offerId: + $ref: '#/components/schemas/offerId' + offerName: + type: string + description: The offer Name + example: Premium + shareCount: + type: integer + description: The share count related to this store + example: 5 + creationUtcDate: + type: string + description: The creation date of the store + format: date-time + example: 2017-04-01T22:30:00.000Z + goVersion: + type: integer + description: The version of GO to use + format: int32 + example: 2 + links: + $ref: '#/components/schemas/storeLinks' + isTest: + type: boolean + description: Is the store a test or a production store + storeLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.getStoreLink' + deleteStore: + $ref: '#/components/schemas/links.deleteStoreLink' + updateStore: + $ref: '#/components/schemas/links.updateStoreLink' + shares: + $ref: '#/components/schemas/links.getStoreSharesLink' + share: + $ref: '#/components/schemas/links.shareStoreLink' + description: The action links for this store + storeName: + type: string + description: The store name. Must be unique. + example: My Store + storeUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: The url of your store + example: http://www.mystore.com + storeCountryIsoCodeAlpha3: + type: string + description: >- + The country iso code alpha 3 based on the list of values + /user/lov/StoreCountry + example: DEU + x-lov: StoreCountry + storeSectors: + type: array + description: The store's sectors based on the list of values /user/lov/ParamSector + example: + - ANIMALERIE + - AUTOMOTO + items: + $ref: '#/components/schemas/storeSector' + storeSector: + type: string + description: The store's sector based on the list of values /user/lov/ParamSector + example: ANIMALERIE + x-lov: ParamSector + contractId: + type: string + description: Your contract identifier + format: guid + example: 7098487a-86f6-4322-b8a5-b67f7363b3e7 + invoiceNumber: + type: string + description: Your invoice number + example: B1234 + createStoreRequest: + required: + - countryIsoCodeAlpha3 + - name + - sectors + - url + type: object + properties: + id: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + name: + $ref: '#/components/schemas/storeName' + url: + $ref: '#/components/schemas/storeUrl' + countryIsoCodeAlpha3: + $ref: '#/components/schemas/storeCountryIsoCodeAlpha3' + sectors: + $ref: '#/components/schemas/storeSectors' + description: >- + The request to create a store. The store identifier is optional, if null + it will be automatically computed. + updateStoreRequest: + required: + - name + - sectors + - url + type: object + properties: + name: + $ref: '#/components/schemas/storeName' + url: + $ref: '#/components/schemas/storeUrl' + sectors: + $ref: '#/components/schemas/storeSectors' + functionalityRightInfo: + required: + - functionalityCode + type: object + properties: + functionalityCode: + type: string + description: The functionality code + example: COMPAMANA + maxValueInterger: + type: integer + description: The max value for this functionality code considering your rights + example: 10 + unlimited: + type: boolean + description: If you can use this functionality unlimitedly + example: true + description: Describe the rights for a functionality + invoiceListLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.getInvoicesLink' + invoiceList: + required: + - invoices + - links + type: object + properties: + links: + $ref: '#/components/schemas/invoiceListLinks' + invoices: + type: array + example: + - invoiceDate: 2016-05-01T00:00:00.000Z + contractId: 7098487a-86f6-4322-b8a5-b67f7363b3e7 + invoiceNumber: B1234 + amount: '101' + amountToBePaid: '0' + currencyCode: EUR + paymentStatus: Paid + dueDate: 2016-05-10T00:00:00.000Z + invoiceUrl: >- + https://beezupbilling.blob.core.windows.net/invoicepdf/2000/CustomerUserId_00000000-0000-0000-0000-000000000000/ContractId_00000000-0000-0000-0000-000000000000/2000-01-01_B1234.pdf + items: + $ref: '#/components/schemas/invoice' + invoicePaymentStatus: + type: string + description: The payment status + example: Paid + enum: + - Paid + - NotPaid + - PartiallyPaid + - Loss + invoice: + required: + - amount + - amountToBePaid + - contractId + - currencyCode + - dueDate + - invoiceDate + - invoiceNumber + - paymentStatus + type: object + properties: + invoiceDate: + type: string + description: The invoice date + format: date + example: 2016-05-01T00:00:00.000Z + contractId: + $ref: '#/components/schemas/contractId' + invoiceNumber: + $ref: '#/components/schemas/invoiceNumber' + amount: + type: number + description: The amount of your invoice + format: double + example: 101.42 + amountToBePaid: + type: number + description: The remaining amount to be paid for this invoice + format: double + example: 0 + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + paymentStatus: + $ref: '#/components/schemas/invoicePaymentStatus' + dueDate: + type: string + format: date + example: 2016-05-10T00:00:00.000Z + invoiceUrl: + type: string + description: The url of the invoice document + format: uri + example: >- + https://beezupbilling.blob.core.windows.net/invoicepdf/2000/CustomerUserId_00000000-0000-0000-0000-000000000000/ContractId_00000000-0000-0000-0000-000000000000/2000-01-01_B1234.pdf + friendEmail: + pattern: ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$ + type: string + description: Your friend's user email + format: email + example: humphray.bogart@yahoo.ma + friendCountryIsoCodeAlpha3: + type: string + description: Your friend's user country iso code alpha 3 + example: USA + x-lov: Country + friendProfilePictureUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: Your friend's user profile picture url + example: >- + https://www.biography.com/.image/c_fill,cs_srgb,dpr_1.0,g_face,h_300,q_80,w_300/MTE4MDAzNDEwNDU3MjMyOTEw/humphrey-bogart-9217486-1-402.jpg + userFriendInfo: + required: + - company + - countryIsoCodeAlpha3 + - email + - firstName + - lastName + - userId + type: object + properties: + userId: + type: string + description: Your friend's user id + format: guid + example: 00c4a9d2-fc8e-4b3d-8e52-c4f276245bc1 + lastName: + type: string + description: Your friend's user last name + example: Humphrey + firstName: + type: string + description: Your friend's user first name + example: Bogart + email: + $ref: '#/components/schemas/friendEmail' + profilePictureUrl: + $ref: '#/components/schemas/friendProfilePictureUrl' + countryIsoCodeAlpha3: + $ref: '#/components/schemas/friendCountryIsoCodeAlpha3' + company: + type: string + description: Your friend's user company name + example: World company + whatIDo: + type: string + description: Your friend's user occupation in his company + example: I'm an actor... + createContract: + allOf: + - $ref: '#/components/schemas/offerRequest' + createContractResponseLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.createContractLink' + contracts: + $ref: '#/components/schemas/links.getContractsLink' + createContractResponse: + type: object + properties: + links: + $ref: '#/components/schemas/createContractResponseLinks' + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + contractsLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.getContractsLink' + create: + $ref: '#/components/schemas/links.createContractLink' + currentContractInfoLinks: + type: object + properties: + disable: + $ref: '#/components/schemas/links.terminateCurrentContractLink' + reenable: + $ref: '#/components/schemas/links.reactivateCurrentContractLink' + nextContractInfoLinks: + type: object + properties: + delete: + $ref: '#/components/schemas/links.deleteNextContractLink' + currentContractInfo: + allOf: + - $ref: '#/components/schemas/contractInfo' + - required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/currentContractInfoLinks' + description: Get the conditions of your current contract + contracts: + required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/contractsLinks' + current: + $ref: '#/components/schemas/currentContractInfo' + next: + $ref: '#/components/schemas/nextContractInfo' + nextContractInfo: + allOf: + - $ref: '#/components/schemas/contractInfo' + - required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/nextContractInfoLinks' + description: Get the conditions of your next contract + contractInfo: + type: object + properties: + trialPeriodInMonth: + type: integer + description: The trial period in month + format: int32 + billingPeriodPercentDiscount: + type: number + description: The percent discount related to the billing period + format: double + discountDurationInMonth: + type: integer + description: The discount duration in month + format: int32 + percentDiscount: + type: number + description: The percent of the discount + format: double + offerId: + $ref: '#/components/schemas/offerId' + storeCount: + $ref: '#/components/schemas/storeCount' + startUtcDate: + type: string + description: The start date of your contract + format: date-time + commitmentCalculatedFinishUtcDate: + type: string + description: The calculated end date of commitment + format: date-time + billingPeriodInMonth: + type: integer + description: The billing period in month + format: int32 + fixedPrice: + type: number + description: The fixed price of your contract + format: double + offerName: + type: string + description: The offer name based on /offers + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + contractId: + $ref: '#/components/schemas/contractId' + commitmentPeriodInMonth: + type: integer + description: The commitment period in month + format: int32 + clickIncluded: + type: integer + description: The click included + format: int32 + additionalClickPrice: + type: number + description: Additional click price + format: double + ipUserCreation: + type: string + description: The IP of the user who creates the contract + ipUserModification: + type: string + description: The IP of the user who modified the contract + fixedAndVariableClickInfo: + $ref: '#/components/schemas/fixedAndVariableClickModelInfo' + variableModelInfo: + $ref: '#/components/schemas/variableModelInfo' + isCommitmentRenewalAutomatically: + type: boolean + description: Is commitment is automatically renewed + discountEndUtcDate: + type: string + description: The end of your discount + format: date-time + isModifiableContract: + type: boolean + description: Is the contract is modifiable ? + description: Describe the conditions of a contract + clickIncludedAndAdditionalClickPrice: + type: object + properties: + clickIncluded: + type: integer + description: The click included + format: int32 + additionalClickPrice: + type: number + description: The additional click price + format: double + clickIncludedAndVariablePrice: + type: object + properties: + clickIncluded: + type: integer + description: Click included + format: int32 + variablePrice: + type: number + description: The pricing applied for this range + format: double + terminateContract: + required: + - contractTerminationReasonType + type: object + properties: + contractTerminationReasonType: + $ref: '#/components/schemas/contractTerminationReasonType' + contractTerminationReason: + $ref: '#/components/schemas/contractTerminationReason' + description: The contract termination info + offerId: + minimum: 1 + type: integer + description: The offer id based on /offers. Not a free offer of course. + format: int32 + example: 1 + storeCount: + minimum: 1 + type: integer + description: The store count you want to have in your contract. + format: int32 + example: 1 + couponDiscountCode: + type: string + description: The coupon discount code + example: I-LOVE-BEEZUP + couponOfferCode: + type: string + description: Your special coupon offer identifier + format: guid + example: 04efc310-bc25-4710-a83a-faf200284fe5 + billingPeriodInMonth: + minimum: 1 + type: integer + description: Can be null. The billing period in month based on /billingPeriods + format: int32 + example: 12 + contractTerminationReasonType: + type: integer + description: >- + The contract termination reason type identifier, if your current + contract is scheduled to be terminated. The value is based on the list + of values /user/lov/ContractTerminationReason + format: int32 + example: 1 + x-lov: ContractTerminationReason + contractTerminationReason: + type: string + description: >- + The termination reason, if your current contract is scheduled to be + terminated. + example: I'm crazy, I want to leave your splendid service... + offerRequest: + required: + - billingPeriodInMonth + - offerId + - storeCount + type: object + properties: + offerId: + $ref: '#/components/schemas/offerId' + storeCount: + $ref: '#/components/schemas/storeCount' + couponDiscountCode: + $ref: '#/components/schemas/couponDiscountCode' + couponOfferCode: + $ref: '#/components/schemas/couponOfferCode' + billingPeriodInMonth: + $ref: '#/components/schemas/billingPeriodInMonth' + paymentMethod: + type: string + description: Payment method + default: OnlinePayment + enum: + - Transfer + - Debit + - Paypal + - Check + - CreditNote + - Loss + - OnlinePayment + offer: + type: object + properties: + content: + $ref: '#/components/schemas/offerContent' + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + links: + $ref: '#/components/schemas/offerLinks' + offerLinks: + type: object + properties: + createContract: + $ref: '#/components/schemas/links.createContractLink' + description: The different actions you can make on this offer + offerContent: + required: + - contractBillingPeriodInfo + - contractBonusInfo + - contractClickInfo + - contractCommitmentInfo + - contractDiscountInfo + - contractMoneyInfo + - contractStoreInfo + - notifyVatExemption + - previousFixPeriodInvoiceProrataInfo + type: object + properties: + previousFixPeriodInvoiceProrataInfo: + $ref: '#/components/schemas/previousFixPeriodInvoiceProrataInfo' + contractBillingPeriodInfo: + $ref: '#/components/schemas/contractBillingPeriodInfo' + contractClickInfo: + $ref: '#/components/schemas/contractClickInfo' + contractCommitmentInfo: + $ref: '#/components/schemas/contractCommitmentInfo' + contractDiscountInfo: + $ref: '#/components/schemas/contractDiscountInfo' + contractMoneyInfo: + $ref: '#/components/schemas/contractMoneyInfo' + contractStoreInfo: + $ref: '#/components/schemas/contractStoreInfo' + contractBonusInfo: + $ref: '#/components/schemas/contractBonusInfo' + contractTerminationReasonType: + $ref: '#/components/schemas/contractTerminationReasonType' + contractTerminationReason: + $ref: '#/components/schemas/contractTerminationReason' + notifyVatExemption: + type: boolean + description: >- + Internal usage: Indicates if we have to notify you about VAT + exemption. + example: true + previousFixPeriodInvoiceProrataInfo: + type: object + properties: + computedProrataToBeDeducted: + type: number + description: The prorata amount + format: double + example: 194.66 + invoiceNumber: + type: string + description: The previous invoice number + example: B1234 + amountToBePaid: + type: number + description: The amount to be payed of the previous invoice + format: double + example: 0 + amountAfterTax: + type: number + description: The amout after tax of the previous invoice + format: double + example: 101.42 + contractId: + type: string + description: The contract id related to the previous invoice + format: guid + example: 8a7fbdec-9e71-472e-9974-27d5c1d57cf8 + fixedPeriodEndDate: + type: string + description: The fixed end period of the previous invoice + format: date + example: 2017-05-01T00:00:00.000Z + fixedPeriodStartDate: + type: string + description: The fixed start period of the previous invoice + format: date + example: 2017-04-01T00:00:00.000Z + description: Describe the prorata info based on your previous invoice + contractBillingPeriodInfo: + type: object + properties: + amountBillingPeriodDiscount: + type: number + description: The amount discounted related to the billing period + format: double + example: 20 + billingPeriodPercentDiscount: + type: number + description: The discount percent related to the billing period + format: double + example: 10 + billingPeriodInMonth: + $ref: '#/components/schemas/billingPeriodInMonth' + description: Describe the billing period information related to the offer. + contractClickInfo: + type: object + properties: + additionalClickPrice: + type: number + description: The addition click price in the offer + format: double + example: 0.001 + clickIncluded: + type: integer + description: The click included in the offer + format: int32 + example: 5000 + initialOfferClickIncluded: + type: integer + description: The click included in your current contract + format: int32 + example: 5000 + description: Describe the click information related to the offer. + contractCommitmentInfo: + type: object + properties: + commitmentCalculatedFinishDate: + type: string + description: The commitment end date related to the offer + format: date + example: 2017-06-02T00:00:00.000Z + newContractStartDate: + type: string + description: The start date related to the offer + format: date-time + commitmentPeriodInMonth: + type: integer + description: The commitment period in month related to the offer + format: int32 + example: 1 + trialPeriodInMonth: + type: integer + description: The trial period in month related to the offer + format: int32 + example: 0 + trialPeriodFinishDate: + type: string + description: The trial period end date related to the offer + format: date + paymentDelayInDays: + type: integer + description: The payment delay in days related to the offer + format: int32 + example: 1 + offerId: + $ref: '#/components/schemas/offerId' + offerName: + type: string + description: The offer Name + example: Premium + currentContractId: + type: string + description: Your current contract id + format: guid + example: dce56457-aa23-478d-8d76-b56eb9be799f + commercialUserId: + type: string + description: Your current commercial user id + format: guid + example: 0ddc2b79-10fe-4071-8161-42faa897082f + model: + type: string + description: 'Interal usage: Old offer type. The model description' + example: BLABLA + currentContractTerminationDate: + type: string + description: The current contract termination date + format: date + example: 2017-06-02T00:00:00.000Z + requestedPaymentMethod: + $ref: '#/components/schemas/paymentMethod' + currentCustomerPaymentMethod: + $ref: '#/components/schemas/paymentMethod' + contractType: + type: integer + description: 'Internal usage: Old offer type. Your contract type' + format: int32 + example: 1234 + isModelMustBeTransmittedInNewContract: + type: boolean + description: >- + Internal usage: Old offer type. Is the current contract model needs + to be converted into a new contract type + example: false + fixedAndVariableClickInfo: + $ref: '#/components/schemas/fixedAndVariableClickModelInfo' + variableModelInfo: + $ref: '#/components/schemas/variableModelInfo' + paymentMethodAuthorized: + $ref: '#/components/schemas/paymentMethod' + couponOfferCode: + $ref: '#/components/schemas/couponOfferCode' + commercialCreatorUserId: + type: string + description: The commercial that is responsible of the creation of your account + format: guid + example: 6e07814d-26a9-494b-91b2-e5ed0b9aba8c + minBillingPeriodInMonths: + type: integer + description: The minimum billing period in month authorized for this offer. + format: int32 + example: 1 + isCustomerWantsToTerminateHisContract: + type: boolean + description: If true, this means you want to leave us and that's sad... :'-( + example: false + description: Describe the commitment information related to the offer. + contractDiscountInfo: + type: object + properties: + amountCodePromoDiscountPerMonth: + type: number + description: The amount discounted per month + format: double + example: 101.42 + discountDurationInMonth: + type: integer + description: Duration of the discount in month + format: int32 + example: 1 + percentDiscount: + type: number + description: Percentage of the discount + format: double + example: 20 + promotionalCodeValidity: + $ref: '#/components/schemas/promotionalCodeValidity' + amountCodePromoDiscount: + type: number + description: The discount amount + format: double + example: 101.42 + couponDiscountCode: + type: string + description: The discount code + example: I-LOVE-BEEZUP + couponDiscountId: + type: integer + description: 'Internal use: The discount id' + format: int32 + example: 1 + isCouponDiscountLinkedToCouponOffer: + type: boolean + description: Is this discount is related to a coupon offer + example: true + customerHasActualDiscount: + type: boolean + description: Do you have currently a discount on your contract ? + example: true + description: Describe the discount information related to the offer. + contractMoneyInfo: + type: object + properties: + amountExcludingTaxesAndExcludingCodePromoDiscountIncludingBillingPeriodDiscount: + type: number + description: >- + The amount excluding taxes and excluding code promo discount + including billing period discount. + format: double + amountExcludingTaxesIncludingDiscounts: + type: number + description: The amount excluding taxes including discounts. + format: double + amountTaxesExcludingDiscountIncludingBillingPeriodDiscount: + type: number + description: The taxes excluding discount including billing period discount. + format: double + amountIncludingTaxesExcludingDiscountIncludingBillingPeriodDiscount: + type: number + description: >- + The amount including taxes excluding discount including billing + period discount. + format: double + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + vatPercent: + type: number + description: The VAT percent. + format: double + amountExcludingTaxesIncludingDiscountsPerMonth: + type: number + description: The amount excluding taxes including discounts per month. + format: double + amountExcludingTaxesAndExcludingDiscounts: + type: number + description: The amount excluding taxes and excluding discounts. + format: double + amountTaxesIncludingDiscounts: + type: number + description: Taxes including discounts. + format: double + amountIncludingTaxesIncludingDiscounts: + type: number + description: The amount including taxes including discounts. + format: double + initialOfferFixedPrice: + type: number + description: The initial offer fixed price. + format: double + description: Describe the pricing information related to the offer. + contractStoreInfo: + type: object + properties: + storeCount: + $ref: '#/components/schemas/storeCount' + maxStoreCount: + type: integer + description: The maximum store count related to the offer. + format: int32 + minStoreCount: + type: integer + description: The minimum store count related to the offer. + format: int32 + ownedStoreCount: + type: integer + description: The owned store count. + format: int32 + additionalStorePrice: + type: number + description: The additional store price. + format: double + storeIncluded: + type: integer + description: The store count included in the offer. + format: int32 + description: Describe the store information related to the offer. + contractBonusInfo: + required: + - bonuses + type: object + properties: + bonuses: + type: array + items: + $ref: '#/components/schemas/bonusInfo' + description: Describe the bonus information related to your current contract. + fixedAndVariableClickModelInfo: + required: + - clickIncludedAndAdditionalClickPrices + type: object + properties: + clickIncludedAndAdditionalClickPrices: + type: array + items: + $ref: '#/components/schemas/clickIncludedAndAdditionalClickPrice' + description: >- + Internal usage: Old offer type. Describe the fix and variable model + information + variableModelInfo: + required: + - clickIncludedAndVariablePrices + - overflowClickCount + - overflowClickPrice + type: object + properties: + clickIncludedAndVariablePrices: + type: array + description: Click included with variable pricing information + items: + $ref: '#/components/schemas/clickIncludedAndVariablePrice' + overflowClickCount: + type: integer + description: The overflow click count + format: int32 + overflowClickPrice: + type: number + description: The overflow click price + format: double + description: >- + Internal usage: Old offer type. Describe the fix and variable model + information + bonusInfo: + required: + - amount + - bonusType + type: object + properties: + bonusType: + $ref: '#/components/schemas/bonusType' + amount: + type: number + format: double + example: 12.34 + lastName: + type: string + description: Your last name + example: Simon + firstName: + type: string + description: Your first name + example: Paul + phoneNumber: + type: string + description: Your phone number + example: '5551234' + address: + type: string + description: Your address + example: 21 jump street + postalCode: + type: string + description: Your address postal code + example: '13014' + city: + type: string + description: Your address city + example: New-York + company: + type: string + description: Your company name + example: My super company + vatNumber: + type: string + description: >- + Your company VATNumber. Used for french company. This number is checked + with official web service before being saved. + example: '1234567890' + accountingEmails: + type: array + description: Your company accounting emails + example: + - myaccountemail@mysupercompany.com + items: + $ref: '#/components/schemas/BeezUP_Common_Email' + profilePictureUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: Indicate the url of your picture profil + example: >- + https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Marlon_Brando_%28cropped%29.jpg/220px-Marlon_Brando_%28cropped%29.jpg + profilePictureSelected: + type: string + description: >- + Your profile picture choice about usage of gravatar picture, initials + picture or uploaded picture. + example: initials + enum: + - gravatar + - initials + - uploaded + whatIDo: + type: string + description: Your role in your company + example: I'm the Manager on this company + beezUPTimeZoneId: + type: integer + description: >- + The time zone identifier based on the list of values + /v2/user/lov/BeezUPTimeZone + format: int32 + example: 79 + x-lov: BeezUPTimeZone + cardNumber: + type: string + description: Card number + example: '1234567890091234' + cardVerificationCode: + type: string + description: Card Verification Code + example: '123' + expirationMonth: + maximum: 12 + minimum: 1 + type: integer + description: Expiration Month + format: int32 + example: 12 + expirationYear: + maximum: 9000 + minimum: 2017 + type: integer + description: Expiration Year + format: int32 + example: 2017 + accountInfoLinks: + required: + - changeEmail + - changePassword + - getCreditCardInfo + - getProfilePictureInfo + - saveCompanyInfo + - saveCreditCardInfo + - savePersonalInfo + - saveProfilePictureInfo + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.getUserAccountInfoLink' + savePersonalInfo: + $ref: '#/components/schemas/links.savePersonalInfoLink' + changeEmail: + $ref: '#/components/schemas/links.changeEmailLink' + changePassword: + $ref: '#/components/schemas/links.changePasswordLink' + saveCompanyInfo: + $ref: '#/components/schemas/links.saveCompanyInfoLink' + getProfilePictureInfo: + $ref: '#/components/schemas/links.getProfilePictureInfoLink' + saveProfilePictureInfo: + $ref: '#/components/schemas/links.saveProfilePictureInfoLink' + getCreditCardInfo: + $ref: '#/components/schemas/links.getCreditCardInfoLink' + saveCreditCardInfo: + $ref: '#/components/schemas/links.saveCreditCardInfoLink' + activateUserAccount: + $ref: '#/components/schemas/links.activateUserAccountLink' + description: The different actions you can make on this account + accountInfo: + required: + - email + - links + - status + - userId + type: object + properties: + userId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + email: + $ref: '#/components/schemas/BeezUP_Common_Email' + personalInfo: + $ref: '#/components/schemas/personalInfo' + status: + $ref: '#/components/schemas/accountStatus' + companyInfo: + $ref: '#/components/schemas/companyInfo' + profilePictureUrl: + $ref: '#/components/schemas/profilePictureUrl' + links: + $ref: '#/components/schemas/accountInfoLinks' + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + personalInfo: + required: + - beezUPTimeZoneId + - firstName + - lastName + - phoneNumber + type: object + properties: + lastName: + $ref: '#/components/schemas/lastName' + firstName: + $ref: '#/components/schemas/firstName' + phoneNumber: + $ref: '#/components/schemas/phoneNumber' + whatIDo: + $ref: '#/components/schemas/whatIDo' + beezUPTimeZoneId: + $ref: '#/components/schemas/beezUPTimeZoneId' + changeEmailRequest: + required: + - newEmail + type: object + properties: + newEmail: + $ref: '#/components/schemas/BeezUP_Common_Email' + changePasswordRequest: + required: + - newPassword + - oldPassword + type: object + properties: + oldPassword: + type: string + description: Your current password + format: password + newPassword: + type: string + description: >- + Your new password. Which must respect the same constraints as the + user registeration + format: password + companyInfo: + required: + - address + - city + - company + - countryIsoCodeAlpha3 + - postalCode + type: object + properties: + address: + $ref: '#/components/schemas/address' + postalCode: + $ref: '#/components/schemas/postalCode' + city: + $ref: '#/components/schemas/city' + countryIsoCodeAlpha3: + $ref: '#/components/schemas/BeezUP_Common_CountryIsoCodeAlpha3' + company: + $ref: '#/components/schemas/company' + vatNumber: + $ref: '#/components/schemas/vatNumber' + accountingEmails: + $ref: '#/components/schemas/accountingEmails' + profilePictureInfoResponseLinks: + required: + - save + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.getProfilePictureInfoLink' + save: + $ref: '#/components/schemas/links.saveProfilePictureInfoLink' + profilePictureInfoResponse: + required: + - links + - profilePictureInfo + type: object + properties: + profilePictureInfo: + $ref: '#/components/schemas/profilePictureInfoWithDefault' + links: + $ref: '#/components/schemas/profilePictureInfoResponseLinks' + profilePictureInfoWithDefault: + allOf: + - $ref: '#/components/schemas/profilePictureInfo' + - required: + - gravatarProfilePictureUrl + - initialsProfilePictureUrl + type: object + properties: + initialsProfilePictureUrl: + $ref: '#/components/schemas/initialsProfilePictureUrl' + gravatarProfilePictureUrl: + $ref: '#/components/schemas/gravatarProfilePictureUrl' + initialsProfilePictureUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: Indicate the url of your picture profil based on your initials + example: https://dummyimage.com/50x50/000000/fff&text=AM + gravatarProfilePictureUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: Indicate the url of your picture profil based on gravatar + example: https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?d=mm + profilePictureInfo: + required: + - profilePictureSelected + type: object + properties: + profilePictureUrl: + $ref: '#/components/schemas/profilePictureUrl' + profilePictureSelected: + $ref: '#/components/schemas/profilePictureSelected' + creditCardInfoResponseLinks: + required: + - saveCreditCardInfo + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.getCreditCardInfoLink' + saveCreditCardInfo: + $ref: '#/components/schemas/links.saveCreditCardInfoLink' + description: The different actions you can make on this offer + creditCardInfoResponse: + required: + - currentPaymentMethod + - links + type: object + properties: + links: + $ref: '#/components/schemas/creditCardInfoResponseLinks' + currentPaymentMethod: + $ref: '#/components/schemas/paymentMethod' + creditCardInfo: + $ref: '#/components/schemas/creditCardInfoWithCardType' + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + creditCardInfo: + required: + - cardNumber + - cardVerificationCode + - expirationMonth + - expirationYear + type: object + properties: + cardNumber: + $ref: '#/components/schemas/cardNumber' + cardVerificationCode: + $ref: '#/components/schemas/cardVerificationCode' + expirationMonth: + $ref: '#/components/schemas/expirationMonth' + expirationYear: + $ref: '#/components/schemas/expirationYear' + creditCardInfoWithCardType: + required: + - cardNumber + - cardType + - expirationMonth + - expirationYear + type: object + properties: + cardNumber: + $ref: '#/components/schemas/cardNumber' + expirationMonth: + $ref: '#/components/schemas/expirationMonth' + expirationYear: + $ref: '#/components/schemas/expirationYear' + cardType: + type: string + description: 'Your credit card type. Example: VISA, MasterCard, etc...' + example: VISA + storeAlerts: + type: object + properties: + alerts: + type: array + example: + - alertId: '8' + alertName: NoImportSinceXDays + isActive: 'true' + properties: + - propertyId: '2' + propertyValidationExpression: \b0*([1-9]|[12][0-9]|30)\b + propertyValue: '2' + items: + $ref: '#/components/schemas/storeAlert' + alertId: + type: integer + description: Alert identifier + format: int32 + example: 8 + alertName: + type: string + description: The alert name + example: NoImportSinceXDays + alertEnabled: + type: boolean + description: Is the alert enable ? + example: true + storeAlert: + required: + - alertId + - alertName + - enabled + - links + type: object + properties: + links: + $ref: '#/components/schemas/storeAlertLinks' + alertId: + $ref: '#/components/schemas/alertId' + alertName: + $ref: '#/components/schemas/alertName' + enabled: + $ref: '#/components/schemas/alertEnabled' + properties: + type: array + description: The current configuration properties of the alert + example: + - propertyId: '2' + propertyValidationExpression: \b0*([1-9]|[12][0-9]|30)\b + propertyValue: '2' + items: + $ref: '#/components/schemas/storeAlertPropertyInfo' + storeAlertLinks: + type: object + properties: + save: + $ref: '#/components/schemas/links.saveStoreAlertsLink' + description: The different actions you can make on this alert + alertPropertyId: + type: integer + description: The property identifier of the alert + format: int32 + example: 2 + alertPropertyValue: + type: string + description: The property value + example: '2' + storeAlertPropertyInfo: + allOf: + - $ref: '#/components/schemas/storeAlertProperty' + - required: + - propertyName + type: object + properties: + propertyName: + type: string + description: The property name of the alert + example: NbDays + propertyValidationExpression: + type: string + description: The regular expression related to the alert property + example: \b0*([1-9]|[12][0-9]|30)\b + saveStoreAlertsRequest: + type: object + additionalProperties: + $ref: '#/components/schemas/saveStoreAlertRequest' + description: The key is the alert identifier (alertId) + saveStoreAlertRequest: + required: + - enabled + type: object + properties: + enabled: + $ref: '#/components/schemas/alertEnabled' + properties: + type: array + description: Properties to configure the alert + example: + - propertyId: '2' + propertyValue: '3' + items: + $ref: '#/components/schemas/storeAlertProperty' + storeAlertProperty: + required: + - propertyId + - propertyValue + type: object + properties: + propertyId: + $ref: '#/components/schemas/alertPropertyId' + propertyValue: + $ref: '#/components/schemas/alertPropertyValue' + standardOffersLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.getStandardOffersLink' + standardOffers: + required: + - functionalities + - links + - offers + type: object + properties: + links: + $ref: '#/components/schemas/standardOffersLinks' + offers: + type: array + description: All standard offers + example: + - additionalClickPrice: '0' + includedClick: '1200' + isMostPopular: 'true' + name: Wonder offer + offerId: '1234' + fixedPrice: '101' + currencyCode: EUR + position: '1' + functionalities: + - functionalityCode: MARKETMANA + maxValueInteger: '4' + unlimited: 'false' + text: Marketplace management + items: + $ref: '#/components/schemas/standardOffer' + functionalities: + type: array + description: All functionalities... + example: + - code: MARKETMANA + order: '1' + items: + $ref: '#/components/schemas/functionality' + standardOfferLinks: + type: object + properties: + getOffer: + $ref: '#/components/schemas/links.getOfferLink' + standardOffer: + required: + - links + - name + - offerId + type: object + properties: + offerId: + type: integer + description: The offer Id + format: int32 + example: 1234 + name: + type: string + description: The offer name + example: Wonder offer + additionalClickPrice: + type: number + description: The additional click price + format: double + example: 0.1234 + includedClick: + type: integer + description: The included click + format: int32 + example: 1200 + isMostPopular: + type: boolean + description: UI purpose. Is the offer is the most popular + example: true + isOldOffer: + type: boolean + description: Is an old offer + example: false + fixedPrice: + type: number + description: The fixed price of the offer + format: double + example: 101.42 + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + position: + type: integer + description: UI purpose. The position of the offer + format: int32 + example: 1 + functionalities: + type: array + example: + - functionalityCode: MARKETMANA + maxValueInteger: '4' + unlimited: 'false' + text: Marketplace management + items: + $ref: '#/components/schemas/offerFunctionality' + links: + $ref: '#/components/schemas/standardOfferLinks' + functionality: + required: + - code + - order + type: object + properties: + code: + type: string + description: The functionality code + example: MARKETMANA + order: + type: integer + description: 'UI purpose: Indicate the position of the functionality' + format: int32 + example: 1 + offerFunctionality: + required: + - functionalityCode + - unlimited + type: object + properties: + functionalityCode: + type: string + description: The functionality code + example: MARKETMANA + maxValueInteger: + type: integer + description: The max value in integer for this feature in this offer + format: int32 + example: 4 + unlimited: + type: boolean + description: Is this feature is unlimited for this offer? + example: false + text: + type: string + description: A description text of this feature + example: Marketplace management + billingPeriodListLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.getBillingPeriodsLink' + billingPeriodList: + required: + - billingPeriods + - links + type: object + properties: + links: + $ref: '#/components/schemas/billingPeriodListLinks' + billingPeriods: + type: array + description: The billing period list + example: + - billingPeriodInMonth: '12' + discountPercentage: '20' + items: + $ref: '#/components/schemas/billingPeriod' + billingPeriod: + required: + - billingPeriodInMonth + - discountPercentage + type: object + properties: + billingPeriodInMonth: + type: integer + description: The billing period in month + format: int32 + example: 12 + discountPercentage: + type: number + description: The discount percentage related to this billing period + format: double + example: 20 + promotionalCodeValidity: + type: string + description: Indicate the validaty of the discount + example: Valid + enum: + - None + - Valid + - Invalid + - ExpiredOrInactive + bonusType: + type: string + enum: + - OnlinePaymentMethodBonus + - PreviousInvoiceProrataBonus + - PreviousContractBonus + zendeskToken: + type: object + properties: + token: + type: string + description: A JWT token build from your name and email to use on Zendesk + example: >- + eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c + description: JWT token to access Zendesk restricted help center + BeezUP_Common_UserId: + type: string + description: The user identifier + format: guid + example: 8a7fbdec-9e71-472e-9974-27d5c1d57cf8 + BeezUP_Common_StoreId: + type: string + description: The store identifier + format: guid + example: 64f43358-63a1-47f7-97ec-0301fc39956b + BeezUP_Common_CountryIsoCodeAlpha3: + type: string + description: >- + The country iso code alpha 3 (ISO + 3166-1_alpha-3) + example: FRA + x-lov: Country + BeezUP_Common_CurrencyCode: + type: string + description: > + The currency code (ISO + 4217) + example: EUR + links.Catalog_ComputeExpressionLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns/computeExpression + method: POST + parameters: + request: + in: body + required: true + type: object + schema: computeExpressionRequest + links.Catalog_ChangeCatalogColumnUserNameLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/catalogColumns/b45c1999-e089-4bb1-a219-80a7a50a6f53/rename + method: POST + parameters: + request: + in: body + required: true + type: object + schema: changeUserColumnNameRequest + links.Catalog_GetBeezUPColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/catalogs/beezupColumns + method: GET + links.CatalogIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/catalogs + method: GET + links.CatalogStoreIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3 + method: GET + links.Auto_GetAutoImportConfigurationLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport + method: GET + links.Auto_StartAutoImportLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport/start + method: POST + links.Auto_PauseAutoImportLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport/pause + method: POST + links.Auto_ResumeAutoImportLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport/resume + method: POST + links.Auto_ConfigureAutoImportIntervalLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport/scheduling/interval + method: POST + parameters: + request: + in: body + required: true + type: object + schema: configureAutoImportIntervalRequest + links.Auto_ScheduleAutoImportLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport/scheduling/schedules + method: POST + parameters: + request: + in: body + required: true + type: object + schema: scheduleAutoImportRequest + links.Catalog_GetCatalogColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/catalogColumns + method: GET + links.Catalog_GetCustomColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns + method: GET + links.Catalog_SaveCustomColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns/{columnId} + method: POST + parameters: + columnId: + type: string + required: true + in: path + request: + type: object + required: true + in: body + schema: createCustomColumnRequest + links.Catalog_DeleteCustomColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb + method: DELETE + links.Catalog_ChangeCustomColumnUserNameLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb/rename + method: POST + parameters: + request: + type: object + required: true + in: body + schema: changeUserColumnNameRequest + links.Catalog_GetCustomColumnExpressionLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb/expression + method: GET + links.Catalog_ChangeCustomColumnExpressionLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb/expression + method: PUT + parameters: + request: + type: object + required: true + in: body + schema: changeCustomColumnExpressionRequest + links.Catalog_GetCategoriesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/categories + method: GET + links.Catalog_GetProductsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/products/list + method: POST + parameters: + request: + in: body + required: true + type: object + schema: getProductsRequest + links.Catalog_GetRandomProductsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/products/random + method: GET + links.Importation_ConfigureCatalogColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/catalogColumns/b45c1999-e089-4bb1-a219-80a7a50a6f53 + method: POST + parameters: + request: + in: body + required: true + type: object + schema: configureCatalogColumnCatalogRequest + links.Importation_IgnoreColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/catalogColumns/b45c1999-e089-4bb1-a219-80a7a50a6f53/ignore + method: POST + links.Importation_ReattendColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/catalogColumns/b45c1999-e089-4bb1-a219-80a7a50a6f53/reattend + method: POST + links.Importation_MapCatalogColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/catalogColumns/b45c1999-e089-4bb1-a219-80a7a50a6f53/map + method: POST + parameters: + request: + in: body + required: true + type: object + schema: mapBeezUPColumnRequest + links.Importation_UnmapCatalogColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/catalogColumns/b45c1999-e089-4bb1-a219-80a7a50a6f53/map + method: POST + links.Importation_GetImportationMonitoringLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c + method: GET + links.Importation_CancelLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/cancel + method: POST + links.Importation_ConfigureRemainingCatalogColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/configureRemainingCatalogColumns + method: POST + links.Importation_CommitColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/commitColumns + method: POST + links.Importation_CommitLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/commit + method: POST + links.Importation_TechnicalProgressionLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/technicalProgression + method: GET + links.Importation_GetReportLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e911432/report + method: GET + links.Importation_GetReportingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations + method: GET + links.Importation_StartManualUpdateLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/start + method: POST + parameters: + request: + in: body + required: true + type: object + schema: startManualImportRequest + links.Importation_GetManualUpdateLastInputConfigLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/inputConfiguration + method: GET + links.Importation_GetDetectedCatalogColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/catalogColumns + method: GET + links.Importation_GetCustomColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/customColumns + method: GET + links.Importation_SaveCustomColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/customColumns/{columnId} + method: POST + parameters: + columnId: + type: string + required: true + in: path + request: + type: object + required: true + in: body + schema: createCustomColumnRequest + links.Importation_DeleteCustomColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb + method: DELETE + links.Importation_GetCustomColumnExpressionLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb/expression + method: GET + links.Importation_MapCustomColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb/map + method: POST + parameters: + request: + in: body + required: true + type: object + schema: mapBeezUPColumnRequest + links.Importation_UnmapCustomColumnLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb/map + method: POST + links.Importation_GetProductSampleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/productSamples/{productSampleIndex} + method: GET + parameters: + productSampleIndex: + in: path + required: true + type: integer + links.Importation_GetProductSampleCustomColumnValueLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/importations/222ef571-bdb7-436d-a01a-e5a0e9161c0c/productSamples/{productSampleIndex}/customColumns/5b56bb78-bc0b-485e-abd8-8db7eed995cb + method: GET + parameters: + productSampleIndex: + in: path + required: true + type: integer + links.Importation_ActivateAutoImportLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/catalogs/a42b780d-4585-4566-800e-4d77a4d6f8a3/autoImport/activate + method: POST + catalogIndexLinks: + required: + - beezUPColumns + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.CatalogIndexLink' + beezUPColumns: + $ref: '#/components/schemas/links.Catalog_GetBeezUPColumnsLink' + catalogIndexLOVLinks: + required: + - beezUPColumnDataTypeLov + - beezUPColumnDisplayGroupLov + - beezUPColumnImportanceLov + - beezUPColumnLov + - compareOptionLov + - duplicateProductValueStrategyLov + type: object + properties: + beezUPColumnLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + beezUPColumnDataTypeLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + beezUPColumnImportanceLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + beezUPColumnDisplayGroupLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + duplicateProductValueStrategyLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + compareOptionLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + catalogIndex: + required: + - links + - lovLinks + type: object + properties: + links: + $ref: '#/components/schemas/catalogIndexLinks' + lovLinks: + $ref: '#/components/schemas/catalogIndexLOVLinks' + storeLinks: + $ref: '#/components/schemas/catalogStoreIndexList' + catalogStoreIndexList: + type: object + properties: + links: + type: object + additionalProperties: + $ref: '#/components/schemas/catalogStoreIndex' + description: The key is the store identifier. + catalogStoreIndexLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.CatalogStoreIndexLink' + inputConfiguration: + $ref: >- + #/components/schemas/links.Importation_GetManualUpdateLastInputConfigLink + autoImportInfo: + $ref: '#/components/schemas/links.Auto_GetAutoImportConfigurationLink' + importations: + $ref: '#/components/schemas/links.Importation_GetReportingsLink' + startImportation: + $ref: '#/components/schemas/links.Importation_StartManualUpdateLink' + catalogColumns: + $ref: '#/components/schemas/links.Catalog_GetCatalogColumnsLink' + customColumns: + $ref: '#/components/schemas/links.Catalog_GetCustomColumnsLink' + categories: + $ref: '#/components/schemas/links.Catalog_GetCategoriesLink' + products: + $ref: '#/components/schemas/links.Catalog_GetProductsLink' + randomProducts: + $ref: '#/components/schemas/links.Catalog_GetRandomProductsLink' + computeExpression: + $ref: '#/components/schemas/links.Catalog_ComputeExpressionLink' + catalogStoreStatus: + type: string + description: | + Indicates the status of the catalog store. + * OK: If the latest importation is a success! + * Failed: If the latest importation has failed ! + * Outdated: If the latest succeed importation is later than 1 day. + example: OK + enum: + - OK + - Failed + - Outdated + catalogStoreIndex: + required: + - links + - status + type: object + properties: + links: + $ref: '#/components/schemas/catalogStoreIndexLinks' + status: + $ref: '#/components/schemas/catalogStoreStatus' + importationsResponseLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.Importation_GetReportingsLink' + start: + $ref: '#/components/schemas/links.Importation_StartManualUpdateLink' + importationReportingLinks: + type: object + properties: + report: + $ref: '#/components/schemas/links.Importation_GetReportLink' + importationsPerStoreResponse: + type: object + additionalProperties: + $ref: '#/components/schemas/importationsResponse' + importationsResponse: + type: object + properties: + links: + $ref: '#/components/schemas/importationsResponseLinks' + importations: + type: array + items: + $ref: '#/components/schemas/importationReporting' + importAlreadyInProgressResponse: + required: + - errors + - links + type: object + properties: + errors: + type: array + description: The error message list + items: + $ref: '#/components/schemas/BeezUP_Common_UserErrorMessage' + links: + $ref: '#/components/schemas/importAlreadyInProgressResponseLinks' + importAlreadyInProgressResponseLinks: + required: + - cancelCurrentImportation + - currentImportation + type: object + properties: + currentImportation: + $ref: '#/components/schemas/links.Importation_GetImportationMonitoringLink' + cancelCurrentImportation: + $ref: '#/components/schemas/links.Importation_CancelLink' + description: The action links + schedulingType: + type: string + description: >- + Indicate the scheduling type. Schedule or Interval. We recommand you to + use interval for a better reporting. + example: Schedule + default: Interval + enum: + - Schedule + - Interval + duplicateProductValueStrategy: + type: string + description: Indicate the duplicate product sku strategy. + example: KeepFirstDuplicateProductOnly + default: None + enum: + - None + - SkipAllDuplicateProducts + - KeepFirstDuplicateProductOnly + - FailImportationIfAnyDuplicateProduct + compareOptions: + type: string + description: Indicate how the product sku are compared for the duplication check. + example: IgnoreCase + default: None + enum: + - None + - IgnoreCase + - IgnoreNonSpace + - IgnoreSymbols + - OrdinalIgnoreCase + - StringSort + - Ordinal + autoImportConfigurationLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.Auto_GetAutoImportConfigurationLink' + activate: + $ref: '#/components/schemas/links.Importation_ActivateAutoImportLink' + start: + $ref: '#/components/schemas/links.Auto_StartAutoImportLink' + pause: + $ref: '#/components/schemas/links.Auto_PauseAutoImportLink' + resume: + $ref: '#/components/schemas/links.Auto_ResumeAutoImportLink' + scheduleInterval: + $ref: '#/components/schemas/links.Auto_ConfigureAutoImportIntervalLink' + schedule: + $ref: '#/components/schemas/links.Auto_ScheduleAutoImportLink' + autoImportConfiguration: + required: + - duplicateProductConfiguration + - input + - inputConfiguredByUserId + - paused + - schedulingType + - schedulingValue + type: object + properties: + input: + $ref: '#/components/schemas/inputConfiguration' + inputConfiguredByUserId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + schedulingType: + $ref: '#/components/schemas/schedulingType' + scheduledByUserId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + schedulingValue: + minItems: 1 + type: array + description: >- + Indicate the scheduling value. If the scheduling type is Interval + then the value will be a duration otherwise the values will be the + time. + example: + - '21:00:00' + - '23:00:00' + - '08:30:00' + items: + type: string + paused: + type: boolean + description: Indicate if the auto import is in pause or not. + example: false + default: false + pauseStatusChangedByUserId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + pauseStatusChangedUtcDate: + type: string + description: Indicate when the pause status has changed in UTC date. + format: date-time + example: 2017-04-01T13:21:42.000Z + duplicateProductConfiguration: + $ref: '#/components/schemas/duplicateProductValueConfiguration' + schedulingLocalTimeZoneName: + type: string + description: >- + Indicate the time zone name of the scheduling. If the scheduling + type is "Schedule" + example: Romance Standard Time + default: Romance Standard Time + inputConfiguration: + required: + - files + type: object + properties: + transformFileUrl: + type: string + description: Can be null. Use to transform multiple files with an XSLT file. + format: uri + example: http://beezupblob.com/Mytransformation.xslt + files: + minItems: 1 + type: array + description: The list of files to get and read + items: + $ref: '#/components/schemas/inputFileConfiguration' + description: Describe the input configuration + inputFileConfiguration: + required: + - fetch + - fileNumber + - read + type: object + properties: + fileNumber: + minimum: 1 + type: integer + description: The file number starting by 1 + format: int32 + example: 1 + fetch: + $ref: '#/components/schemas/inputFileFetchConfiguration' + read: + $ref: '#/components/schemas/inputFileReadConfiguration' + description: Describe how to get and read a file + downloadCatalogStrategy: + type: string + description: >- + Indicate the download strategy (simple uri, ftps, ftplatest file, + etc...) + example: SimpleUri + enum: + - SimpleUri + - FtpLatest + - Sftp + - SftpLatest + - Ftps + - FtpsLatest + - Local + compressionFormatStrategy: + type: string + description: Indicate the compression type + example: None + enum: + - None + - Zip + - TarGz + - Gzip + - Bzip2 + - Rar + inputFileFetchConfiguration: + required: + - downloadCatalogStrategy + - uri + type: object + properties: + uri: + type: string + description: >- + Indicate the Uri of the file. (http, https, ftp, ftps, sftp are + allowed) + example: http://www.mywebsite.com/mycatalog.csv + credential: + $ref: '#/components/schemas/credential' + downloadCatalogStrategy: + $ref: '#/components/schemas/downloadCatalogStrategy' + compressionFormatStrategy: + $ref: '#/components/schemas/compressionFormatStrategy' + compressedRelativePath: + type: string + description: Indicate the relative path in the compressed file + example: folder/file.xxx + downloadTimeout: + type: integer + description: Indicate the download time out in second + format: int32 + example: 360 + default: 30 + description: Describe the way to download the file + fileFormatStrategy: + type: string + description: CSV or XML + example: Csv + enum: + - Unknown + - Csv + - Xml + - Json + inputFileReadConfiguration: + required: + - format + type: object + properties: + format: + $ref: '#/components/schemas/fileFormatStrategy' + encodingTypeName: + type: string + description: The encoding type. UTF-8 by default. + example: UTF-8 + default: UTF-8 + cultureName: + type: string + description: >- + The culture name of the file. (i.e. fr-FR). If null then Invariant + culture will be used. + example: fr-FR + default: '' + csvFileReadProperties: + $ref: '#/components/schemas/inputFileReadCsvConfiguration' + xmlFileReadProperties: + $ref: '#/components/schemas/inputFileReadXmlConfiguration' + description: > + Describe how to read the file. If FileFormatStrategy is CSV, + csvFileReadProperties is required. Otherwise the xmlFileReadProperties + is required. + credential: + required: + - userName + type: object + properties: + userName: + type: string + description: The user name + example: MyLogin + password: + type: string + description: The password + format: password + example: MyPassword + description: Provides the credentials + csvSeparator: + type: string + description: Indicate the separator of the values in the CSV file. Generally ";" + example: ; + default: ; + inputFileReadCsvConfiguration: + required: + - csvSeparator + - hasHeaderRecord + - ignoreHeaderRecord + type: object + properties: + hasHeaderRecord: + type: boolean + description: Indicate if the csv file contains the column name at the first row + example: true + default: true + ignoreHeaderRecord: + type: boolean + description: >- + Indicate if the importation should not use the csv column name from + the file + example: true + default: false + csvSeparator: + $ref: '#/components/schemas/csvSeparator' + csvTextQualifier: + type: string + description: >- + Indicate the text qualifier of the CSV file. Generally the value is + " + example: '' + default: '' + description: The CSV file description + inputFileReadXmlConfiguration: + required: + - flattenXmlChildElements + - useXmlAttributes + type: object + properties: + useXmlAttributes: + type: boolean + description: >- + Indicate if the importation should take in account the attribute in + the xml nodes. + example: true + flattenXmlChildElements: + type: boolean + description: >- + Indicate if the children xml nodes should be flatten with there + parent to take in account the sub node values. + example: true + description: The XML file description + configureAutoImportIntervalRequest: + required: + - interval + type: object + properties: + interval: + pattern: >- + (00:1[5-9])|(00:[2-5][0-9])|(0[1-9]:[0-5][0-9])|(1[0-9]:[0-5][0-9])|(2[0-3]:[0-5][0-9]) + type: string + description: >- + Indicate the interval in time span. (i.e. "04:00:00" for every 4 + hours) + example: '04:00:00' + description: The message request to configure the auto import interval + scheduleAutoImportRequest: + required: + - schedules + type: object + properties: + schedules: + minItems: 1 + uniqueItems: true + type: array + description: >- + Indicate the time span you want to import your catalog. (i.e. + "21:00:00" to import your catalog at 9PM) + example: + - '21:00:00' + - '23:00:00' + - '08:30:00' + items: + pattern: >- + (00:1[5-9])|(00:[2-5][0-9])|(0[1-9]:[0-5][0-9])|(1[0-9]:[0-5][0-9])|(2[0-3]:[0-5][0-9]) + type: string + localTimeZoneName: + type: string + description: If null the local time zone name will be "Romance Standard Time" + example: Romance Standard Time + default: Romance Standard Time + description: The message request to schedule the auto import + lastManualImportInputConfiguration: + required: + - input + type: object + properties: + input: + $ref: '#/components/schemas/inputConfiguration' + description: Last manual import input configuration + displayGroupName: + type: string + description: Indicate the display group name where the column must be putted + example: Category + canBeTruncated: + type: boolean + description: >- + If the size of the value is greater than the limit we can truncate the + value instead of failing... + example: false + default: false + beezUPColumnConfiguration: + required: + - beezUPColumnName + - columnImportance + - displayGroupName + type: object + properties: + beezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + unique: + type: boolean + description: "/!\\ ONLY AVAILABLE ON CATALOG COLUMN NOT ON CUSTOM COLUMNS!!\r\nIf true, an error happen at the second occurence of the same value for this column\r\nThis information will be used during the importation process and later for mapping proposal" + example: false + default: false + columnImportance: + $ref: '#/components/schemas/BeezUP_Common_ColumnImportance' + columnDataType: + $ref: '#/components/schemas/BeezUP_Common_ColumnDataType' + canBeTruncated: + $ref: '#/components/schemas/canBeTruncated' + displayGroupName: + $ref: '#/components/schemas/displayGroupName' + description: + type: string + description: Describe the BeezUP column + example: Use for big text, like description + description: Describe a BeezUP column + changeUserColumnNameRequest: + required: + - userColumName + type: object + properties: + userColumName: + $ref: '#/components/schemas/userColumName' + description: The message request for the change user column name + encryptedExpression: + type: string + description: The encrypted excel expression of the column + example: uziushdczaniodnndonisodndsiondsoidsndoin + encryptedBlocklyExpression: + type: string + description: The encrypted XML Blockly representation of the expression + example: apokpoa,opz,sixsoisiosnoisn + createCustomColumnRequest: + required: + - displayGroupName + - encryptedBlocklyExpression + - encryptedExpression + - userColumnName + type: object + properties: + userColumnName: + $ref: '#/components/schemas/userColumName' + encryptedExpression: + $ref: '#/components/schemas/encryptedExpression' + encryptedBlocklyExpression: + $ref: '#/components/schemas/encryptedBlocklyExpression' + displayGroupName: + $ref: '#/components/schemas/displayGroupName' + description: The request message to create a custom column + changeCustomColumnExpressionRequest: + required: + - encryptedBlocklyExpression + - encryptedExpression + type: object + properties: + encryptedExpression: + $ref: '#/components/schemas/encryptedExpression' + encryptedBlocklyExpression: + $ref: '#/components/schemas/encryptedBlocklyExpression' + description: The request message to change the custom column expression + computeExpressionRequest: + required: + - encryptedExpression + - productValues + type: object + properties: + productValues: + $ref: '#/components/schemas/productValues' + encryptedExpression: + $ref: '#/components/schemas/encryptedExpression' + description: >- + The request message to compute an expression based on the provided + product values + importationMonitoring: + required: + - beginUtcDate + - executionId + - lastUpdateUtcDate + - steps + - success + type: object + properties: + userId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + success: + type: boolean + description: Indicates if the importation was successfully completed or not + example: true + executionId: + $ref: '#/components/schemas/executionId' + lastUpdateUtcDate: + type: string + description: The last update of the reporting + format: date-time + example: 2017-04-01T13:10:09.000Z + beginUtcDate: + type: string + description: The start date of the importation + format: date-time + example: 2017-04-01T13:01:01.000Z + errors: + type: array + description: In case of error a description will be indicated + items: + $ref: '#/components/schemas/BeezUP_Common_UserErrorMessage' + steps: + type: object + additionalProperties: + type: boolean + description: >- + Contains all steps of the importation process with a boolean. If + true the step has been passed, false the step is not complete + example: + isCatalogImportPrepareReadCompleted: 'false' + isCatalogImportComputeDiffCompleted: 'false' + isCatalogUpdateCompleted: 'false' + isSavedInDb: 'false' + links: + $ref: '#/components/schemas/importationMonitoringLinks' + description: Describe the reporting of the catalog importation + importationMonitoringLinks: + required: + - self + - technicalProgression + type: object + properties: + self: + $ref: '#/components/schemas/links.Importation_GetImportationMonitoringLink' + technicalProgression: + $ref: '#/components/schemas/links.Importation_TechnicalProgressionLink' + cancel: + $ref: '#/components/schemas/links.Importation_CancelLink' + configureRemainingCatalogColumns: + $ref: >- + #/components/schemas/links.Importation_ConfigureRemainingCatalogColumnsLink + commitColumns: + $ref: '#/components/schemas/links.Importation_CommitColumnsLink' + commit: + $ref: '#/components/schemas/links.Importation_CommitLink' + activateAutoImport: + $ref: '#/components/schemas/links.Importation_ActivateAutoImportLink' + catalogColumns: + $ref: '#/components/schemas/links.Importation_GetDetectedCatalogColumnsLink' + customColumns: + $ref: '#/components/schemas/links.Importation_GetCustomColumnsLink' + productSamples: + $ref: '#/components/schemas/links.Importation_GetProductSampleLink' + description: Applicable operations considering the state of the importation + catalogColumnName: + type: string + description: The catalog column name + example: SKU + columnId: + type: string + description: The catalog column identifier + format: guid + example: 8f6671d6-a9bc-4de0-a0c4-4643b0c3f871 + detectedCatalogColumnListLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.Importation_GetDetectedCatalogColumnsLink' + detectedCatalogColumnList: + required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/detectedCatalogColumnListLinks' + detectedCatalogColumns: + type: array + description: Contains all deteted catalog columns + items: + $ref: '#/components/schemas/detectedCatalogColumn' + description: The list of detected catalog column + detectedCatalogColumnLinks: + type: object + properties: + configure: + $ref: '#/components/schemas/links.Importation_ConfigureCatalogColumnLink' + ignore: + $ref: '#/components/schemas/links.Importation_IgnoreColumnLink' + reattend: + $ref: '#/components/schemas/links.Importation_ReattendColumnLink' + map: + $ref: '#/components/schemas/links.Importation_MapCatalogColumnLink' + unmap: + $ref: '#/components/schemas/links.Importation_UnmapCatalogColumnLink' + detectedCatalogColumn: + allOf: + - $ref: '#/components/schemas/catalogColumn' + - required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/detectedCatalogColumnLinks' + description: The catalog column detected during the first parsing step + productValues: + type: object + additionalProperties: + type: string + description: The key is the column identifier + example: + 68082b11-4ffd-4bec-964a-465a471c7d37: SKU1234 + b6d74510-41ce-42ec-947a-0bdf62e9beee: Refrigerateur + 012929c0-e78b-462a-a96e-25c061575385: >- + http://media.conforama.fr/Medias/500000/80000/5000/500/10/G_585511_A.jpg + ba270fa0-8482-46be-905a-cae4ca746b92: >- + http://www.conforama.fr/gros-electromenager/encastrable/refrigerateur-encastrable/refrigerateur-combine-161-litres-far-r5115s/p/585511 + 46602e10-bc45-4944-a440-63d5f7ece1f8: '42' + productSample: + type: object + properties: + productValues: + $ref: '#/components/schemas/productValues' + description: Describe a product sample + configureCatalogColumnCatalogRequest: + required: + - catalogColumn + type: object + properties: + catalogColumn: + $ref: '#/components/schemas/catalogColumn' + description: The request to configure a catalog column + catalogColumnList: + required: + - catalogColumns + type: object + properties: + catalogColumns: + type: array + items: + $ref: '#/components/schemas/catalogColumn' + customColumnListLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.Catalog_GetCustomColumnsLink' + add: + $ref: '#/components/schemas/links.Catalog_SaveCustomColumnLink' + customColumnList: + required: + - customColumns + - links + type: object + properties: + links: + $ref: '#/components/schemas/customColumnListLinks' + customColumns: + type: array + items: + $ref: '#/components/schemas/customColumn' + importationCustomColumnListLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.Importation_GetCustomColumnsLink' + add: + $ref: '#/components/schemas/links.Importation_SaveCustomColumnLink' + importationCustomColumnList: + required: + - customColumns + - links + type: object + properties: + links: + $ref: '#/components/schemas/customColumnListLinks' + customColumns: + type: array + items: + $ref: '#/components/schemas/importationCustomColumn' + catalogColumnLinks: + type: object + properties: + rename: + $ref: '#/components/schemas/links.Catalog_ChangeCatalogColumnUserNameLink' + catalogColumn: + required: + - catalogColumnName + - configuration + - id + - links + - userColumName + type: object + properties: + ignored: + type: boolean + description: >- + IF true, the product values of this column will be not taken in + account during the importation process + default: false + duplicateProductValueConfiguration: + $ref: '#/components/schemas/duplicateProductValueConfiguration' + id: + $ref: '#/components/schemas/columnId' + catalogColumnName: + $ref: '#/components/schemas/catalogColumnName' + userColumName: + $ref: '#/components/schemas/userColumName' + configuration: + $ref: '#/components/schemas/columnConfiguration' + links: + $ref: '#/components/schemas/catalogColumnLinks' + description: The catalog column configuration + example: + ignored: 'true' + duplicateProductValueConfiguration: + strategy: KeepFirstDuplicateProductOnly + compareOptions: IgnoreCase + id: 8a76f06a-fefc-4c0d-bcfe-b210f1482977 + catalogColumnName: SKU + userColumName: My SKU + configuration: + beezUPColumnName: CategoryFirstLevel + columnImportance: Required + columnDataType: String + columnCultureName: fr-FR + columnFormat: MM/dd/yyyy + canBeTruncated: 'false' + displayGroupName: Category + duplicateProductValueConfiguration: + required: + - compareOptions + - strategy + type: object + properties: + strategy: + $ref: '#/components/schemas/duplicateProductValueStrategy' + compareOptions: + $ref: '#/components/schemas/compareOptions' + description: Describe how you want to manage the duplication of the product value + columnConfiguration: + required: + - columnDataType + - columnImportance + type: object + properties: + beezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + columnImportance: + $ref: '#/components/schemas/BeezUP_Common_ColumnImportance' + columnDataType: + $ref: '#/components/schemas/BeezUP_Common_ColumnDataType' + columnCultureName: + $ref: '#/components/schemas/columnCultureName' + columnFormat: + $ref: '#/components/schemas/columnFormat' + canBeTruncated: + $ref: '#/components/schemas/canBeTruncated' + displayGroupName: + $ref: '#/components/schemas/displayGroupName' + description: >- + Indicates the configuration applied on the column (catalog or custom) + during the importation process. + columnCultureName: + type: string + description: >- + If non null, culture used to parse the value to the storage type of this + column\r\n will be used for parsing and for consolidation proces + example: fr-FR + columnFormat: + type: string + description: >- + If non null, format used to parse the value to the storage type of this + column\r\n will be used for parsing and for consolidation proces + example: MM/dd/yyyy + mapBeezUPColumnRequest: + required: + - beezUPColumnName + type: object + properties: + beezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + importationReporting: + required: + - beginUtcDate + - executionId + - lastUpdateUtcDate + - steps + type: object + properties: + links: + $ref: '#/components/schemas/importationReportingLinks' + executionId: + $ref: '#/components/schemas/executionId' + stepName: + type: string + description: The last step name of the importation process + example: IsSaveInDb + userId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + success: + type: boolean + description: Indicate if the importation succeed or not. + example: true + totalProductCount: + type: integer + description: >- + Indicate the total product count detected in the catalog during the + importation. + format: int32 + example: 101 + totalProductErrorCount: + type: integer + description: >- + Indicate the total product count in error detected in the catalog + during the importation. + format: int32 + example: 0 + totalProductSuccessCount: + type: integer + description: >- + Indicate the total product count in success in the catalog during + the importation. + format: int32 + example: 101 + errors: + type: array + description: Indicate the error message list related to this importation. + items: + $ref: '#/components/schemas/BeezUP_Common_UserErrorMessage' + lastUpdateUtcDate: + type: string + description: Indicate the last update UTC date of the reporting. + format: date-time + example: 2017-04-01T13:10:09.000Z + autoImported: + type: boolean + description: Indicate if this importation is an auto import or not. + example: true + beginUtcDate: + type: string + description: Indicate the begin UTC date of this importation. + format: date-time + example: 2017-04-01T13:01:01.000Z + endUtcDate: + type: string + description: Indicate the end UTC date of this importation. + format: date-time + example: 2017-04-01T13:10:09.000Z + inputConfigurationUrl: + type: string + description: Indicate the input url of this importation. + format: uri + example: http://blal.com/catalog.csv + steps: + type: object + additionalProperties: + type: boolean + description: >- + Indicate the steps that have been passed during the importation + process + example: + isCatalogImportPrepareReadCompleted: 'false' + isCatalogImportComputeDiffCompleted: 'false' + isCatalogUpdateCompleted: 'false' + isSavedInDb: 'false' + description: The catalog importation reporting + startManualImportRequest: + required: + - input + type: object + properties: + input: + $ref: '#/components/schemas/inputConfiguration' + duplicateProductSkuConfiguration: + $ref: '#/components/schemas/duplicateProductValueConfiguration' + description: >- + The message request start a manual importation process. Indicate the way + to handle duplicate product. Can be null if you want to reuse the + configuration of the previous importation succeed. + importationTechnicalProgression: + type: object + properties: + stepsProgression: + type: object + additionalProperties: + type: array + items: + type: string + description: Indicate for each step of the importation the uris to look at + changeCustomColumnRequest: + required: + - encryptedBlocklyExpression + - encryptedExpression + - userColumName + type: object + properties: + encryptedExpression: + $ref: '#/components/schemas/encryptedExpression' + encryptedBlocklyExpression: + $ref: '#/components/schemas/encryptedBlocklyExpression' + userColumName: + $ref: '#/components/schemas/userColumName' + description: The message request to change a custom column expression an user name + customColumnLinks: + required: + - delete + - expression + - rename + - save + - saveExpression + type: object + properties: + save: + $ref: '#/components/schemas/links.Catalog_SaveCustomColumnLink' + delete: + $ref: '#/components/schemas/links.Catalog_DeleteCustomColumnLink' + rename: + $ref: '#/components/schemas/links.Catalog_ChangeCustomColumnUserNameLink' + expression: + $ref: '#/components/schemas/links.Catalog_GetCustomColumnExpressionLink' + saveExpression: + $ref: '#/components/schemas/links.Catalog_ChangeCustomColumnExpressionLink' + customColumn: + required: + - configuration + - id + - links + - userColumName + type: object + properties: + id: + $ref: '#/components/schemas/columnId' + userColumName: + $ref: '#/components/schemas/userColumName' + configuration: + $ref: '#/components/schemas/columnConfiguration' + catalogColumnDependencies: + type: array + items: + $ref: '#/components/schemas/catalogColumnName' + links: + $ref: '#/components/schemas/customColumnLinks' + description: The custom column configuration + importationCustomColumnLinks: + required: + - delete + - expression + - save + type: object + properties: + save: + $ref: '#/components/schemas/links.Importation_SaveCustomColumnLink' + delete: + $ref: '#/components/schemas/links.Catalog_DeleteCustomColumnLink' + expression: + $ref: '#/components/schemas/links.Catalog_GetCustomColumnExpressionLink' + map: + $ref: '#/components/schemas/links.Importation_MapCustomColumnLink' + unmap: + $ref: '#/components/schemas/links.Importation_UnmapCustomColumnLink' + productSampleValue: + $ref: >- + #/components/schemas/links.Importation_GetProductSampleCustomColumnValueLink + importationCustomColumn: + required: + - configuration + - id + - links + - userColumName + type: object + properties: + id: + $ref: '#/components/schemas/columnId' + userColumName: + $ref: '#/components/schemas/userColumName' + configuration: + $ref: '#/components/schemas/columnConfiguration' + links: + $ref: '#/components/schemas/importationCustomColumnLinks' + description: The custom column configuration + randomProductList: + required: + - products + type: object + properties: + products: + type: array + items: + $ref: '#/components/schemas/product' + productList: + required: + - paginationResult + - products + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + products: + type: array + items: + $ref: '#/components/schemas/product' + product: + required: + - categoryId + - exists + - productId + - values + type: object + properties: + productId: + $ref: '#/components/schemas/BeezUP_Common_ProductId' + categoryId: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryId' + values: + $ref: '#/components/schemas/productValues' + exists: + type: boolean + description: Indicates if the product exists in the current catalog + example: true + description: Represent a catalog product + getProductsRequest: + required: + - pageNumber + - pageSize + type: object + properties: + pageNumber: + $ref: '#/components/schemas/BeezUP_Common_PageNumber' + pageSize: + $ref: '#/components/schemas/BeezUP_Common_PageSize' + columnIdList: + maxItems: 5 + minItems: 1 + type: array + items: + $ref: '#/components/schemas/BeezUP_Common_CatalogColumnId' + exists: + type: boolean + description: Search for existing products or not. If null you will received both. + example: true + productIdList: + type: array + description: Filter with a list of product identifier + items: + $ref: '#/components/schemas/BeezUP_Common_ProductId' + sku: + type: string + description: Search for product by sku + example: MySku123 + ean: + type: string + description: Search for product by ean + example: MySku123 + mpn: + type: string + description: Search for product by mpn + example: MySku123 + title: + type: string + description: Search for products containing this title + example: Frigo + categoryPath: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryPath' + orderByCatalogColumnId: + $ref: '#/components/schemas/BeezUP_Common_CatalogColumnId' + withoutSubCategories: + type: boolean + description: >- + Do not retrieve sub categories. By default, this value is set to + false + example: false + description: The request message to get products based on these filters + categoryList: + required: + - categories + type: object + properties: + categories: + type: array + description: The category list + items: + $ref: '#/components/schemas/category' + description: The object which contains the category list + category: + required: + - categoryPath + - selfProductCount + - totalProductCount + type: object + properties: + categoryId: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryId' + categoryPath: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryPath' + totalProductCount: + type: integer + description: >- + The total product count related to this category and his sub + categories + format: int32 + example: 101 + selfProductCount: + type: integer + description: The product count related to this category + format: int32 + example: 101 + description: The catalog category + getImportationProductsReportRequest: + required: + - pageNumber + - pageSize + type: object + properties: + pageNumber: + $ref: '#/components/schemas/BeezUP_Common_PageNumber' + pageSize: + $ref: '#/components/schemas/BeezUP_Common_PageSize' + sku: + type: string + description: Filter by Sku (equals) + ean: + type: string + description: Filter by EAN (equals) + mpn: + type: string + description: Filter by MPN (equals) + title: + type: string + description: Filter by Title (StartsWith) + errorCodes: + $ref: '#/components/schemas/getImportationProductsReportRequestErrorCodes' + description: Get Importation Products Report Request + getImportationProductsReportRequestErrorCodes: + type: array + description: Get Importation Products Report Request Error Codes + items: + $ref: '#/components/schemas/getImportationProductsReportRequestErrorCode' + getImportationProductsReportRequestErrorCode: + type: object + properties: + errorCode: + $ref: '#/components/schemas/errorCode' + userColumnName: + $ref: '#/components/schemas/userColumName' + description: Get Importation Products Report Request Error Codes + getImportationProductsReportResponse: + required: + - paginationResult + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + productErrors: + $ref: '#/components/schemas/productErrors' + description: Get Importation Products Report Response + productErrors: + type: array + description: Product Errors + items: + $ref: '#/components/schemas/productError' + productError: + required: + - errors + - lineNumber + type: object + properties: + lineNumber: + type: integer + sku: + $ref: '#/components/schemas/sku' + ean: + type: string + mpn: + type: string + title: + type: string + errors: + $ref: '#/components/schemas/productErrorCodes' + productErrorCodes: + type: array + items: + $ref: '#/components/schemas/productErrorCode' + productErrorCode: + type: object + properties: + errorCode: + $ref: '#/components/schemas/errorCode' + userColumName: + $ref: '#/components/schemas/userColumName' + beezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + errorMessage: + type: string + errorCode: + type: string + description: Error Code + getImportationReportResponseDiff: + required: + - createdCount + - deletedCount + - updatedCount + type: object + properties: + createdCount: + type: integer + updatedCount: + type: integer + deletedCount: + type: integer + unchangedCount: + type: integer + getImportationReportResponseProductMetrics: + required: + - activeCount + - detectedCount + - duplicatedCount + - failedCount + type: object + properties: + detectedCount: + type: integer + duplicatedCount: + type: integer + failedCount: + type: integer + activeCount: + type: integer + getImportationReportResponse: + required: + - errors + - executionId + - importationInfo + type: object + properties: + executionId: + $ref: '#/components/schemas/executionId' + importationInfo: + $ref: '#/components/schemas/getImportationReportResponseImportationInfo' + columns: + $ref: '#/components/schemas/getImportationReportResponseDiff' + categories: + $ref: '#/components/schemas/getImportationReportResponseDiff' + products: + $ref: '#/components/schemas/getImportationReportResponseDiff' + productMetrics: + $ref: '#/components/schemas/getImportationReportResponseProductMetrics' + errors: + $ref: '#/components/schemas/getImportationReportResponseErrors' + description: Get Importation Report Response + getImportationReportResponseImportationInfo: + required: + - beginUtcDate + - endUtcDate + - inputConfiguration + - userId + type: object + properties: + beginUtcDate: + type: string + description: The start date of the importation + format: date-time + example: 2017-04-01T13:01:01.000Z + endUtcDate: + type: string + description: The start date of the importation + format: date-time + example: 2017-04-01T13:01:01.000Z + userId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + inputConfiguration: + $ref: '#/components/schemas/inputFileConfiguration' + getImportationReportResponseErrors: + type: array + items: + $ref: '#/components/schemas/getImportationReportResponseError' + getImportationReportResponseError: + required: + - errorCode + - productCount + - userColumName + type: object + properties: + errorCode: + $ref: '#/components/schemas/errorCode' + userColumName: + $ref: '#/components/schemas/userColumName' + beezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + productCount: + type: integer + BeezUP_Common_BeezUPColumnName: + type: string + description: The BeezUP column name + example: CategoryFirstLevel + BeezUP_Common_ColumnImportance: + type: string + description: Importance of the column + example: Required + default: Optional + enum: + - Required + - Recommended + - Optional + BeezUP_Common_ColumnDataType: + type: string + description: >- + Data type of the column, will be used for parsing and for consolidation + proces + example: String + default: String + enum: + - String + - Url + - Text + - Decimal + - DateTime + - Int + - SpecialInt + - InStock + - Unknown + - ImageUrl + userColumName: + type: string + description: Column named by the user + example: My SKU + BeezUP_Common_PageNumber: + minimum: 1 + type: integer + description: Indicates the page number + format: int32 + example: 1 + default: 1 + BeezUP_Common_PageSize: + maximum: 100 + minimum: 25 + type: integer + description: Indicate the item count per page + format: int32 + example: 100 + default: 100 + BeezUP_Common_CatalogColumnId: + type: string + description: The catalog column identifier (catalog or custom column) + format: guid + example: bea7c21e-948b-4ac3-9ffd-4396e62c4163 + BeezUP_Common_ProductId: + type: string + description: The product identifier + format: guid + example: 578419df-1bbf-41a6-96fa-862e42182b67 + BeezUP_Common_CatalogCategoryPath: + type: array + description: The catalog category path + example: + - Vêtements + - Femmes + - Chaussures + items: + type: string + BeezUP_Common_PaginationResult: + required: + - entryCount + - links + - pageCount + - totalEntryCount + type: object + properties: + entryCount: + minimum: 0 + type: integer + description: The entry count currently returned + example: 25 + pageCount: + minimum: 0 + type: integer + description: The page count + example: 38 + totalEntryCount: + minimum: 0 + type: integer + description: The total entry count + example: 943 + links: + $ref: '#/components/schemas/BeezUP_Common_PaginationResultLinks' + example: + entryCount: '25' + pageCount: '38' + totalEntryCount: '943' + links: + first: + href: /v2/user/marketplaces/orders/list/full + method: POST + parameters: + - name: request + in: body + type: object + schema: orderListRequest + value: + beginPeriodUtcDate: 2014-08-25T07:32:31.584Z + endPeriodUtcDate: 2014-09-24T07:32:31.584Z + pageSize: '25' + pageNumber: '1' + last: + href: /v2/user/marketplaces/orders/list/full + method: POST + parameters: + - name: request + in: body + type: object + schema: orderListRequest + value: + beginPeriodUtcDate: 2014-08-25T07:32:31.584Z + endPeriodUtcDate: 2014-09-24T07:32:31.584Z + pageSize: '25' + pageNumber: '38' + next: + href: /v2/user/marketplaces/orders/list/full + method: POST + parameters: + - name: request + in: body + type: object + schema: orderListRequest + value: + beginPeriodUtcDate: 2014-08-25T07:32:31.584Z + endPeriodUtcDate: 2014-09-24T07:32:31.584Z + pageSize: '25' + pageNumber: '2' + executionId: + type: string + description: The execution identifier of the catalog importation + format: guid + example: bf3bc288-604c-4267-925e-66b1a15dca75 + BeezUP_Common_CatalogCategoryId: + type: string + description: The catalog category identifier + format: guid + example: 81a058a6-0451-4b79-84ef-94c58d0ed4ac + BeezUP_Common_PaginationResultLinks: + required: + - first + - last + type: object + properties: + first: + $ref: '#/components/schemas/BeezUP_Common_Link3' + last: + $ref: '#/components/schemas/BeezUP_Common_Link3' + previous: + $ref: '#/components/schemas/BeezUP_Common_Link3' + next: + $ref: '#/components/schemas/BeezUP_Common_Link3' + description: The navigation links 'first', 'last', 'next', 'previous' + sku: + maxLength: 50 + type: string + description: >- + The Stock Keeping Unit (SKU), i.e. a merchant-specific identifier for a + product or service, or the product to which the offer refers. + http://schema.org/sku + links.GetChannelInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channels/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + method: GET + channelHeader: + required: + - channelId + - channelLogoUrl + - channelName + - links + - types + type: object + properties: + channelId: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + channelName: + $ref: '#/components/schemas/BeezUP_Common_ChannelName' + channelLogoUrl: + $ref: '#/components/schemas/BeezUP_Common_HttpUrl' + types: + type: array + description: The type list related to a channel + example: + - Marketplace + items: + type: string + links: + $ref: '#/components/schemas/channelHeaderLinks' + description: The available channel + channelHeaderLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelInfoLink' + description: The links related to an available channel + channelInfo: + required: + - channelId + - channelName + type: object + properties: + channelId: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + channelName: + $ref: '#/components/schemas/BeezUP_Common_ChannelName' + channelLogoUrl: + $ref: '#/components/schemas/BeezUP_Common_HttpUrl' + channelDescription: + type: string + description: Indicae a description to the channel + example: >- + Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia + dolorum, animi voluptatibus maiores, assumenda maxime illum, labore + quae quas ducimus laudantium provident veritatis doloremque + dignissimos eum. Error magni illum autem. + beezUPOffer: + type: string + description: Indicate the BeezUP offer + example: First month free + salesContact: + type: object + properties: + name: + type: string + description: Indicate the BeezUP offer + example: Stéphanie Gregis + email: + type: string + description: Indicate the sales contact email + format: email + example: stephanie.gregis@m6.fr + phoneNumber: + type: string + description: The sales contact phone number + example: 0033 6 08 87 85 45 + details: + type: object + properties: + costs: + type: string + description: The cost's description of the channel + example: CPC variation from 0.10€ to 0.20€ + businessModel: + type: string + description: The business model of the channel + example: CPC + channelType: + type: string + description: The channel type + example: Comparator + trackingType: + type: string + description: The tracking type + example: Redirect + category: + type: string + description: The channel category + example: null + homeUrl: + type: string + description: The home url of the channel + format: uri + example: http://www.achetezfacile.com + subscriptionLink: + type: string + description: The subscription link to the channel + example: | + By Email at : stephanie.gregis@m6.fr + keyNumbers: + type: object + properties: + products: + type: string + description: The estimated product count of the channel + example: 1M + categories: + type: string + description: The estimated category count of the channel + example: NC + stores: + type: string + description: The estimated store count of the channel + example: '3000' + viewsPerMonth: + type: string + description: The estimated view count per month of the channel + example: 3M + technicalContact: + type: object + properties: + name: + type: string + description: The technical contact name + example: Pierre Guédon + phoneNumber: + type: string + description: The technical contact phone number + example: NC + email: + type: string + description: The technical contact email + example: pierre.guedon@m6.fr + channelCategoryDefaultCost: + type: number + description: The default cost on this channel category + format: decimal + example: 10.42 + channelCategoryChannelCode: + type: string + description: The channel category channel code identifier + example: '1342' + channelCategoryLevel: + maximum: 9 + minimum: 1 + type: integer + description: The channel category level starting from 1 + format: int32 + example: 3 + channelRootCategory: + required: + - firstLevelCategories + type: object + properties: + firstLevelCategories: + type: array + items: + $ref: '#/components/schemas/channelFirstLevelCategory' + description: Get channel first level category list + channelFirstLevelCategory: + required: + - channelCategoryId + - channelCategoryLevel + - channelCategoryName + type: object + properties: + channelCategoryId: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryId' + channelCategoryName: + type: string + description: The channel category name + example: Clothing + channelCategoryLevel: + $ref: '#/components/schemas/channelCategoryLevel' + channelCategoryDefaultCost: + $ref: '#/components/schemas/channelCategoryDefaultCost' + channelCategoryChannelCode: + $ref: '#/components/schemas/channelCategoryChannelCode' + channelCategoryColumnOverrides: + $ref: '#/components/schemas/channelCategoryColumnOverrides' + subCategories: + type: array + items: + $ref: '#/components/schemas/channelCategory' + description: The first level category with his sub categories + channelCategory: + required: + - channelCategoryId + - channelCategoryLevel + - channelCategoryPath + type: object + properties: + channelCategoryId: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryId' + channelCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryPath' + channelCategoryLevel: + $ref: '#/components/schemas/channelCategoryLevel' + channelCategoryDefaultCost: + $ref: '#/components/schemas/channelCategoryDefaultCost' + channelCategoryChannelCode: + $ref: '#/components/schemas/channelCategoryChannelCode' + channelCategoryColumnOverrides: + $ref: '#/components/schemas/channelCategoryColumnOverrides' + description: The channel category + channelCategoryColumnOverrides: + type: object + additionalProperties: + $ref: '#/components/schemas/channelCategoryColumnOverride' + description: The channel category column overrides + channelCategoryColumnOverride: + required: + - channelColumnId + - channelColumnName + - configuration + - showInMapping + type: object + properties: + channelColumnId: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnId' + channelColumnName: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnName' + channelColumnDescription: + $ref: '#/components/schemas/channelColumnDescription' + showInMapping: + $ref: '#/components/schemas/channelColumnShowInMapping' + configuration: + $ref: '#/components/schemas/channelColumnConfiguration' + restrictedValues: + $ref: '#/components/schemas/channelColumnRestrictedValues' + channelColumnDescription: + type: string + description: The channel column description + example: >- + Please enter the base prices (price per unit) according to Article + PAngV + channelColumnShowInMapping: + type: boolean + description: Indicates if this column must shown in the mapping page or not + example: true + channelColumn: + required: + - channelColumnId + - channelColumnName + - configuration + - position + - showInMapping + type: object + properties: + channelColumnId: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnId' + channelColumnName: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnName' + channelColumnDescription: + $ref: '#/components/schemas/channelColumnDescription' + showInMapping: + $ref: '#/components/schemas/channelColumnShowInMapping' + position: + type: integer + description: The position of the column starting from 1 + example: 1 + configuration: + $ref: '#/components/schemas/channelColumnConfiguration' + restrictedValues: + $ref: '#/components/schemas/channelColumnRestrictedValues' + description: The channel column + channelColumnRestrictedValues: + type: object + additionalProperties: + type: string + description: > + The restricted values. The key will be the restricted value identifier + (format:guid) and the value will be the restriced value + channelColumnConfiguration: + required: + - columnDataType + - columnImportance + type: object + properties: + columnImportance: + $ref: '#/components/schemas/BeezUP_Common_ColumnImportance' + columnDataType: + $ref: '#/components/schemas/BeezUP_Common_ColumnDataType' + beezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + description: >- + The channel column configuration. The BeezUP Column Name is optional. If + the BeezUP column is mapped we will indicate the data type and column + importance of the BeezUP column. + BeezUP_Common_ChannelColumnId: + type: string + description: The channel column identifier + format: guid + example: 8a76f06a-fefc-4c0d-bcfe-b210f1482977 + BeezUP_Common_ChannelId: + type: string + description: The channel identifier + format: guid + example: 2dc136a7-0d3d-4cc9-a825-a28a42c53e28 + BeezUP_Common_ChannelName: + type: string + description: The channel name + example: Amazon FRA + BeezUP_Common_HttpUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: >- + The URL https://en.wikipedia.org/wiki/URL + example: http://www.mydomain.com + BeezUP_Common_ChannelColumnName: + type: string + description: The channel column name + example: NAME + BeezUP_Common_ChannelCategoryId: + type: string + format: guid + example: 24f508da-a069-4467-b9d3-15baebe9bac7 + BeezUP_Common_ChannelCategoryPath: + type: array + description: The channel category path + example: + - Clothing + - Women + - Shoes + items: + type: string + links.GetChannelCatalogsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channelCatalogs + method: GET + links.GetChannelCatalogFilterOperatorsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channelCatalogs/filterOperators + method: GET + links.GetChannelCatalogExportationCacheInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exportations/cache + method: GET + links.GetChannelCatalogExportationHistoryLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exportations/history + method: GET + links.ClearChannelCatalogExportationCacheLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exportations/cache/clear + method: POST + links.GetChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + method: GET + links.DeleteChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + method: DELETE + links.GetChannelCatalogCategoriesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + description: >- + If you did not configure the cost settings this link will not be + displayed. + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/categories + method: GET + links.DisableChannelCatalogCategoryMappingLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/categories/disableMapping + method: POST + links.ReenableChannelCatalogCategoryMappingLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/categories/reenableMapping + method: POST + links.ConfigureChannelCatalogCategoryLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/category/configure + method: POST + links.EnableChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/enable + method: POST + links.DisableChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/disable + method: POST + links.GetChannelCatalogProductInfoListLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products + method: POST + links.ExportChannelCatalogProductInfoListLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/export + method: POST + parameters: + format: + in: query + required: true + type: string + value: csv + links.ConfigureChannelCatalogColumnMappingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/columnMappings + method: PUT + links.ConfigureChannelCatalogGeneralSettingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/settings/general + method: POST + links.ConfigureChannelCatalogCostSettingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/settings/cost + method: POST + links.AddChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channelCatalogs + method: POST + links.ConfigureChannelCatalogExclusionFiltersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exclusionFilters + method: PUT + links.GetChannelCatalogExclusionFiltersCopyLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exclusionFilters/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/copy + method: GET + links.ConfigureChannelCatalogExclusionFiltersCopyLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exclusionFilters/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/copy + method: POST + links.GetChannelCatalogExclusionFiltersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/exclusionFilters + method: GET + links.GetChannelCatalogProductInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/578419df-1bbf-41a6-96fa-862e42182b67 + method: GET + links.DisableChannelCatalogProductLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/578419df-1bbf-41a6-96fa-862e42182b67/disable + method: POST + links.ReenableChannelCatalogProductLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/578419df-1bbf-41a6-96fa-862e42182b67/reenable + method: POST + links.OverrideChannelCatalogProductValuesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/578419df-1bbf-41a6-96fa-862e42182b67/overrides + method: POST + links.GetChannelCatalogProductValueOverrideCopyLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/578419df-1bbf-41a6-96fa-862e42182b67/overrides/copy + method: GET + links.ConfigureChannelCatalogProductValueOverrideCopyLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/products/578419df-1bbf-41a6-96fa-862e42182b67/overrides/copy + method: POST + channelCatalogExportCacheInfoResponse: + required: + - cacheInfo + - links + type: object + properties: + cacheInfo: + $ref: '#/components/schemas/channelCatalogExportCacheInfo' + links: + $ref: '#/components/schemas/channelCatalogExportCacheInfoResponseLinks' + channelCatalogExportCacheInfoResponseLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogExportationCacheInfoLink' + clear: + $ref: '#/components/schemas/links.ClearChannelCatalogExportationCacheLink' + channelCatalogExportCacheInfo: + required: + - cacheStatus + type: object + properties: + cacheStatus: + type: string + description: The cache status + example: ReadyForGeneration + x-lov: ChannelCatalogExportCacheStatus + lastUpdateUtcDate: + type: string + description: The last update UTC date of the cache + format: date-time + example: 2014-08-25T07:32:31.584Z + lastContentChangeUtcDate: + type: string + description: The last content change UTC date + format: date-time + example: 2014-08-25T07:30:31.584Z + expirationUtcDate: + type: string + description: The expiration UTC date of the cache + format: date-time + example: 2014-08-25T08:02:31.584Z + feedUrl: + type: string + description: The feed url + example: https://www.scootmotoshop.com/feed.xml + channelCatalogExportationHistoryLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogExportationHistoryLink' + channelCatalogExportationHistory: + required: + - exportations + - links + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + exportations: + type: array + items: + $ref: '#/components/schemas/channelCatalogExportationReporting' + links: + $ref: '#/components/schemas/channelCatalogExportationHistoryLinks' + channelCatalogExportationReporting: + required: + - clientIpAddress + - clientUserAgent + - exportationUtcDate + type: object + properties: + exportationUtcDate: + type: string + description: The exportation UTC date + format: date-time + example: 2014-08-25T07:32:31.584Z + exportationDuration: + pattern: >- + (00:1[5-9])|(00:[2-5][0-9])|(0[1-9]:[0-5][0-9])|(1[0-9]:[0-5][0-9])|(2[0-3]:[0-5][0-9]) + type: string + description: | + The exportation duration. \ + '00:01:00' measn 1 minute. + example: '00:01:00' + cacheStatus: + type: string + description: The cache status during the exportation + example: Available + x-lov: ChannelCatalogExportationCacheGenerationStatus + exportedProductCount: + type: integer + description: The exportated product count during this exportation + format: int32 + example: 10142 + clientIpAddress: + type: string + description: The IP address of the client who requests this exportation + example: 42.101.42.101 + clientUserAgent: + type: string + description: >- + The http header User-Agent sent by the client who requests this + operation + example: Wget/1.13.4 (linux-gnu) + externalLinks.Catalog_GetBeezUPColumnsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/catalogs/beezUPColumns + method: GET + channelCatalogListLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogsLink' + beezUPColumns: + $ref: '#/components/schemas/externalLinks.Catalog_GetBeezUPColumnsLink' + add: + $ref: '#/components/schemas/links.AddChannelCatalogLink' + filterOperators: + $ref: '#/components/schemas/links.GetChannelCatalogFilterOperatorsLink' + description: > + Indicates how global actions you can do like how to create a channel + catalog, exclusion filter operators, etc... + channelCatalogListLovLinks: + type: object + properties: + channelCatalogExclusionFilterOperatorLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + channelCatalogExportCacheStatusLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + channelCatalogList: + type: object + properties: + links: + $ref: '#/components/schemas/channelCatalogListLinks' + lovLinks: + $ref: '#/components/schemas/channelCatalogListLovLinks' + channelCatalogs: + type: object + additionalProperties: + $ref: '#/components/schemas/channelCatalog' + description: The channel catalog list. The key is the channel catalog identifier + description: This is the index of the channel catalog API + addChannelCatalogRequest: + required: + - channelId + - storeId + type: object + properties: + channelId: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + storeId: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + generalSettings: + required: + - acceptToPublishInfo + - activeBeezUPTracking + - doNotExportOutOfStockProducts + type: object + properties: + acceptToPublishInfo: + type: boolean + description: >- + If true then you authorize disclosure of my statistics generated + from clicks and sales + example: true + doNotExportOutOfStockProducts: + type: boolean + description: > + Do not export "out of stock" products. Note: this option is not + taken into account by the counter. + example: true + activeBeezUPTracking: + type: boolean + description: Activate BeezUP tracking for my statistics (checked by default) + example: true + default: true + description: Represents the general settings of your channel catalog + costType: + type: string + description: | + CPC means cost per click. + CPA means cost per action. + You can have CPC/CPA with a global cost value. + You can have CPC/CPA by category the cost value MUST be null + You can have global fixed price. + example: Fixed_Global + enum: + - CPC_Global + - CPA_Global + - CPC_ByCategory + - CPA_ByCategory + - Fixed_Global + channelCostSettings: + required: + - costType + type: object + properties: + costType: + $ref: '#/components/schemas/costType' + globalCostValue: + type: number + description: In case of global cost type, you have to indicate the cost value. + format: decimal + example: 10.21 + description: Indicate the default configuration of the cost on this channel. + costSettings: + required: + - costType + type: object + properties: + costType: + $ref: '#/components/schemas/costType' + globalCostValue: + type: number + description: In case of global cost type, you have to indicate the cost value. + format: decimal + example: 10.21 + description: > + If this property is not indicated please force the user to configure the + cost settings. + + Defines the cost type you have on this channel with the cost value. + unmapCategoryRequest: + required: + - catalogCategoryPath + type: object + properties: + catalogCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryPath' + description: >- + The request message to unmap a catalog category path to a channel + category path + configureCategoryRequest: + required: + - channelCatalogCategories + - overrideSubCategoryMappings + type: object + properties: + overrideSubCategoryMappings: + type: boolean + description: >- + Great feature! In case of mapping to parent channel category, you + can ask to override the mapping of all sub channel category to this + catalog category path + example: true + channelCatalogCategories: + type: array + items: + $ref: '#/components/schemas/channelCatalogCategoryConfiguration' + description: >- + The request message to make a mapping between catalog category path and + a channel category path + channelCatalogCategoryMappingsLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogCategoriesLink' + disable: + $ref: '#/components/schemas/links.DisableChannelCatalogCategoryMappingLink' + reenable: + $ref: '#/components/schemas/links.ReenableChannelCatalogCategoryMappingLink' + description: The action you can do on the category mappings + channelCatalogCategoryConfigurationList: + required: + - channelCatalogCategoryConfigurations + - costStatus + - links + - mappingStatus + type: object + properties: + links: + $ref: '#/components/schemas/channelCatalogCategoryMappingsLinks' + channelCatalogCategoryConfigurations: + type: array + items: + $ref: '#/components/schemas/channelCatalogCategoryConfigurationInfo' + mappingStatus: + $ref: '#/components/schemas/mappingStatus' + costStatus: + $ref: '#/components/schemas/costStatus' + mappingStatus: + type: string + example: required + enum: + - required + - optional + - notConfigurable + costStatus: + type: string + example: required + enum: + - required + - optional + - notConfigurable + channelCatalogCategoryMappingInfoLinks: + type: object + properties: + configureCategories: + $ref: '#/components/schemas/links.ConfigureChannelCatalogCategoryLink' + channelCatalogCategoryConfigurationInfo: + required: + - catalogCategoryPath + - links + type: object + properties: + links: + $ref: '#/components/schemas/channelCatalogCategoryMappingInfoLinks' + catalogCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryPath' + channelCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryPath' + costValue: + $ref: '#/components/schemas/channelCatalogCategoryCostValue' + description: For all catalog categories the current mapping applied + channelCatalogCategoryCostValue: + type: number + description: >- + In case of CPC_ByCategory or CPA_ByCategory cost type, you have to + indicate the cost value. + format: decimal + example: 10.21 + channelCatalogCategoryConfiguration: + required: + - autoMapNewSubCategories + - catalogCategoryPath + type: object + properties: + autoMapNewSubCategories: + type: boolean + description: >- + Great feature! In case of mapping to parent catalog category, you + can ask to automatically map new sub catalog category in the next + importation to this channel category path. + example: true + catalogCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryPath' + channelCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryPath' + costValue: + $ref: '#/components/schemas/channelCatalogCategoryCostValue' + description: > + Represent a mapping between a catalog category path and a channel + category path. + + The cost on this mapping can be applied. + channelCatalogColumnMappingWithName: + allOf: + - $ref: '#/components/schemas/channelCatalogColumnMapping' + - required: + - channelColumnName + type: object + properties: + channelColumnName: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnName' + channelBeezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + catalogColumnName: + $ref: '#/components/schemas/BeezUP_Common_CatalogColumnUserName' + catalogBeezUPColumnName: + $ref: '#/components/schemas/BeezUP_Common_BeezUPColumnName' + channelCatalogColumnMapping: + required: + - channelColumnId + type: object + properties: + channelColumnId: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnId' + channelCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryPath' + catalogColumnId: + $ref: '#/components/schemas/BeezUP_Common_CatalogColumnId' + description: >- + Represent a mapping between a channel column (considering channel + category mapping) and a catalog column + upgradeOfferRequired: + required: + - offerId + type: object + properties: + offerId: + type: integer + description: The offer identifier required + format: int32 + example: 9 + description: >- + The message contains the offer identifier required to execute this + operation + channelCatalogColumnMappingListWithName: + type: array + description: The column mapping list between a channel and a catalog + items: + $ref: '#/components/schemas/channelCatalogColumnMappingWithName' + channelCatalogColumnMappingList: + type: array + description: The column mapping list between a channel and a catalog + items: + $ref: '#/components/schemas/channelCatalogColumnMapping' + channelCatalogState: + required: + - categoryMappingState + - columnMappingStatus + - exportedProductCount + type: object + properties: + exportedProductCount: + type: integer + format: int32 + example: 101 + columnMappingStatus: + $ref: '#/components/schemas/columnMappingStatus' + categoryMappingState: + $ref: '#/components/schemas/categoryMappingState' + apiSettingsStatus: + $ref: '#/components/schemas/BeezUP_Common_ApiSettingsStatus' + description: Channel Catalog State + columnMappingStatus: + type: string + example: success + enum: + - warning + - success + - failed + categoryMappingState: + type: object + properties: + status: + $ref: '#/components/schemas/categoryMappingStatus' + uncategorizedProductCount: + type: integer + description: Indicates the uncategorized product count + format: int32 + example: 101 + withoutCategoryCostProductCount: + type: integer + description: Indicates the count of products without cost defined + format: int32 + example: 42 + description: The category mapping state of the channel catalog + categoryMappingStatus: + type: string + example: success + enum: + - warning + - success + - failed + channelCategorySettings: + type: object + properties: + mappingRequired: + type: boolean + description: >- + Indicates if the category mapping is required, otherwise you can map + the categories but it will not block the publication of your catalog + example: true + mappingLeafRequired: + type: boolean + description: >- + Indicates if the category mapping is required on category path leaf + or not + example: true + channelCatalogCategoryMappingSettings: + type: object + properties: + categoryMappingDisabledByMerchant: + type: boolean + description: >- + Optional parameter. Indicates that you have decided to do not map + your categories with the channel's categories. + example: false + channelCatalog: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + - required: + - channelCatalogId + - channelCategorySettings + - channelCostSettings + - enabled + - generalSettings + - isMarketplace + - links + - state + - storeId + - types + type: object + properties: + enabled: + type: boolean + description: Indicates if the channel catalog is enable + example: true + isMarketplace: + type: boolean + description: Indicates if this channel catalog is related to a marketplace + example: true + channelCatalogId: + $ref: '#/components/schemas/BeezUP_Common_ChannelCatalogId' + storeId: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + generalSettings: + $ref: '#/components/schemas/generalSettings' + channelCostSettings: + $ref: '#/components/schemas/channelCostSettings' + channelCategorySettings: + $ref: '#/components/schemas/channelCategorySettings' + costSettings: + $ref: '#/components/schemas/costSettings' + categoryMappingSettings: + $ref: '#/components/schemas/channelCatalogCategoryMappingSettings' + columnMappings: + $ref: '#/components/schemas/channelCatalogColumnMappingListWithName' + exclusionFilters: + $ref: '#/components/schemas/exclusionFilters' + exportUrl: + $ref: '#/components/schemas/BeezUP_Common_HttpUrl' + state: + $ref: '#/components/schemas/channelCatalogState' + types: + type: array + description: The channel type list related to the channel + example: + - Marketplace + items: + type: string + links: + $ref: '#/components/schemas/channelCatalogLinks' + description: The channel catalog + externalLinks.GetChannelCatalogMarketplaceSettingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/channelcatatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/settings + method: GET + externalLinks.GetChannelInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/channels/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + method: GET + channelCatalogLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogLink' + delete: + $ref: '#/components/schemas/links.DeleteChannelCatalogLink' + enable: + $ref: '#/components/schemas/links.EnableChannelCatalogLink' + disable: + $ref: '#/components/schemas/links.DisableChannelCatalogLink' + configureGeneralSettings: + $ref: >- + #/components/schemas/links.ConfigureChannelCatalogGeneralSettingsLink + configureCostSettings: + $ref: '#/components/schemas/links.ConfigureChannelCatalogCostSettingsLink' + configureColumnMappings: + $ref: '#/components/schemas/links.ConfigureChannelCatalogColumnMappingsLink' + reenableCategoryMappings: + $ref: '#/components/schemas/links.ReenableChannelCatalogCategoryMappingLink' + disableCategoryMappings: + $ref: '#/components/schemas/links.DisableChannelCatalogCategoryMappingLink' + categoryMappings: + $ref: '#/components/schemas/links.GetChannelCatalogCategoriesLink' + exclusionFilters: + $ref: '#/components/schemas/links.GetChannelCatalogExclusionFiltersLink' + products: + $ref: '#/components/schemas/links.GetChannelCatalogProductInfoListLink' + exportationCacheInfo: + $ref: '#/components/schemas/links.GetChannelCatalogExportationCacheInfoLink' + marketplaceSettings: + $ref: >- + #/components/schemas/externalLinks.GetChannelCatalogMarketplaceSettingsLink + channelInfo: + $ref: '#/components/schemas/externalLinks.GetChannelInfoLink' + description: Indicates the actions you can do on a channel catalog + productOverridesCopyResponse: + type: object + additionalProperties: + type: string + description: Product overrides compatibilites list + example: + 8a76f06a-fefc-4c0d-bcfe-b210f1482977: '3563' + B7B79A0B-A8DE-54DA-964C-E2704DF3738A: SHBELNL56 + 57F70E81-E4F2-5034-BC65-E1D5C48EBEDA: Sony bravia + 2A77749D-0AAB-5245-89B5-6A1A4E06DACA: http://www.blalbla.nl/images/cache/dldldl.jpg + 54B3B3CB-5CA5-5471-9DAE-5310C032059A: http://www.blalbla.nl/images/cache/dlmdl.jpg + 0EA21509-1141-57BD-B679-371BC98B2ADA: http://www.blalbla.nl/images/cache/ldldld.jpg + productOverrides: + type: object + additionalProperties: + type: string + description: The key is the channel column identifier + example: + 8a76f06a-fefc-4c0d-bcfe-b210f1482977: '3563' + B7B79A0B-A8DE-54DA-964C-E2704DF3738A: SHBELNL56 + 57F70E81-E4F2-5034-BC65-E1D5C48EBEDA: Sony bravia + 2A77749D-0AAB-5245-89B5-6A1A4E06DACA: http://www.blalbla.nl/images/cache/dldldl.jpg + 54B3B3CB-5CA5-5471-9DAE-5310C032059A: http://www.blalbla.nl/images/cache/dlmdl.jpg + 0EA21509-1141-57BD-B679-371BC98B2ADA: http://www.blalbla.nl/images/cache/ldldld.jpg + productOverridesWithCatalogValues: + type: object + additionalProperties: + $ref: '#/components/schemas/productOverrideWithCatalogValue' + description: The key is the channel column identifier + example: + 8a76f06a-fefc-4c0d-bcfe-b210f1482977: + catalogValue: x235 + override: '3563' + B7B79A0B-A8DE-54DA-964C-E2704DF3738A: + catalogValue: x_ezlSHBELNL56 + override: SHBELNL56 + 57F70E81-E4F2-5034-BC65-E1D5C48EBEDA: + catalogValue: Sony + override: Sony bravia + 2A77749D-0AAB-5245-89B5-6A1A4E06DACA: + catalogValue: http://www.toto.com/thing/images/cache/dldldl.jpg + override: http://www.blalbla.nl/images/cache/dldldl.jpg + 54B3B3CB-5CA5-5471-9DAE-5310C032059A: + catalogValue: http://www.toto.com/thing/cache/dlmdl.jpg + override: http://www.blalbla.nl/images/cache/dlmdl.jpg + 0EA21509-1141-57BD-B679-371BC98B2ADA: + catalogValue: http://www.toto.com/thing/images/cache/ldldld.jpg + override: http://www.blalbla.nl/images/cache/ldldld.jpg + productOverrideWithCatalogValue: + required: + - override + type: object + properties: + override: + type: string + description: The overridden product value + example: Sony bravia + catalogValue: + type: string + description: The catalog product value + example: Sony + exclusionFiltersResponseLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogExclusionFiltersLink' + configure: + $ref: >- + #/components/schemas/links.ConfigureChannelCatalogExclusionFiltersLink + exclusionFiltersResponse: + required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/exclusionFiltersResponseLinks' + exclusionFilters: + $ref: '#/components/schemas/exclusionFilters' + exclusionFilters: + type: array + description: The exclusion filter list + items: + $ref: '#/components/schemas/exclusionFilter' + exclusionFilterName: + type: string + description: The exclusion filter name + example: Exclude sony products + exclusionFilter: + required: + - channelColumnId + - enabled + - groupId + - name + - operatorName + - position + - positionInGroup + type: object + properties: + name: + $ref: '#/components/schemas/exclusionFilterName' + position: + minimum: 1 + type: integer + description: The position of the exclusion filter + format: int32 + example: 1 + groupId: + type: string + description: >- + Indicate the filter's group. All filters in the same group means an + "AND" operation in the filter group + format: guid + example: d9833f4b-718a-436f-bab5-89da3d21bf60 + positionInGroup: + minimum: 1 + type: integer + description: >- + Indicate the filter group position. This information is used for the + UI purpose and must be unique in the filter group. + format: int32 + example: 1 + channelColumnId: + $ref: '#/components/schemas/BeezUP_Common_ChannelColumnId' + operatorName: + $ref: '#/components/schemas/filterOperatorName' + value: + maxLength: 4000 + type: string + description: >- + The value indicate by the user when the filter operation requires + it. + example: sony + enabled: + type: boolean + description: indicates if the filter is currently enable. + example: true + description: The exclusion filter + filterOperatorName: + type: string + description: The exclusion filter operator name + example: Contains + x-lov: ProductColumnFilterOperatorName + filterOperatorDataType: + type: string + description: Data type of the operator + example: string + default: string + enum: + - string + - number + filterOperator: + type: object + properties: + name: + $ref: '#/components/schemas/filterOperatorName' + expectedChannelColumnDataType: + $ref: '#/components/schemas/filterOperatorDataType' + valueRequired: + type: boolean + description: This operator requires a value + example: true + expectedValueDataType: + $ref: '#/components/schemas/filterOperatorDataType' + description: The filter operator + productSetVisibilityCriteriaLogicType: + type: string + description: > + Indicate how you want to combine the filters: + + * funnel: You will get the products which meet at least one of the + product set criterion. The criteria are applied in the following order: + - categorization + - exclusion filters + - deactivations + * cumulative: You will get the products which have all the product set + criteria + enum: + - funnel + - cumulative + productSetVisibilityCriteria: + required: + - logic + type: object + properties: + logic: + $ref: '#/components/schemas/productSetVisibilityCriteriaLogicType' + exist: + type: boolean + description: >- + If false, search for products absent from the current catalog. If + true, search for products currently in the catalog. If null the + filter will not be taken in account. + example: true + uncategorized: + type: boolean + description: >- + Search product WITHOUT category mapped with the channel. If null the + filter will not be taken in account. + example: false + excluded: + type: boolean + description: >- + Search excluded products by at least an exclusion filter. If null + the filter will not be taken in account. + example: false + disabled: + type: boolean + description: >- + Search disabled products. If null the filter will not be taken in + account. + example: false + getChannelCatalogProductInfoListRequest: + required: + - criteria + - pageNumber + - pageSize + type: object + properties: + pageNumber: + minimum: 1 + type: integer + format: int32 + example: 1 + pageSize: + minimum: 100 + type: integer + format: int32 + example: 100 + criteria: + $ref: '#/components/schemas/productSetVisibilityCriteria' + overridden: + type: boolean + description: >- + Search overridden products. If null the filter will not be taken in + account. + example: true + productFilters: + $ref: '#/components/schemas/channelCatalogProductFilters' + catalogCategoryFilter: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryFilter' + channelCategoryFilter: + $ref: '#/components/schemas/BeezUP_Common_ChannelCategoryFilter' + channelCatalogProductFilters: + type: object + properties: + catalogSkus: + type: array + description: The catalog product SKU filter (multiple values) + items: + type: string + catalogEans: + type: array + description: The catalog product EAN filter (multiple values) + items: + type: string + catalogMpns: + type: array + description: The catalog product MPN filter (multiple values) + items: + type: string + channelSkus: + type: array + description: The channel product SKU filter (multiple values) + items: + type: string + channelEans: + type: array + description: The channel product EAN filter (multiple values) + items: + type: string + channelMpns: + type: array + description: The channel product MPN filter (multiple values) + items: + type: string + title: + type: string + description: The product title filter + example: Refrigérateur + additionalProductFilters: + $ref: '#/components/schemas/BeezUP_Common_AdditionalProductFilters' + channelCatalogProductsCounters: + type: object + properties: + existingProductCount: + type: integer + description: Imported product count currently in your catalog. + format: int32 + example: 1000 + uncategorizedProductCount: + type: integer + description: Product count WITHOUT category mapped on existing products. + format: int32 + example: 250 + disabledProductCountIncludingUncategorized: + type: integer + description: >- + Disabled product count INCLUDING uncategorized products on existing + products. + format: int32 + example: 169 + disabledProductCountExcludingUncategorized: + type: integer + description: >- + Disabled product count EXCLUDING uncategorized products on existing + products. + format: int32 + example: 150 + excludedProductCountIncludingUncategorizedAndDisabled: + type: integer + description: >- + Excluded product count INCLUDING uncategorized products AND disabled + products on existing products. + format: int32 + example: 66 + excludedProductCountExcludingUncategorizedAndDisabled: + type: integer + description: >- + Excluded product count EXCLUDING uncategorized products AND disabled + products on existing products. + format: int32 + example: 50 + description: >- + The channel catalog products counters. For each counter you will have a + count. + channelCatalogProductInfoListLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogProductInfoListLink' + export: + $ref: '#/components/schemas/links.ExportChannelCatalogProductInfoListLink' + channelCatalogProductInfoList: + required: + - links + - paginationResult + - productInfos + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + links: + $ref: '#/components/schemas/channelCatalogProductInfoListLinks' + productInfos: + type: array + items: + $ref: '#/components/schemas/channelCatalogProductInfo' + description: The channel catalog product info list + channelCatalogProductInfo: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_ProductBasicInfo' + - required: + - disabled + - excluded + - links + - overrides + - uncategorized + type: object + properties: + overrides: + $ref: '#/components/schemas/productOverridesWithCatalogValues' + disabled: + type: boolean + description: Indicates if the product has been disabled or not + example: false + default: false + uncategorized: + type: boolean + description: >- + Indicates if the product's category has been NOT mapped to a + channel category + example: true + excluded: + type: boolean + description: Indicates if the product has been excluded by a exclusion filter + example: true + default: false + excludedBy: + type: array + example: + - Exclude sony products + items: + $ref: '#/components/schemas/exclusionFilterName' + links: + $ref: '#/components/schemas/channelCatalogProductInfoLinks' + description: The channel catalog product information + channelCatalogProductInfoLinks: + required: + - override + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogProductInfoLink' + override: + $ref: '#/components/schemas/links.OverrideChannelCatalogProductValuesLink' + disable: + $ref: '#/components/schemas/links.DisableChannelCatalogProductLink' + reenable: + $ref: '#/components/schemas/links.ReenableChannelCatalogProductLink' + description: Indicates the differents actions you can do on a channel product + channelCatalogProductByChannelCatalogRequest: + required: + - channelCatalogIds + - productId + - storeId + type: object + properties: + storeId: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + productId: + $ref: '#/components/schemas/BeezUP_Common_ProductId' + channelCatalogIds: + type: array + description: The list of channel catalog identifier + items: + $ref: '#/components/schemas/BeezUP_Common_ChannelCatalogId' + channelCatalogProductByChannelCatalogResponse: + type: object + properties: + channelCatalogs: + type: object + additionalProperties: + $ref: '#/components/schemas/channelCatalogProductInfo' + description: >- + The channel catalog product by channel catalog. The key is the + channel catalog identifier + BeezUP_Common_CatalogCategoryFilter: + type: object + properties: + categoryPath: + type: array + description: Indicates on which catalog category path you want to make the filter + example: + - Maison + - Chambre + items: + type: string + BeezUP_Common_ChannelCategoryFilter: + type: object + properties: + categoryPath: + type: array + description: Indicates on which channel category path you want to make the filter + example: + - Home + - Bedroom + items: + type: string + BeezUP_Common_ChannelCatalogId: + type: string + description: The channel catalog identifier + format: guid + example: 6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + BeezUP_Common_ChannelBasicInfo: + required: + - channelId + - channelImageUrl + - channelName + type: object + properties: + channelId: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + channelName: + $ref: '#/components/schemas/BeezUP_Common_ChannelName' + channelImageUrl: + $ref: '#/components/schemas/BeezUP_Common_HttpUrl' + description: The basic info related to a channel + BeezUP_Common_AdditionalProductFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/BeezUP_Common_AdditionalProductFiltersValue' + description: | + Describe a filter on a product's column. + The key is the column identifier of your catalog or a custom column. + BeezUP_Common_ProductBasicInfo: + required: + - productExists + - productId + - productSku + - productTitle + type: object + properties: + productId: + type: string + description: The product identifier + format: guid + example: 00000000-0000-0000-0000-000000000000 + productSku: + type: string + description: The product SKU + example: SKU1234 + productTitle: + type: string + description: The product tile + example: My supert product + productImageUrl: + type: string + description: The product image Url + format: uri + example: >- + http://i2.cdscdn.com/pdt2/3/9/0/1/550x550/hai6901018043390/rw/haier-b20fwrss-refrigerateur-americain.jpg + productExists: + type: boolean + description: Indicates if the product still exists in your catalog + example: true + description: The basic information related to a product + BeezUP_Common_ApiSettingsStatus: + type: string + example: success + enum: + - warning + - success + - failed + BeezUP_Common_AdditionalProductFiltersValue: + type: object + properties: + operatorName: + $ref: '#/components/schemas/BeezUP_Common_ProductColumnFilterOperatorName' + values: + type: array + description: > + Must be null if the operator is "IsNull" or "IsNotNull". + + Can contains multiple value in case of "InList" operator. Otherwise + a single value is expected. + example: + - My value + items: + type: string + example: + 672644c7-5bd0-4e25-88c1-1f732bda5e4c: + operatorName: GreaterTo + values: + - '100' + BeezUP_Common_CatalogColumnUserName: + type: string + description: The catalog column named by the user (catalog or custom column) + example: My title + BeezUP_Common_ProductColumnFilterOperatorName: + type: string + description: Indicate the operator you want to make on the columnId + x-lov: ProductColumnFilterOperatorName + publicationStrategy: + type: string + description: The Publication Type + x-lov: MarketplacePublicationV3Strategy + publicationType: + type: string + description: The Publication Type + example: PublishOffers + enum: + - PublishProducts + - PublishOffers + - Unpublish + x-lov: MarketplacePublicationType + feedType: + type: string + description: The Feed Type + example: Offers + enum: + - Products + - Inventory + - Pricing + - Images + - Relationships + - Unpublish + - Offers + x-lov: MarketplacePublicationFeedType + accountPublicationsLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetPublicationsLink' + accountPublications: + required: + - links + - publications + type: object + properties: + links: + $ref: '#/components/schemas/accountPublicationsLinks' + publications: + type: array + description: The recent publications for the requested account + example: + - publicationType: PublishOffers + feeds: + - feedType: Offers + startUtcDate: 2016-02-13T12:01:11.000Z + endUtcDate: 2016-02-13T12:02:00.000Z + processingStatus: Done + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + - feedType: Inventory + startUtcDate: 2016-02-13T12:01:11.000Z + endUtcDate: 2016-02-13T12:02:00.000Z + processingStatus: Done + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + - feedType: Pricing + startUtcDate: 2016-02-13T12:01:11.000Z + processingStatus: InProgress + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + - publicationType: PublishProducts + feeds: + - feedType: Product + startUtcDate: 2016-02-13T12:01:11.000Z + endUtcDate: 2016-02-13T12:02:00.000Z + processingStatus: Done + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + - feedType: Inventory + startUtcDate: 2016-02-13T12:01:11.000Z + endUtcDate: 2016-02-13T12:02:00.000Z + processingStatus: Done + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + - feedType: Pricing + startUtcDate: 2016-02-13T12:01:11.000Z + processingStatus: InProgress + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + items: + $ref: '#/components/schemas/publicationReporting' + description: The publication history for an account + publicationReporting: + required: + - feeds + - publicationType + type: object + properties: + publicationType: + $ref: '#/components/schemas/publicationType' + feeds: + type: array + description: The feeds that were published + example: + - feedType: Offers + startUtcDate: 2016-02-13T12:01:11.000Z + endUtcDate: 2016-02-13T12:02:00.000Z + processingStatus: Done + exportedProducts: '10142' + transmittedItems: '10042' + publishedItems: '10041' + publishedItemsWithWarning: '123' + failedItems: '1' + errorMessage: '' + htmlReportUrl: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: '' + items: + $ref: '#/components/schemas/publicationFeedReporting' + description: Model for a publication reporting, can have multiple feeds + publicationFeedReporting: + required: + - feedType + - processingStatus + - startUtcDate + type: object + properties: + feedType: + $ref: '#/components/schemas/feedType' + startUtcDate: + type: string + description: The feed publication start time (UTC timezone) + format: date-time + example: 2016-02-13T12:01:11.000Z + endUtcDate: + type: string + description: The feed publication end time (UTC timezone) + format: date-time + example: 2016-02-13T12:02:00.000Z + processingStatus: + type: string + description: The processing status + example: Done + exportedProducts: + type: integer + description: The product count downloaded from BeezUP Export + format: int32 + example: 10142 + transmittedItems: + type: integer + description: The item count (products or offers) sent to the marketplace + format: int32 + example: 10042 + publishedItems: + type: integer + description: >- + The item count (products or offers) the marketplace flagged as + successful + format: int32 + example: 10041 + publishedItemsWithWarning: + type: integer + description: >- + The item count (products or offers) the marketplace flagged as + successful with warnings + format: int32 + example: 123 + failedItems: + type: integer + description: >- + The item count (products or offers) the marketplace flagged as + failed + format: int32 + example: 1 + errorMessage: + type: string + description: The error message + example: '' + htmlReportUrl: + type: string + description: The Url for the Html Report generated + format: uri + example: http://www.myreporthtml.com + htmlReportGenerationErrorMessage: + type: string + description: The error message if the Html Report generation failed + example: Example error message + completed: + type: boolean + description: Indicates if the publication is completed or not + example: true + description: Publication feed reporting + links.GetChannelCatalogMarketplacePropertiesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/channelcatatalogs/6a90fcfd-24c7-422e-a65f-aadb1725bbfe/properties + externalLinks.GetExternalConfigurationPageLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + channelCatalogMarketplacePropertiesLinks: + required: + - self + type: object + properties: + self: + $ref: >- + #/components/schemas/links.GetChannelCatalogMarketplacePropertiesLink + settings: + $ref: '#/components/schemas/links.GetChannelCatalogMarketplaceSettingsLink' + externalConfigurationPage: + $ref: '#/components/schemas/externalLinks.GetExternalConfigurationPageLink' + channelCatalogMarketplaceProperties: + required: + - links + - propertyGroups + type: object + properties: + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + links: + $ref: '#/components/schemas/channelCatalogMarketplacePropertiesLinks' + propertyGroups: + type: array + description: The groups settings with constraints + example: + - name: AccountInformations + position: '1' + properties: + - name: EbayToken + position: '1' + readOnly: 'true' + values: + - >- + AgAAAA**AQAAAA**aAAAAA**2VFhVg**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AElISgCJaLpwWdj6x9nY+seQ**OEsBAA**AAMAAA**jzsVAMwj1dPBsyCEp0Fuj/toSBrfZF2JpKKDrrXIirMzgvgbsyxnA2h1wl7WjFD+TfdCmaBq3CAFLOog/433G5gsse1DLTT6uXFajdiHnPVfnL7QtKIpQEIwL8ZO5Tx1dGl0XQLsU7knPwbGHn5X6Z3JzXrCGvvpw2+MIzDNhasYlqPfOEr8Lct5dcsIIdhXl/qgrzALe5++v76/XjaXvP6eic3uCWBEXBiXC1uisjEtOqaNIPkFaiICBaXsQUzVZdM68bQatBg5bwf6hxvqOyNJRw4pttGStovcXXjL+aszw7ejbxLv1lJ6qeTMj5oRwTPl0AzBAejcY+DTBrLEmgdzrvWHLvMOa1ijGOGzVodBoDGimiqadCPQpAVZr0e7HvQIVbOlbmKpuCUFJ4RPCv0NxpkCm1/nxZWeS9H8gd/SfLf9Chgd115dcKzgxFBoSh7myJcw+MRM7szPQ2Pwv980dTRyHvbI8XR4OieYvXmU4H7Nl51N8B3qkjYFkdcp6J06eqs4dO68lDNdWZfXHkjwI3dY6umDUp4y82IdQl8IykPty3/DZfUAfqafgiAwMHZvXjewp5HhPjDi2zgf+5EcDlvf6rNMzjsghjdWUQi4WldDk+LXgkos6jswIQaNPdpW1D4KyPYWtGYknx0Xzzuc6WmBoVwGFalgMvCWWI9Gs2w6PG5GqB9zm1Fnr3svtPbNYPQ6q3VQpkKL2SWQXy383O1cp6ZMLI9GwZe0FnrqCxb/wc4XJUVw2RoR3qiX + - name: PayPalEmailAddress + position: '2' + required: true + pattern: >- + (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) + x-pattern: >- + (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) + - displayGroupCode: AnnounceTitle + displayGroupPosition: '2' + properties: + - name: Postalcode + required: true + position: '1' + - name: Country + position: '2' + required: true + lovLink: + href: /v2/user/lov/Country_eBay + lovRequired: 'true' + - name: ReturnsWithinOption + position: '3' + required: true + lovLink: + href: /v2/user/lov/ReturnsWithinDuration_eBay + lovRequired: 'true' + - name: ShippingService + position: '4' + required: true + lovLink: + href: /v2/user/lov/FRA_ShippingService_eBay + lovRequired: 'true' + - name: Currency + position: '5' + required: true + lovLink: + href: /v2/user/lov/Currency_eBay + lovRequired: 'true' + - name: PaymentMethods + position: '6' + required: true + lovLink: + href: /v2/user/lov/PaymentMethods_eBay + lovRequired: 'true' + minItems: 1 + maxItems: 2 + - displayGroupCode: SalesConditions + displayGroupPosition: '3' + properties: + - name: ReturnsAcceptedOption + position: '1' + required: true + lovLink: + href: /v2/user/lov/ReturnsAcceptedOption_eBay + lovRequired: 'true' + - name: ShippingCostPaidByOption + position: '2' + required: true + lovLink: + href: /v2/user/lov/ShippingCostPaidByOption_eBay + lovRequired: 'true' + - name: RefundOption + position: '3' + required: true + lovLink: + href: /v2/user/lov/RefundOption_eBay + lovRequired: 'true' + - name: ReturnsWithinOption + position: '4' + required: true + lovLink: + href: /v2/user/lov/ReturnsWithinDuration_eBay + lovRequired: 'true' + - name: ReturnDescription + position: '5' + required: false + maxLength: 5000 + - displayGroupCode: HTML + displayGroupPosition: '4' + properties: + - name: Template_HTML + position: '1' + required: false + maxLength: 50000 + - displayGroupCode: OrdersRetrievalOptions + displayGroupPosition: '5' + properties: + - name: RetrieveOnlyOneCountry + description: If true allows to retireve one marketplace country only + position: '1' + type: boolean + required: false + items: + $ref: '#/components/schemas/channelCatalogMarketplacePropertyGroup' + channelCatalogMarketplacePropertyGroup: + required: + - name + - position + - properties + type: object + properties: + name: + type: string + description: Indicate the code identifier of the group + example: AccountInformations + x-lov: MarketplaceStorePropertyGroup + position: + minimum: 1 + type: integer + description: Indicate the position of the group + example: 1 + properties: + type: array + example: + - name: EbayToken + position: '1' + readOnly: 'true' + values: + - >- + AgAAAA**AQAAAA**aAAAAA**2VFhVg**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AElISgCJaLpwWdj6x9nY+seQ**OEsBAA**AAMAAA**jzsVAMwj1dPBsyCEp0Fuj/toSBrfZF2JpKKDrrXIirMzgvgbsyxnA2h1wl7WjFD+TfdCmaBq3CAFLOog/433G5gsse1DLTT6uXFajdiHnPVfnL7QtKIpQEIwL8ZO5Tx1dGl0XQLsU7knPwbGHn5X6Z3JzXrCGvvpw2+MIzDNhasYlqPfOEr8Lct5dcsIIdhXl/qgrzALe5++v76/XjaXvP6eic3uCWBEXBiXC1uisjEtOqaNIPkFaiICBaXsQUzVZdM68bQatBg5bwf6hxvqOyNJRw4pttGStovcXXjL+aszw7ejbxLv1lJ6qeTMj5oRwTPl0AzBAejcY+DTBrLEmgdzrvWHLvMOa1ijGOGzVodBoDGimiqadCPQpAVZr0e7HvQIVbOlbmKpuCUFJ4RPCv0NxpkCm1/nxZWeS9H8gd/SfLf9Chgd115dcKzgxFBoSh7myJcw+MRM7szPQ2Pwv980dTRyHvbI8XR4OieYvXmU4H7Nl51N8B3qkjYFkdcp6J06eqs4dO68lDNdWZfXHkjwI3dY6umDUp4y82IdQl8IykPty3/DZfUAfqafgiAwMHZvXjewp5HhPjDi2zgf+5EcDlvf6rNMzjsghjdWUQi4WldDk+LXgkos6jswIQaNPdpW1D4KyPYWtGYknx0Xzzuc6WmBoVwGFalgMvCWWI9Gs2w6PG5GqB9zm1Fnr3svtPbNYPQ6q3VQpkKL2SWQXy383O1cp6ZMLI9GwZe0FnrqCxb/wc4XJUVw2RoR3qiX + - name: PaypalAddress + position: '2' + required: true + pattern: >- + (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) + x-pattern: >- + (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) + items: + $ref: '#/components/schemas/channelCatalogMarketplaceProperty' + type: + type: string + description: The Data Type + example: string + enum: + - string + - integer + - boolean + - number + channelCatalogMarketplacePropertyDiscriminatorType: + type: string + example: string + enum: + - channelCatalogMarketplaceStringProperty + - channelCatalogMarketplaceIntegerProperty + - channelCatalogMarketplaceBooleanProperty + - channelCatalogMarketplaceNumberProperty + channelCatalogMarketplaceProperty: + required: + - discriminatorType + - name + - position + - readOnly + - required + - type + - visible + type: object + properties: + name: + $ref: '#/components/schemas/channelCatalogMarketplacePropertyName' + info: + $ref: '#/components/schemas/BeezUP_Common_InfoSummaries' + description: + type: string + description: Indicate the description of the property + example: If true allows to retireve one marketplace country only + position: + minimum: 1 + type: integer + description: Indicate the position of the property in the display group + example: 1 + readOnly: + type: boolean + description: >- + Indicate if the value cannot be changed. This is used for example + for ebay token that should not be changed. + example: false + default: false + minLength: + minimum: 0 + type: integer + description: Indicates the minimum size of the property value + format: int32 + example: 1 + default: 0 + maxLength: + minimum: 1 + type: integer + description: Indicates the maximum size of the property value + format: int32 + example: 500 + minItems: + minimum: 0 + type: integer + description: Indicates the minimum item count of the property value. + format: int32 + example: 1 + default: 1 + maxItems: + minimum: 1 + type: integer + description: Indicates the maximum item count of the property value + format: int32 + example: 2 + default: 1 + lovLink: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + lovRequired: + type: boolean + description: Indicates if the property value must be in the list of value. + example: true + default: false + required: + type: boolean + description: Indicate if the property is required or not + example: true + default: false + offerIdRequired: + type: integer + description: Indicates the offer identifier required to configure this property. + example: 10 + visible: + type: boolean + description: >- + Indicates if this property should be displayed in the configuration + page. + example: true + default: true + type: + $ref: '#/components/schemas/type' + discriminatorType: + $ref: >- + #/components/schemas/channelCatalogMarketplacePropertyDiscriminatorType + pattern: + type: string + description: >- + Channel catalog marketplace setting value format validation regular + expression + example: >- + (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) + description: Model for fetching a channel catalog marketplace property + discriminator: + propertyName: discriminatorType + channelCatalogMarketplaceStringProperty: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceProperty' + - type: object + properties: + default: + type: array + description: Indicate the default values of the property + example: + - My default value + items: + type: string + channelCatalogMarketplaceIntegerProperty: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceProperty' + - type: object + properties: + default: + type: array + description: Indicate the default values of the property + example: + - '201' + items: + type: integer + channelCatalogMarketplaceBooleanProperty: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceProperty' + - type: object + properties: + default: + type: boolean + description: Indicate the default values of the property + example: false + channelCatalogMarketplaceNumberProperty: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceProperty' + - type: object + properties: + default: + type: array + description: Indicate the default values of the property + example: + - '201.69' + items: + type: number + setChannelCatalogMarketplaceSettingsRequest: + required: + - settings + type: object + properties: + settings: + $ref: '#/components/schemas/channelCatalogMarketplaceSettingArray' + description: The channel catalog marketplace settings to save + publishCatalogToMarketplaceRequest: + required: + - feedType + - publicationStrategyKind + - withUnpublish + type: object + properties: + publicationStrategyKind: + $ref: '#/components/schemas/publicationStrategyKind' + feedType: + $ref: '#/components/schemas/feedType' + withUnpublish: + type: boolean + description: >- + In full publication strategy kind, for some marktetplace, you can + ask to unpublish or not your existing feeds on the markeptlace + absent from your exported catalog. + description: Publish the catalog to the marketplace + publicationStrategyKind: + type: string + description: > + Define the publication strategy kind, for that you have 2 choices + + * Delta - This is the recommanded publication strategy kind, this + strategy will push to the marketplace only the difference between your + catalog and the previous published feeds done by BeezUP. + + * Full - If you want to force the publication of all your catalog feeds + to the marketplace. + !WARNING! Depending to the marketplace this operation will purge the existing offers on the marketplace that are not in the catalog or unknown from the publication feed referential. + default: Delta + enum: + - Delta + - Full + links.GetChannelCatalogMarketplaceSettingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/channelcatatalogs/6a90fcfd-24c7-422e-a65f-aadb1725bbfe/settings + links.SetChannelCatalogMarketplaceSettingsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/channelcatatalogs/6a90fcfd-24c7-422e-a65f-aadb1725bbfe/settings + method: POST + parameters: + request: + in: body + type: object + schema: setChannelCatalogMarketplaceSettingsRequest + channelCatalogMarketplaceSettingsLinks: + required: + - save + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetChannelCatalogMarketplaceSettingsLink' + save: + $ref: '#/components/schemas/links.SetChannelCatalogMarketplaceSettingsLink' + channelCatalogMarketplaceSettings: + required: + - links + - settings + type: object + properties: + links: + $ref: '#/components/schemas/channelCatalogMarketplaceSettingsLinks' + settings: + type: array + example: + - name: Country + values: + - FR + - name: Currency + values: + - EUR + - name: ListingDuration + values: + - GTC + - name: PaymentMethods + values: + - CCAccepted + - name: PayPalEmailAddress + values: + - pascal@ixeoline.com + - name: PostalCode + values: + - '69630' + - name: RefundOption + values: + - MoneyBackOrExchange + - name: ReturnsAcceptedOption + values: + - ReturnsAccepted + - name: ReturnsWithinOption + values: + - Days_10 + - name: ShippingCostPaidByOption + values: + - Buyer + - name: ShippingService + values: + - FR_ColiposteColissimo + items: + $ref: '#/components/schemas/channelCatalogMarketplaceSetting' + description: The channel catalog marketplace settings + channelCatalogMarketplaceSettingArray: + type: array + example: + - name: Country + values: + - FR + - name: Currency + values: + - EUR + - name: ListingDuration + values: + - GTC + - name: PaymentMethods + values: + - CCAccepted + - name: PayPalEmailAddress + values: + - pascal@ixeoline.com + - name: PostalCode + values: + - '69630' + - name: RefundOption + values: + - MoneyBackOrExchange + - name: ReturnsAcceptedOption + values: + - ReturnsAccepted + - name: ReturnsWithinOption + values: + - Days_10 + - name: ShippingCostPaidByOption + values: + - Buyer + - name: ShippingService + values: + - FR_ColiposteColissimo + items: + $ref: '#/components/schemas/channelCatalogMarketplaceSetting' + channelCatalogMarketplacePropertyName: + type: string + description: Channel catalog marketplace property name + example: PaypalAddress + x-lov: MarketplaceStoreProperty + channelCatalogMarketplaceSettingDiscriminatorType: + type: string + example: string + enum: + - channelCatalogMarketplaceStringSetting + - channelCatalogMarketplaceIntegerSetting + - channelCatalogMarketplaceBooleanSetting + - channelCatalogMarketplaceNumberSetting + channelCatalogMarketplaceSetting: + required: + - discriminatorType + - name + type: object + properties: + name: + $ref: '#/components/schemas/channelCatalogMarketplacePropertyName' + discriminatorType: + $ref: >- + #/components/schemas/channelCatalogMarketplaceSettingDiscriminatorType + description: Model for fetching a channel catalog marketplace setting + discriminator: + propertyName: discriminatorType + channelCatalogMarketplaceStringSetting: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceSetting' + - type: object + properties: + values: + type: array + description: Channel catalog marketplace property values + example: + - myemail@mydomain.com + items: + type: string + channelCatalogMarketplaceIntegerSetting: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceSetting' + - type: object + properties: + values: + type: array + description: Channel catalog marketplace property values + example: + - '201' + items: + type: integer + channelCatalogMarketplaceBooleanSetting: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceSetting' + - type: object + properties: + value: + type: boolean + description: Channel catalog marketplace property values + example: false + channelCatalogMarketplaceNumberSetting: + allOf: + - $ref: '#/components/schemas/channelCatalogMarketplaceSetting' + - type: object + properties: + values: + type: array + description: Channel catalog marketplace property values + example: + - '201.69' + items: + type: number + marketplaceChannelCatalogList: + required: + - links + - marketplaceChannelCatalogs + type: object + properties: + links: + $ref: '#/components/schemas/marketplaceChannelCatalogListLinks' + marketplaceChannelCatalogs: + type: array + description: The list of marketplace channel catalog + items: + $ref: '#/components/schemas/marketplaceChannelCatalog' + description: The marketplace channel catalog list + links.GetMarketplaceChannelCatalogsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/channelcatalogs + marketplaceChannelCatalogListLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetMarketplaceChannelCatalogsLink' + marketplaceChannelCatalog: + required: + - apiSettingsStatus + - beezUPChannelCatalogId + - beezUPChannelId + - beezUPMarketplaceName + - beezUPStoreId + - beezUPStoreName + - enabled + - links + - lovLinks + - marketplaceBusinessCode + - marketplaceIsoCountryCodeAlpha2 + - marketplaceMarketPlaceId + - marketplaceTechnicalCode + type: object + properties: + apiSettingsStatus: + $ref: '#/components/schemas/BeezUP_Common_ApiSettingsStatus' + enabled: + type: boolean + description: The enabled status of the Channel Catalog + example: true + marketplaceTechnicalCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceTechnicalCode' + marketplaceBusinessCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceBusinessCode' + marketplaceMarketPlaceId: + type: string + description: The marketplace identifier in the marketplace + example: '71' + marketplaceIsoCountryCodeAlpha2: + type: string + description: >- + The marketplace country iso code alpha 2 (see + http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Decoding_table for + more details) + example: FR + beezUPMarketplaceName: + type: object + description: The marketplace name + example: ebay FRA + beezUPChannelId: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + beezUPChannelCatalogId: + $ref: '#/components/schemas/BeezUP_Common_ChannelCatalogId' + beezUPStoreId: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + beezUPStoreName: + type: string + description: The store name + example: My Store 1 + marketplaceMerchantIdentifiers: + type: object + additionalProperties: + type: string + description: The marketplace merchant identifier list + example: + Ebay_PayPalEmailAddress: yourEbayId@paypal.com + marketplaceAccountId: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceAccountId' + lovLinks: + $ref: '#/components/schemas/marketplaceChannelCatalogLovLinks' + links: + $ref: '#/components/schemas/marketplaceChannelCatalogLinks' + description: >- + This object indicates you the association between a channel catalog and + a marketplace. The account identifier will be automatically defined + based on your marketplace merchant identfier. + links.GetPublicationsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/channelcatalogs/publications/Amazon/123/history + links.PublishCatalogToMarketplaceLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/channelcatalogs/publications/Cdiscount/123/publish + marketplaceChannelCatalogLovLinks: + type: object + properties: + shippingMethodLOV: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + carrierCodeLOV: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + cancelationReasonCodeLOV: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + refundReasonCodeLOV: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + marketplaceStorePropertyLOV: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + marketplaceStorePropertyGroupLOV: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + description: Indicates the List Of Values related to the marketplace + marketplaceChannelCatalogLinks: + required: + - properties + - settings + type: object + properties: + properties: + $ref: >- + #/components/schemas/links.GetChannelCatalogMarketplacePropertiesLink + settings: + $ref: '#/components/schemas/links.GetChannelCatalogMarketplaceSettingsLink' + publications: + $ref: '#/components/schemas/links.GetPublicationsLink' + publishOptions: + type: array + items: + $ref: '#/components/schemas/marketplaceChannelCatalogPublicationOption' + description: >- + Indicate the actions you can do on a channel catalog. If the settings + are valid, you will be able to access to the publication history. + marketplaceChannelCatalogPublicationOption: + required: + - feedType + - kind + - link + - strategy + - withUnpublish + type: object + properties: + kind: + $ref: '#/components/schemas/publicationStrategyKind' + feedType: + $ref: '#/components/schemas/feedType' + withUnpublish: + type: boolean + strategy: + $ref: '#/components/schemas/publicationStrategy' + link: + $ref: '#/components/schemas/links.PublishCatalogToMarketplaceLink' + BeezUP_Common_MarketplaceTechnicalCode: + type: string + description: The technical code of the marketplace. + example: Amazon + x-lov: OMMarketplaceTechnicalCode + BeezUP_Common_MarketplaceBusinessCode: + type: string + description: >- + In an marketplace technical code like CDiscount you can have several + marketplaces like GO SPORT, etc. We identify them by a business code. + example: GOSPORT + x-lov: MarketplaceBusinessCode + BeezUP_Common_MarketplaceAccountId: + type: integer + description: >- + The marketplace account identifier in BeezUP. This account identifier is + based on your api settings. + format: int32 + example: 1234 + beezUPOrderId: + type: string + description: The BeezUP Order identifier + format: uuid + accountId: + type: integer + description: >- + The marketplace account identifier in BeezUP. This account identifier is + based on your api settings. + format: int32 + example: 1234 + order_MerchantOrderId: + type: string + description: The order merchant identifier + example: MyOrderMerchantId + order_MerchantECommerceSoftwareName: + type: string + description: The e-commerce software name of the merchant + example: Prestashop + order_MerchantECommerceSoftwareVersion: + type: string + description: The e-commece software version of the merchant + example: 123.0.1 + orderExportationsLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetOrderExportationsLink' + links.GetOrderExportationsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/exportations + method: GET + links.ExportOrdersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/exportations + method: POST + properties: + request: + in: body + required: true + type: object + schema: exportOrderListRequest + orderExportations: + required: + - exportations + - links + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + exportations: + type: array + items: + $ref: '#/components/schemas/orderExportationReporting' + links: + $ref: '#/components/schemas/orderExportationsLinks' + description: | + The list of Order report exportations.\ + The paginationResult properties can be null if the list is empty. + orderExportationReporting: + required: + - enqueuedUtcDate + - executionUUID + - ipAddress + - processingStatus + - sourceType + - sourceUserName + type: object + properties: + abortionUtcDate: + type: string + format: date-time + example: 2017-04-01T13:10:12.000Z + beginUtcDate: + type: string + format: date-time + example: 2017-04-01T13:10:12.000Z + blobNameUri: + type: string + example: http://beezuporder2.blob.com/yourReport.csv + endUtcDate: + type: string + format: date-time + example: 2017-04-01T15:10:12.000Z + enqueuedUtcDate: + type: string + format: date-time + example: 2017-04-01T13:09:12.000Z + errorMessage: + type: string + example: You have an error here + executionUUID: + type: string + format: uuid + expirationUtcDate: + type: string + format: date-time + example: 2017-04-01T13:39:12.000Z + failureUtcDate: + type: string + format: date-time + example: 2017-04-01T13:39:12.000Z + ipAddress: + type: string + example: 127.0.0.1 + jsonCriteria: + type: string + description: Raw representation of the JSON + example: >- + {"StartDate:"2016-09-30T22:00:00Z","EndDate:"2016-10-30T23:00:00Z","OrderListingFilterDateSearchType:0,"MarketPlaceOrderIds:null,"BeezUPOrderStatusNames:null,"ResultByPage:20,"MerchantOrderIds:null,"PageIndex:0,"MarketPlaceTechnicalCodes:["PriceMinister","Amazon","CDiscount","Mirakl"],"MarketPlaceBusinessCodes:["PRICEMINISTER"],"AccountIds:[1234,987],"StoreIds:["00000000-0000-0000-0000-00000000007c"],"BuyerFullName:null} + lastUpdateUtcDate: + type: string + format: date-time + example: 2017-04-01T15:10:12.000Z + orderCount: + type: integer + format: int32 + example: 1024 + processingStatus: + $ref: '#/components/schemas/orderExportationReportingProcessingStatus' + remainingOrderCount: + type: integer + format: int32 + example: 0 + resumedUtcDate: + type: string + format: date-time + example: 2017-04-01T13:39:12.000Z + sourceType: + $ref: '#/components/schemas/sourceType' + sourceUserId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + sourceUserName: + type: string + example: Marilyn monroe + suspendedUtcDate: + type: string + format: date-time + example: 2017-04-01T13:39:12.000Z + timeoutDuration: + type: string + example: '00:30:00' + warningMessage: + type: string + example: You have a warning here + description: Represent the reporting of the Order report exportations + dateSearchType: + type: string + description: Indicates on which date you want to make the filter + default: Modification + enum: + - Modification + - Purchase + - MarketPlaceModification + invoiceAvailabilityType: + type: string + description: Indicates on which invoice availability to filter + example: All + x-lov: InvoiceAvailabilityType + orderMerchantInfoSynchronizationStatus: + type: string + description: Indicates on which order merchant info synchronization status to filter + example: All + x-lov: OrderMerchantInfoSynchronizationStatus + pageSize: + maximum: 100 + minimum: 25 + type: integer + description: Indicate the order count per page + format: int32 + example: 100 + default: 100 + pageNumber: + minimum: 1 + type: integer + description: Indicates the page number + format: int32 + example: 1 + default: 1 + order_Buyer_Name: + type: string + description: Buyer full name + example: Monroe + orderListRequestWithoutPagination: + required: + - beginPeriodUtcDate + - endPeriodUtcDate + type: object + properties: + marketplaceTechnicalCodes: + type: array + example: + - PriceMinister + items: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceTechnicalCode' + marketplaceBusinessCodes: + type: array + example: + - PRICEMINISTER + items: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceBusinessCode' + accountIds: + type: array + description: Account Id list + example: + - '12345' + items: + $ref: '#/components/schemas/accountId' + storeIds: + type: array + description: Store Id list + items: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + beezUPOrderStatuses: + type: array + example: + - InProgress + items: + $ref: '#/components/schemas/beezUPOrderStatus' + dateSearchType: + $ref: '#/components/schemas/dateSearchType' + beginPeriodUtcDate: + type: string + description: | + The begin period you want to make the search. \ + The period MUST not be greater than 30 days. + The begin period MUST be lower than the end period. + format: date-time + example: 2017-03-01T13:10:01.000Z + endPeriodUtcDate: + type: string + description: | + The end period of you search. \ + The period MUST not be greater than 30 days. \ + The end period MUST be greater than the begin period. + The end period MUST be lower to the current date. + format: date-time + example: 2017-04-01T13:10:01.000Z + invoiceAvailabilityType: + $ref: '#/components/schemas/invoiceAvailabilityType' + order_Buyer_Name: + $ref: '#/components/schemas/order_Buyer_Name' + marketplaceOrderIds: + type: array + example: + - AmazonOrderId1234 + items: + $ref: '#/components/schemas/marketplaceOrderId' + orderMerchantInfoSynchronizationStatus: + $ref: '#/components/schemas/orderMerchantInfoSynchronizationStatus' + order_MerchantOrderIds: + type: array + description: Merchant order id list + example: + - MyOrderId1234 + items: + $ref: '#/components/schemas/order_MerchantOrderId' + orderListRequest: + allOf: + - $ref: '#/components/schemas/orderListRequestWithoutPagination' + - required: + - pageNumber + - pageSize + type: object + properties: + pageSize: + $ref: '#/components/schemas/pageSize' + pageNumber: + $ref: '#/components/schemas/pageNumber' + exportOrderListFormat: + type: string + description: The type of the file to export + example: csv + default: csv + enum: + - csv + exportOrderListRequest: + required: + - orderListRequestWithoutPagination + - storeId + type: object + properties: + format: + $ref: '#/components/schemas/exportOrderListFormat' + storeId: + $ref: '#/components/schemas/BeezUP_Common_StoreId' + orderListRequestWithoutPagination: + $ref: '#/components/schemas/orderListRequestWithoutPagination' + description: >- + The message request to export order list. The store identifier is + requested to regroup the exportations. + orderExportationReportingProcessingStatus: + type: string + example: Done + enum: + - None + - InProgress + - Done + - Failed + - AlreadyInProgress + - Aborted + - Suspended + automaticTransitionInfoListLinks: + required: + - configure + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetAutomaticTransitionsLink' + configure: + $ref: '#/components/schemas/links.ConfigureAutomaticTransitionsLink' + automaticTransitionInfoList: + required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/automaticTransitionInfoListLinks' + automaticTransitionInfos: + type: array + items: + $ref: '#/components/schemas/automaticTransitionInfo' + businessOperationType: + type: string + example: ShipOrder + x-lov: OrderChangeBusinessOperationType + automaticTransitionInfoLinks: + required: + - configure + type: object + properties: + configure: + $ref: '#/components/schemas/links.ConfigureAutomaticTransitionsLink' + automaticTransitionInfo: + allOf: + - $ref: '#/components/schemas/automaticTransition' + - required: + - beezUPOrderStatus + - businessOperationType + - marketplaceBusinessCode + type: object + properties: + marketplaceBusinessCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceBusinessCode' + beezUPOrderStatus: + $ref: '#/components/schemas/beezUPOrderStatus' + businessOperationType: + $ref: '#/components/schemas/businessOperationType' + links: + $ref: '#/components/schemas/automaticTransitionInfoLinks' + configureAutomaticTransitionRequest: + required: + - automaticTransitions + type: object + properties: + automaticTransitions: + type: array + items: + $ref: '#/components/schemas/automaticTransition' + automaticTransition: + required: + - accountId + - enabled + - marketplaceTechnicalCode + - orderStatusTransitionId + type: object + properties: + marketplaceTechnicalCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceTechnicalCode' + accountId: + $ref: '#/components/schemas/accountId' + orderStatusTransitionId: + type: integer + format: int32 + example: 1234 + enabled: + type: boolean + example: false + orderIdentifier: + required: + - accountId + - beezUPOrderId + - marketplaceTechnicalCode + type: object + properties: + marketplaceTechnicalCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceTechnicalCode' + accountId: + $ref: '#/components/schemas/accountId' + beezUPOrderId: + $ref: '#/components/schemas/beezUPOrderId' + clearMerchantOrderInfoListRequest: + required: + - orders + type: object + properties: + orders: + maxItems: 100 + minItems: 1 + uniqueItems: true + type: array + example: + - marketplaceTechnicalCode: Amazon + accountId: '1234' + beezUPOrderId: '0' + - marketplaceTechnicalCode: Amazon + accountId: '5678' + beezUPOrderId: '0' + - marketplaceTechnicalCode: Ebay + accountId: '9876' + beezUPOrderId: '0' + items: + $ref: '#/components/schemas/orderIdentifier' + setMerchantOrderInfoListRequest: + required: + - order_MerchantECommerceSoftwareName + - order_MerchantECommerceSoftwareVersion + - orders + type: object + properties: + order_MerchantECommerceSoftwareName: + $ref: '#/components/schemas/order_MerchantECommerceSoftwareName' + order_MerchantECommerceSoftwareVersion: + $ref: '#/components/schemas/order_MerchantECommerceSoftwareVersion' + orders: + maxItems: 100 + minItems: 1 + uniqueItems: true + type: array + example: + - marketplaceTechnicalCode: Amazon + accountId: '1234' + beezUPOrderId: 8D47FF1427A26B064ca98e95f644361ada5a5be0bbb3b53 + order_MerchantOrderId: BX1234 + - marketplaceTechnicalCode: Amazon + accountId: '5678' + beezUPOrderId: 8D47FF149F213D055f26e3c413e4c9ba5c5cfda460547a4 + order_MerchantOrderId: BX5678 + - marketplaceTechnicalCode: Ebay + accountId: '9876' + beezUPOrderId: 8D47FF150217B60bdec05ab61c445d1a59e3da050b52823 + order_MerchantOrderId: BX9876 + items: + $ref: '#/components/schemas/setMerchantOrderInfoListRequestItem' + setMerchantOrderInfoListRequestItem: + allOf: + - $ref: '#/components/schemas/orderIdentifier' + - required: + - order_MerchantOrderId + type: object + properties: + order_MerchantOrderId: + $ref: '#/components/schemas/order_MerchantOrderId' + setMerchantOrderInfoRequest: + required: + - order_MerchantECommerceSoftwareName + - order_MerchantECommerceSoftwareVersion + - order_MerchantOrderId + type: object + properties: + order_MerchantOrderId: + $ref: '#/components/schemas/order_MerchantOrderId' + order_MerchantECommerceSoftwareName: + $ref: '#/components/schemas/order_MerchantECommerceSoftwareName' + order_MerchantECommerceSoftwareVersion: + $ref: '#/components/schemas/order_MerchantECommerceSoftwareVersion' + accountSynchronizationList: + type: object + properties: + accountSynchronizations: + type: array + items: + $ref: '#/components/schemas/accountSynchronization' + accountSynchronization: + required: + - accountId + - marketplaceBusinessCode + - marketplaceTechnicalCode + type: object + properties: + accountId: + $ref: '#/components/schemas/accountId' + completedHarvestSynchroUtcDate: + type: string + format: date-time + marketplaceBusinessCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceBusinessCode' + marketplaceTechnicalCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceTechnicalCode' + processing: + type: boolean + description: >- + If true, there is currently a harvest or an order change in progress. + Otherwise false. + example: false + links.GetOrderLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000 + method: GET + orderHeaderLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetOrderLink' + orderHeader: + required: + - accountId + - beezUPOrderId + - etag + - links + - marketplaceBusinessCode + - marketplaceTechnicalCode + - order_LastModificationUtcDate + - order_MarketplaceLastModificationUtcDate + - order_MarketplaceOrderId + - order_PurchaseUtcDate + - order_Status_BeezUPOrderStatus + - processing + type: object + properties: + marketplaceTechnicalCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceTechnicalCode' + accountId: + $ref: '#/components/schemas/accountId' + beezUPOrderId: + $ref: '#/components/schemas/beezUPOrderId' + beezUPOrderUrl: + $ref: '#/components/schemas/BeezUP_Common_HttpUrl' + marketplaceBusinessCode: + $ref: '#/components/schemas/BeezUP_Common_MarketplaceBusinessCode' + order_MarketplaceOrderId: + $ref: '#/components/schemas/marketplaceOrderId' + order_Status_BeezUPOrderStatus: + $ref: '#/components/schemas/beezUPOrderStatus' + order_Status_MarketplaceOrderStatus: + $ref: '#/components/schemas/marketplaceOrderStatus' + order_MerchantOrderId: + $ref: '#/components/schemas/order_MerchantOrderId' + order_MerchantECommerceSoftwareName: + $ref: '#/components/schemas/order_MerchantECommerceSoftwareName' + order_MerchantECommerceSoftwareVersion: + $ref: '#/components/schemas/order_MerchantECommerceSoftwareVersion' + order_PurchaseUtcDate: + type: string + description: The purchase date of this order + format: date-time + example: 2017-03-31T21:30:23.000Z + order_LastModificationUtcDate: + type: string + description: The last modification UTC date done by BeezUP of this order + format: date-time + example: 2017-04-16T10:30:23.000Z + order_MarketplaceLastModificationUtcDate: + type: string + description: The last modification UTC date done by the marketplace on this order + format: date-time + example: 2017-04-16T10:25:23.000Z + order_Buyer_Name: + $ref: '#/components/schemas/order_Buyer_Name' + order_TotalPrice: + type: number + description: >- + The total price of this order (corresponding to the amount paid by + the customer) + format: decimal + example: 101.42 + order_CurrencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + order_Invoice_Number: + type: string + description: The order invoice number + order_Invoice_Uri: + type: string + description: The order invoice URI + processing: + $ref: '#/components/schemas/processing' + etag: + $ref: '#/components/schemas/etag' + links: + $ref: '#/components/schemas/orderHeaderLinks' + description: >- + Describe the basic information related to an order. All properties with + the prefix order_ are translated in the list of values + /user/lov/OrderMetaInfoOrderDetails + etag: + type: string + description: > + ETag value to identify the order.\ + + This information is required for the operation GetOrder and + ChangeOrder.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + example: '"ca071a4580129f932a03971968ffef69"' + orderItem: + required: + - beezUPOrderItemId + - orderItem_OrderItemType + type: object + properties: + beezUPOrderItemId: + type: string + description: The BeezUP identifier of the order Item + example: '1' + orderItem_OrderItemType: + type: string + description: The order item type of the order item + example: Product + orderItem_MerchantImportedProductId: + type: string + description: >- + The product id indicated in the catalog importation in BeezUP system + for this order item. This property will help you to match the order + to the inventory system. + example: '73267' + orderItem_MerchantImportedProductIdColumnName: + type: string + description: >- + The column name for the product id indicated in the catalog + importation in BeezUP system related to this order item. This + property will help you to match the order to the inventory system. + example: reference + orderItem_MerchantImportedProductUrl: + type: string + description: >- + The product url indicated in the catalog importation in BeezUP + system related to this order item + example: http://blabla.com/my-folder/73267.html + orderItem_MerchantProductIdColumnName: + type: string + description: >- + The column name indicate in the mapping for the product id related + to the order item + example: reference_produit + orderItem_BeezUPStoreId: + type: string + description: >- + The store id in the beezup system related to the order item. This + property will help you to match the order to the inventory system. + example: 00000000-cceb-4c20-b2c9-000000000000 + orderItem_ItemTax: + type: number + description: The tax of the order item + format: decimal + example: 0 + orderItem_Title: + type: string + description: The title of the order item + example: bLA acide-plomb 6v-4.5ah 70x48x106mm + orderItem_ImageUrl: + type: string + description: The URL of the image of the order item + example: http://blabla.com//das6-45.jpg + orderItem_MerchantProductId: + type: string + description: The merchant product id of the order item + example: BlaLdas6-4.5 + orderItem_MarketPlaceProductId: + type: string + description: The marketplace product identifier of the order item + example: '' + orderItem_gtin: + type: string + description: The order item gtin + example: gtin_sample + orderItem_ItemPrice: + type: number + description: The price of the order item + format: decimal + example: 6.86 + orderItem_Quantity: + type: number + description: The quantity of the order item + format: decimal + example: 1 + orderItem_TotalPrice: + type: number + description: The total price of the order item + format: decimal + example: 6.86 + orderItem_Shipping_Price: + type: number + description: The shipping price of the order item + format: decimal + example: 0 + orderItem_Condition: + type: string + description: The merchant product condition of the order item + example: New + orderItem_MarketplaceProductUri: + type: string + description: The merchant product uri of the order item + example: http://beezupblob.com/productLink.xml + orderItem_MarketplaceImageUri: + type: string + description: The marketplace image uri + example: http://beezupblob.com/marketplaceImg.jpg + description: >- + Describe an order item. All properties with the prefix orderItem_ are + translated in the list of values /user/lov/OrderMetaInfoOrderItems + orderLinks: + allOf: + - $ref: '#/components/schemas/orderHeaderLinks' + - required: + - clearMerchantInfo + - harvest + - history + - setMerchantInfo + type: object + properties: + history: + $ref: '#/components/schemas/links.GetOrderHistoryLink' + harvest: + $ref: '#/components/schemas/links.HarvestOrderLink' + setMerchantInfo: + $ref: '#/components/schemas/links.SetMerchantOrderInfoLink' + clearMerchantInfo: + $ref: '#/components/schemas/links.ClearMerchantOrderInfoLink' + links.GetOrderHistoryLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/history + method: GET + links.SetMerchantOrderInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/setMerchantOrderInfo + method: POST + parameters: + request: + in: body + type: object + schema: setMerchantOrderInfoRequest + links.ClearMerchantOrderInfoLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/clearMerchantOrderInfo + method: POST + links.HarvestOrderLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/harvest + method: POST + order: + allOf: + - $ref: '#/components/schemas/orderHeader' + - required: + - links + - orderItems + - transitionLinks + type: object + properties: + links: + $ref: '#/components/schemas/orderLinks' + order_MarketPlaceChannel: + type: string + description: >- + Useful to identify the origin of the order. For example in + Amazon. + example: Amazon France + order_TotalTax: + type: number + description: The total tax of this order + format: decimal + example: 0 + order_TotalCommission: + type: number + description: The total commission of this order + format: decimal + example: 0 + order_PaymentMethod: + type: string + description: The payment method of this order + example: 1 / 1X + order_PayingUtcDate: + type: string + description: The UTC date of the payment of this order + format: date-time + example: 2017-04-01T13:22:01.000Z + order_Comment: + type: string + description: The comment associated to this order + example: This is a comment + order_Shipping_FirstName: + type: string + description: Order Shipping first name + example: Monroe + order_Shipping_LastName: + type: string + description: Order Shipping last name + example: Monroe + order_Shipping_Civility: + type: string + description: >- + The civility of the person in the shipping address for this + order + example: MRS + order_Shipping_CompanyName: + type: string + description: The company name of the shipping address for this order + example: My Company + order_Shipping_AddressName: + type: string + description: The name of the person in the shipping address for this order + example: Jacques BAUREGARD + order_Shipping_Email: + type: string + description: The email of the person in the shipping address for this order + example: client_000000@manomano.fr + order_Shipping_AddressLine1: + type: string + description: The shipping address line 1 of this order + example: 5 rue amélie + order_Shipping_AddressLine2: + type: string + description: The shipping address line 2 of this order + example: BDR + order_Shipping_AddressLine3: + type: string + description: The shipping address line 3 of this order + example: RDC + order_Shipping_AddressPostalCode: + type: string + description: The shipping address postal code of this order + example: '13014' + order_Shipping_AddressCity: + type: string + description: The shipping address city of this order + example: Marseille + order_Shipping_AddressStateOrRegion: + type: string + description: The shipping address state or region of this order + example: BDR + order_Shipping_AddressCountryName: + type: string + description: The shipping address country name + example: France + order_Shipping_AddressCountryIsoCodeAlpha2: + type: string + description: >- + The shipping address country iso code alpha 2 (see + http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#/decoding_table + for more details) + example: FR + order_Shipping_Phone: + type: string + description: >- + The phone number of the person in the shipping address for this + order + example: 33000000041 + order_Shipping_MobilePhone: + type: string + description: >- + The mobile phone number of the person in the shipping address + for this order + example: 33000000042 + order_Shipping_Price: + type: number + description: The shipping price of this order + format: decimal + example: 6.9 + order_Shipping_Method: + type: string + description: The shipping method of this order + example: DPD Domicile + order_Shipping_ShippingTax: + type: number + description: The shipping tax for this order + format: decimal + example: 0 + order_Shipping_EarliestShipUtcDate: + type: string + description: The UTC date of the earliest ship for this order + format: date-time + example: 2017-04-02T21:30:00.000Z + order_Shipping_LatestShipUtcDate: + type: string + description: The UTC date of the latest ship for this order + format: date-time + example: 2017-04-30T21:30:00.000Z + order_Buyer_Identifier: + type: string + description: The buyer identifier for this order + example: '1234567890' + order_Buyer_FirstName: + type: string + description: Order Buyer first name + example: Monroe + order_Buyer_LastName: + type: string + description: Order Buyer last name + example: Monroe + order_Buyer_Civility: + type: string + description: The buyer civility for this order + example: Marseille + order_Buyer_CompanyName: + type: string + description: The buyer company name for this order + example: Marsillia + order_Buyer_Email: + type: string + description: The email of the buyer for this order + example: client_000000@manomano.fr + order_Buyer_AddressLine1: + type: string + description: The Buyer address line 1 of this order + example: 5 rue amélie + order_Buyer_AddressLine2: + type: string + description: The Buyer address line 2 of this order + example: BDR + order_Buyer_AddressLine3: + type: string + description: The Buyer address line 3 of this order + example: RDC + order_Buyer_AddressPostalCode: + type: string + description: The Buyer address postal code of this order + example: '13014' + order_Buyer_AddressCity: + type: string + description: The Buyer address city of this order + example: Marseille + order_Buyer_AddressStateOrRegion: + type: string + description: The Buyer address state or region of this order + example: BDR + order_Buyer_AddressCountryName: + type: string + description: The Buyer address country name + example: France + order_Buyer_AddressCountryIsoCodeAlpha2: + type: string + description: >- + The Buyer address country iso code alpha 2 (see + http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#/decoding_table + for more details) + example: FR + order_Buyer_Phone: + type: string + description: The phone number of the buyer for this order + example: 33000000101 + order_Buyer_MobilePhone: + type: string + description: The mobile phone number of the buyer for this order + example: 33000000042 + order_IsPrime: + type: boolean + description: Indicates if the order is considered as Prime (only on Amazon) + example: true + order_FulfilledBy: + type: string + description: The order FulfilledBy + order_IsBusiness: + type: boolean + description: The order IsBusiness + order_OrderSourceUri: + type: string + description: > + Technical information: The url to the source of this order. We + received this information from the marketplace. + format: uri + example: http://beezupblob.com/order.xml + order_OrderItemsSourceUri: + type: string + description: > + Technical information: The url to the source of this order + items. We received this information from the marketplace. + format: uri + example: http://beezupblob.com/orderItems.xml + orderItems: + type: array + items: + $ref: '#/components/schemas/orderItem' + transitionLinks: + $ref: '#/components/schemas/orderTransitionLinks' + description: >- + Describe in details all informations related to an order. All + properties with the prefix order_ are translated in the list of + values /user/lov/OrderMetaInfoOrderDetails. + links.ChangeOrderLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + properties: + rel: + type: string + description: Indicate the relation name related to the link + example: self + - type: object + example: + rel: ShipOrder + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/ShipOrder + method: POST + templated: 'true' + parameters: + If-Match: + in: header + value: '"ca071a4580129f932a03971968ffef69"' + required: true + type: string + testMode: + in: query + type: boolean + required: false + value: 'false' + userName: + in: query + type: string + required: true + request: + in: body + type: object + schema: changeOrderRequest + properties: + order_Shipping_FulfillmentDate: + required: true + type: date-time + order_Shipping_ShipperTrackingNumber: + required: true + type: string + order_Shipping_CarrierName: + required: true + type: string + lovRequired: 'true' + lovLink: + href: /v2/user/PriceMinisterCarrierName + order_Shipping_Method: + required: true + type: string + lovRequired: 'false' + lovLink: + href: /v2/user/ShippingMethod_PriceMinister + orderTransitionLinks: + type: array + description: Contains the authorized change actions for an order + example: + - rel: ShipOrder + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/ShipOrder + method: POST + templated: 'true' + parameters: + If-Match: + in: header + value: '"ca071a4580129f932a03971968ffef69"' + required: true + type: string + testMode: + in: query + type: boolean + required: false + value: 'false' + userName: + in: query + type: string + required: true + request: + in: body + type: object + schema: changeOrderRequest + properties: + order_Shipping_FulfillmentDate: + required: true + type: date-time + order_Shipping_ShipperTrackingNumber: + required: true + type: string + order_Shipping_CarrierName: + required: true + type: string + lovRequired: 'true' + lovLink: + href: /v2/user/PriceMinisterCarrierName + order_Shipping_Method: + required: true + type: string + lovRequired: 'false' + lovLink: + href: /v2/user/ShippingMethod_PriceMinister + - rel: CancelOrder + href: >- + /v2/user/marketplaces/orders/Amazon/1001/00000000000000000000000000000000000000000000000/CancelOrder + method: POST + templated: 'true' + parameters: + If-Match: + in: header + value: '"ca071a4580129f932a03971968ffef69"' + required: true + type: string + testMode: + in: query + type: boolean + required: false + value: 'false' + userName: + in: query + type: string + required: true + request: + in: body + type: object + schema: changeOrderRequest + properties: + order_Cancel_Reason: + required: true + type: string + items: + $ref: '#/components/schemas/links.ChangeOrderLink' + orderIndex: + required: + - links + - lovLinks + type: object + properties: + links: + $ref: '#/components/schemas/orderIndexLinks' + lovLinks: + $ref: '#/components/schemas/orderIndexLovLinks' + links.GetOrderIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders + method: GET + orderIndexLinks: + required: + - autoTransitions + - clearMerchantInfos + - export + - harvest + - lightOrders + - orders + - self + - setMerchantInfos + - status + type: object + properties: + self: + $ref: '#/components/schemas/links.GetOrderIndexLink' + status: + $ref: '#/components/schemas/links.GetMarketplaceAccountsSynchronizationLink' + harvest: + $ref: '#/components/schemas/links.HarvestAllLink' + setMerchantInfos: + $ref: '#/components/schemas/links.SetMerchantOrderInfoListLink' + clearMerchantInfos: + $ref: '#/components/schemas/links.ClearMerchantOrderInfoListLink' + export: + $ref: '#/components/schemas/links.ExportOrdersLink' + autoTransitions: + $ref: '#/components/schemas/links.GetAutomaticTransitionsLink' + exportations: + $ref: '#/components/schemas/links.GetOrderExportationsLink' + orders: + $ref: '#/components/schemas/links.GetOrderListFullLink' + lightOrders: + $ref: '#/components/schemas/links.GetOrderListLightLink' + description: Gives you all entry point operations you can do on this API + orderIndexLovLinks: + required: + - orderChangeBusinessOperationType + - orderProperty + - orderPropertyPosted + - orderState + type: object + properties: + orderChangeBusinessOperationType: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + orderState: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + orderProperty: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + orderPropertyPosted: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + description: >- + Gives you all the LOV to get the translations realated to operation + name, codes, property names and statuses. + links.GetOrderListFullLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/list/full + method: POST + properties: + Accept-Encoding: + in: header + required: true + type: ​array + schema: string + request: + in: body + required: false + type: object + schema: orderListRequest + links.GetOrderListLightLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/list/light + method: POST + properties: + request: + in: body + required: false + type: object + schema: orderListRequest + links.GetAutomaticTransitionsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/autoTransitions + method: GET + links.ConfigureAutomaticTransitionsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/autoTransitions + method: POST + parameters: + request: + in: body + request: 'true' + schema: configureAutomaticTransitionRequest + orderListLinks: + required: + - clearMerchantInfos + - export + - harvest + - setMerchantInfos + - status + type: object + properties: + harvest: + $ref: '#/components/schemas/links.HarvestAllLink' + setMerchantInfos: + $ref: '#/components/schemas/links.SetMerchantOrderInfoListLink' + clearMerchantInfos: + $ref: '#/components/schemas/links.ClearMerchantOrderInfoListLink' + export: + $ref: '#/components/schemas/links.ExportOrdersLink' + status: + $ref: '#/components/schemas/links.GetMarketplaceAccountsSynchronizationLink' + description: The list of actions you can do from the order list response + links.GetMarketplaceAccountsSynchronizationLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/status + method: GET + orderListLightLinks: + allOf: + - $ref: '#/components/schemas/orderListLinks' + - required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetOrderListLightLink' + orderListFullLinks: + allOf: + - $ref: '#/components/schemas/orderListLinks' + - required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetOrderListFullLink' + links.SetMerchantOrderInfoListLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/setMerchantOrderInfos + method: POST + parameters: + request: + in: body + required: true + type: object + schema: setMerchantOrderInfoRequest + links.ClearMerchantOrderInfoListLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/clearMerchantOrderInfos + method: POST + links.HarvestAllLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/marketplaces/orders/harvest + method: POST + orderListLight: + required: + - links + - orders + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + orders: + type: array + items: + $ref: '#/components/schemas/orderHeader' + links: + $ref: '#/components/schemas/orderListLightLinks' + description: | + The order list with minimum information we have from the orders.\ + The paginationResult properties can be null if the list is empty. + orderListFull: + required: + - links + - orders + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + orders: + type: array + items: + $ref: '#/components/schemas/order' + links: + $ref: '#/components/schemas/orderListFullLinks' + description: > + The order list with all information we have from the orders and its + items.\ + + The paginationResult properties can be null if the list is empty. + beezUPOrderStatus: + type: string + description: BeezUP order status. Unified for all marketplaces. + example: Shipped + x-lov: BeezUPOrderState + marketplaceOrderStatus: + type: string + description: The marketplace order state + example: In_progress_3 + marketplaceOrderId: + type: string + description: The order marketplace identifier + example: AMAZON12345 + orderHistory: + type: object + properties: + changeOrderReportings: + type: array + description: The list of change order operation + items: + $ref: '#/components/schemas/changeOrderReporting' + harvestOrderReportings: + type: array + items: + $ref: '#/components/schemas/harvestOrderReporting' + lastModificationUtcDate: + type: string + format: date-time + description: Describe the history related to an order + sourceType: + type: string + description: Indicates the origin of the operation + example: Api + enum: + - Api + - Go + executionUUID: + type: string + description: The execution identifier + format: uuid + changeOrderReporting: + type: object + properties: + executionUUID: + $ref: '#/components/schemas/executionUUID' + changeOrderType: + $ref: '#/components/schemas/businessOperationType' + sourceType: + $ref: '#/components/schemas/sourceType' + sourceUserId: + $ref: '#/components/schemas/BeezUP_Common_UserId' + sourceUserName: + type: string + example: Guillaume Tell + creationUtcDate: + type: string + description: The creation UTC date of the execution + format: date-time + example: 2017-04-01T13:10:03.000Z + processingStatus: + type: string + description: The processing status of the execution + example: Done + lastUpdateUtcDate: + type: string + description: The last update UTC date of the execution + format: date-time + example: 2017-04-01T13:10:05.000Z + errorMessage: + type: string + description: The error message during the execution + example: This is an error message + ipAddress: + type: string + description: The IP address who request this operation + example: 127.0.0.1 + testMode: + type: boolean + description: This operation was a test + example: false + details: + type: object + additionalProperties: + type: object + properties: {} + description: The reporting related to a change order operation + harvestOrderReporting: + type: object + properties: + executionUUID: + $ref: '#/components/schemas/executionUUID' + creationUtcDate: + type: string + description: The creation UTC date of the execution + format: date-time + example: 2017-04-01T13:10:03.000Z + processingStatus: + type: string + description: The processing status of the execution + example: Done + lastUpdateUtcDate: + type: string + description: The last update UTC date of the execution + format: date-time + example: 2017-04-01T13:10:05.000Z + errorMessage: + type: string + description: The warning message during the execution + example: This is an error message + warningMessage: + type: string + description: The warning message during the execution + example: This is a warning + beezUPStatus: + $ref: '#/components/schemas/beezUPOrderStatus' + marketplaceStatus: + type: string + description: The order marketplace status + example: In_progress_3 + beezUPForcedStatus: + type: string + description: >- + The marketplace order status forced by BeezUP during the order + change oepration. This could happend when there is no status on the + marketplace side. + example: In_progress_3 + description: The reporting related to a harvest order operation + changeOrderListRequest: + required: + - changeOrders + type: object + properties: + changeOrders: + type: array + description: The change order operations + items: + $ref: '#/components/schemas/changeOrderListRequestItem' + description: >- + Contains all change order operations you want to make. (max 100 items + per call) + changeOrderListRequestItem: + required: + - order + type: object + properties: + order: + $ref: '#/components/schemas/orderIdentifierWithETag' + changeOrderRequest: + $ref: '#/components/schemas/changeOrderRequest' + description: Contains the order identifier and the change order request + orderIdentifierWithETag: + allOf: + - $ref: '#/components/schemas/orderIdentifier' + - required: + - etag + type: object + properties: + etag: + $ref: '#/components/schemas/etag' + changeOrderRequest: + type: object + additionalProperties: + type: string + description: >- + All properties with the prefix order_ are translated in the list of + values /user/lov#OrderMetaInfoPosted + example: + order_Shipping_ShipperTrackingNumber: 1H01845163783 + order_Shipping_ShippingUrl: https://trackingpackage.com?number=1H01845163783 + order_Shipping_CarrierName: La poste + order_Shipping_FulfillmentDate: 2014-09-23T09:58:00.000Z + order_Shipping_EstimatedDeliveryDate: 2014-09-24T09:58:00.000Z + batchOrderOperationResponse: + required: + - operations + type: object + properties: + operations: + type: array + items: + $ref: '#/components/schemas/orderOperationResponse' + description: The response given by the batch operation + orderOperationResponse: + required: + - order + - status + - success + type: object + properties: + order: + $ref: '#/components/schemas/orderIdentifier' + success: + type: boolean + description: Indicates if the operation succeed or not + example: true + status: + type: integer + description: Indicates the http status corresponding to the individual operation + example: 204 + errors: + type: array + description: The error list + items: + $ref: '#/components/schemas/BeezUP_Common_UserErrorMessage' + description: The response given by the batch operation for an order + oMReadyMarketplaceBusinessCodeResponse: + type: array + items: + $ref: '#/components/schemas/listOfValueItem' + orderListFullWithLinks: + required: + - links + - orders + - paginationResult + type: object + properties: + orders: + type: array + items: + $ref: '#/components/schemas/orderWithLinks' + links: + $ref: '#/components/schemas/orderListFullLinks' + paginationResult: + $ref: '#/components/schemas/paginationResult' + orderListLightWithLinks: + required: + - links + - orders + - paginationResult + type: object + properties: + orders: + type: array + items: + $ref: '#/components/schemas/orderHeaderWithLinks' + links: + $ref: '#/components/schemas/orderListLightLinks' + paginationResult: + $ref: '#/components/schemas/paginationResult' + orderWithLinks: + allOf: + - $ref: '#/components/schemas/order' + - required: + - links + - transitionLinks + type: object + properties: + links: + $ref: '#/components/schemas/orderLinks' + transitionLinks: + $ref: '#/components/schemas/orderTransitionLinks' + orderHeaderWithLinks: + allOf: + - $ref: '#/components/schemas/orderHeader' + - required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/orderHeaderLinks' + links.GetOrderV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: >- + /orders/v3/Amazon/1001/00000000000000000000000000000000000000000000000 + method: GET + links.GetOrderHistoryV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: >- + /orders/v3/Amazon/1001/00000000000000000000000000000000000000000000000/history + method: GET + links.HarvestOrderV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: >- + /orders/v3/Amazon/1001#/00000000000000000000000000000000000000000000000/harvest + method: POST + links.SetMerchantOrderInfoV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: >- + /orders/v3/Amazon/1001/00000000000000000000000000000000000000000000000/setMerchantOrderInfo + method: POST + parameters: + request: + in: body + type: object + schema: setMerchantOrderInfoRequest + links.ClearMerchantOrderInfoV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: >- + /orders/v3/Amazon/1001/00000000000000000000000000000000000000000000000/clearMerchantOrderInfo + method: POST + links.GetOrderListLightV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: /orders/v3/list/light + method: POST + properties: + request: + in: body + required: false + type: object + schema: orderListRequest + links.HarvestAllV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: /orders/v3/harvest + method: POST + links.SetMerchantOrderInfoListV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: /orders/v3/setMerchantOrderInfos + method: POST + parameters: + request: + in: body + required: true + type: object + schema: setMerchantOrderInfoRequest + links.ClearMerchantOrderInfoListV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: /orders/v3/clearMerchantOrderInfos + method: POST + links.GetMarketplaceAccountsSynchronizationV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: /orders/v3/status + method: GET + links.ChangeOrderV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + properties: + rel: + type: string + description: Indicate the relation name related to the link + example: self + - type: object + example: + rel: ShipOrder + href: >- + /orders/v3/Amazon/1001/00000000000000000000000000000000000000000000000/ShipOrder + method: POST + templated: 'true' + parameters: + If-Match: + in: header + value: '"ca071a4580129f932a03971968ffef69"' + required: true + type: string + testMode: + in: query + type: boolean + required: false + value: 'false' + userName: + in: query + type: string + required: true + request: + in: body + type: object + schema: changeOrderRequest + properties: + order_Shipping_FulfillmentDate: + required: true + type: date-time + order_Shipping_ShipperTrackingNumber: + required: true + type: string + order_Shipping_CarrierName: + required: true + type: string + lovRequired: 'true' + lovLink: + href: /v2/user/PriceMinisterCarrierName + order_Shipping_Method: + required: true + type: string + lovRequired: 'false' + lovLink: + href: /v2/user/ShippingMethod_PriceMinister + links.GetOrderListFullV3Link: + allOf: + - $ref: '#/components/schemas/link3' + - type: object + example: + href: /orders/v3/list/full + method: POST + properties: + Accept-Encoding: + in: header + required: true + type: string + request: + in: body + required: false + type: object + schema: orderListRequest + errorResponseMessage: + required: + - errors + type: object + properties: + errors: + type: array + items: + $ref: '#/components/schemas/userErrorMessage' + x-exclude: true + changeOrderListRequestV2: + required: + - changeOrders + type: object + properties: + changeOrders: + type: array + description: The change order operations + items: + $ref: '#/components/schemas/changeOrderListRequestItemV2' + description: >- + Contains all change order operations you want to make. (max 100 items + per call) + listOfValueItem: + required: + - codeIdentifier + - intIdentifier + type: object + properties: + position: + type: integer + format: int32 + example: 1 + codeIdentifier: + type: string + example: FRA + translationText: + type: string + example: France + intIdentifier: + type: integer + format: int32 + example: 1 + description: This object is used by LOV apis + userErrorMessage: + required: + - code + - message + type: object + properties: + docUrl: + $ref: '#/components/schemas/docUrl' + code: + $ref: '#/components/schemas/errorCode' + message: + type: string + description: The error message + example: > + There is already an importation in progress: + b24d0dd8-a561-478a-9b26-34f573f03527 + cultureName: + $ref: '#/components/schemas/cultureName' + arguments: + $ref: '#/components/schemas/userErrorMessageArguments' + x-exclude: true + paginationResult: + required: + - entryCount + - links + - pageCount + - totalEntryCount + type: object + properties: + entryCount: + minimum: 0 + type: integer + description: The entry count currently returned + example: 25 + pageCount: + minimum: 0 + type: integer + description: The page count + example: 38 + totalEntryCount: + minimum: 0 + type: integer + description: The total entry count + example: 943 + links: + $ref: '#/components/schemas/paginationResultLinks' + example: + entryCount: '25' + pageCount: '38' + totalEntryCount: '943' + links: + first: + href: /merchant/orders/v1/list/full + method: POST + parameters: + - name: request + in: body + type: object + schema: orderListRequest + value: + beginPeriodUtcDate: 2014-08-25T07:32:31.584Z + endPeriodUtcDate: 2014-09-24T07:32:31.584Z + pageSize: '25' + pageNumber: '1' + last: + href: /merchant/orders/v1/list/full + method: POST + parameters: + - name: request + in: body + type: object + schema: orderListRequest + value: + beginPeriodUtcDate: 2014-08-25T07:32:31.584Z + endPeriodUtcDate: 2014-09-24T07:32:31.584Z + pageSize: '25' + pageNumber: '38' + next: + href: /merchant/orders/v1/list/full + method: POST + parameters: + - name: request + in: body + type: object + schema: orderListRequest + value: + beginPeriodUtcDate: 2014-08-25T07:32:31.584Z + endPeriodUtcDate: 2014-09-24T07:32:31.584Z + pageSize: '25' + pageNumber: '2' + x-exclude: true + orderChangeType: + type: string + description: The business operation type that can be done on an order + x-lov: OrderChangeBusinessOperationType + changeOrderListRequestItemV2: + required: + - order + type: object + properties: + order: + $ref: '#/components/schemas/orderIdentifier' + changeOrderRequest: + $ref: '#/components/schemas/changeOrderRequest' + description: Contains the order identifier and the change order request + docUrl: + type: string + description: The documentation related to this operation. + format: uri + example: https://api-docs.imn.io/#operation/EnableChannelCatalog + x-exclude: true + cultureName: + type: string + description: If the error is translated, the culture name will be indicated + example: en + x-exclude: true + x-lov: Go2CultureName + userErrorMessageArguments: + type: object + additionalProperties: + type: object + properties: {} + description: a dictionary string/object + x-exclude: true + beezUPMarketplaceAccountId: + type: integer + description: >- + The marketplace account identifier in BeezUP. This account identifier is + based on your api settings. + format: int32 + example: 1234 + beezUPMarketplaceBusinessCode: + type: string + description: >- + In an marketplace technical code like CDiscount you can have several + marketplaces like GO SPORT, etc. We identify them by a business code. + example: GOSPORT + x-lov: MarketplaceBusinessCode + beezUPMarketplaceTechnicalCode: + type: string + description: The technical code of the marketplace. + example: Amazon + x-lov: MarketplaceTechnicalCode + storeId: + type: string + description: The store identifier + format: guid + x-exclude: true + orderListDateSearchType: + type: string + description: Indicates on which date you want to make the filter + default: Modification + enum: + - Modification + - Purchase + - MarketPlaceModification + paginationResultLinks: + required: + - first + - last + type: object + properties: + first: + $ref: '#/components/schemas/link3' + last: + $ref: '#/components/schemas/link3' + previous: + $ref: '#/components/schemas/link3' + next: + $ref: '#/components/schemas/link3' + description: The navigation links 'first', 'last', 'next', 'previous' + x-exclude: true + userId: + type: string + description: The user identifier + format: guid + example: 8a7fbdec-9e71-472e-9974-27d5c1d57cf8 + x-exclude: true + exchangedMessagesItem: + required: + - operationName + type: object + properties: + operationName: + type: string + requestUri: + type: string + format: uri + responseUri: + type: string + format: uri + requestUtcDate: + type: string + format: date-time + responseUtcDate: + type: string + format: date-time + link3: + required: + - href + type: object + properties: + label: + type: string + description: >- + The label corresponding to the link. This label is automatically + translated based on the Accept-Language http header. + example: The translated label + docUrl: + $ref: '#/components/schemas/docUrl' + description: + type: string + description: The description of the link + example: This is a description link + href: + $ref: '#/components/schemas/href' + operationId: + $ref: '#/components/schemas/operationId' + method: + $ref: '#/components/schemas/httpMethod' + parameters: + $ref: '#/components/schemas/linkParameter3Types' + urlTemplated: + type: boolean + description: indicates whether the href is templated or not + allRequiredParamsProvided: + type: boolean + description: indicates whether all required params have been provided + allOptionalParamsProvided: + type: boolean + description: indicates whether all optionals params have been provided + info: + $ref: '#/components/schemas/infoSummaries' + rel: + type: string + description: Indicate the relation name related to the link + x-exclude: true + orderHarvestErrors: + type: object + additionalProperties: + $ref: '#/components/schemas/orderHarvestErrorValue' + description: The key is the OrderMetaInfo. + httpUrl: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + type: string + description: >- + The URL https://en.wikipedia.org/wiki/URL + example: http://www.mydomain.com + x-exclude: true + x-pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$ + currencyCode: + pattern: ^[A-Z]{3}$ + type: string + description: > + The currency code (ISO + 4217) + example: EUR + x-exclude: true + x-pattern: ^[A-Z]{3}$ + href: + type: string + description: Indicate the relative uri for this link + example: /merchant/orders/v1/{marketplaceCode}/{IMNOrderId} + x-exclude: true + operationId: + type: string + description: The operationId to call. + example: GetOrder + x-exclude: true + httpMethod: + type: string + description: Indicate the http method to use on this link + example: GET + default: GET + enum: + - GET + - POST + - PATCH + - DELETE + - PUT + - HEAD + x-exclude: true + linkParameter3Types: + type: object + additionalProperties: + $ref: '#/components/schemas/linkParameter3' + infoSummaries: + type: object + properties: + successes: + type: array + items: + $ref: '#/components/schemas/successSummary' + errors: + type: array + items: + $ref: '#/components/schemas/errorSummary' + warnings: + type: array + items: + $ref: '#/components/schemas/warningSummary' + informations: + type: array + items: + $ref: '#/components/schemas/infoSummary' + x-exclude: true + orderHarvestErrorValue: + required: + - errorMessage + - technicalCodePropertyName + type: object + properties: + technicalCodePropertyName: + type: string + errorMessage: + type: string + linkParameter3: + required: + - in + type: object + properties: + label: + type: string + description: >- + The label corresponding to the link parameter. This label is + automatically translated based on the Accept-Language http header. + example: The translated label + value: + type: object + properties: {} + description: >- + The value of the parameter. It can be an integer a string or an + object. + required: + type: boolean + example: true + default: false + in: + $ref: '#/components/schemas/parameterIn' + lovLink: + $ref: '#/components/schemas/LOVLink3' + lovRequired: + type: boolean + description: >- + If true, you MUST indicate a value from the list of values otherwise + it's a freetext + example: true + description: + type: string + description: description of the parameter + example: the store identifier + schema: + type: string + description: schema of the parameter + example: orderListRequest + pattern: + $ref: '#/components/schemas/validationPattern' + properties: + type: object + description: >- + If the parameter is an object with flexible properties + (additionProperties/dictionary), we will describe the properties of + the object. + x-exclude: true + successSummary: + type: object + properties: + successCode: + type: string + successMessage: + type: string + successArguments: + type: object + additionalProperties: + type: string + propertyName: + type: string + propertyValue: + type: string + objectName: + type: string + errorSummary: + type: object + properties: + utcDate: + type: string + format: date-time + errorGuid: + type: string + format: uuid + errorCode: + type: string + errorMessage: + type: string + technicalErrorMessage: + type: string + exceptionDetail: + $ref: '#/components/schemas/exceptionDetail' + errorArguments: + type: object + additionalProperties: + type: string + propertyName: + type: string + propertyValue: + type: string + objectName: + type: string + source: + type: string + warningSummary: + type: object + properties: + technicalErrorMessage: + type: string + warningMessage: + type: string + warningCode: + type: string + warningArguments: + type: object + additionalProperties: + type: string + infoSummary: + type: object + properties: + informationCode: + type: string + informationMessage: + type: string + informationArguments: + type: object + additionalProperties: + type: string + propertyName: + type: string + propertyValue: + type: string + objectName: + type: string + parameterIn: + type: string + description: > + * path: if the parameter must be pass in the path uri + + * header: if the parameter must be passed in http header + + * query: if the parameter must be passed in querystring + + * body: if the parameter must be passed in the body + + * file: if the parameter must be passed in a multipart/form-data + (https://swagger.io/docs/specification/2-0/file-upload/) + example: path + enum: + - path + - header + - query + - body + - file + x-exclude: true + LOVLink3: + required: + - href + type: object + properties: + href: + type: string + description: Indicate the uri to the list of value + format: uri + example: /merchant/lov/v1/Go2CultureName + method: + $ref: '#/components/schemas/httpMethod' + description: Describe the way you have to follow to get access to the LOV + x-exclude: true + validationPattern: + type: string + description: The regular expression to validate the value + example: '*.-api$' + linkParameterProperty3: + required: + - type + type: object + properties: + label: + type: string + description: >- + The label corresponding to the link parameter property. This label + is automatically translated based on the Accept-Language http + header. + example: The translated label + value: + type: object + properties: {} + description: >- + The value of the parameter. It can be an integer a string or an + object. + required: + type: boolean + example: true + type: + $ref: '#/components/schemas/parameterType' + lovLink: + $ref: '#/components/schemas/LOVLink3' + lovRequired: + type: boolean + description: >- + If true, you MUST use indicate a value from the list of values + otherwise it's a freetext + example: true + description: + type: string + description: description of the parameter + example: the store identifier + schema: + type: string + description: schema of the parameter + example: orderListRequest + pattern: + $ref: '#/components/schemas/validationPattern' + x-exclude: true + exceptionDetail: + type: object + properties: + helpLink: + type: string + message: + type: string + stackTrace: + type: string + type: + type: string + parameterType: + type: string + description: The value type of the parameter + example: string + default: string + enum: + - string + - integer + - number + - boolean + - object + - array + - date + - date-time + - file + x-exclude: true + subscriptionLinks: + type: object + properties: + reporting: + $ref: '#/components/schemas/link3' + activate: + $ref: '#/components/schemas/link3' + deactivate: + $ref: '#/components/schemas/link3' + retry: + $ref: '#/components/schemas/link3' + delete: + $ref: '#/components/schemas/link3' + subscriptionIndex: + allOf: + - $ref: '#/components/schemas/subscription' + - type: object + properties: + links: + $ref: '#/components/schemas/subscriptionLinks' + createSubscriptionRequest: + required: + - merchantApplicationName + - merchantApplicationVersion + - name + - targetUrl + type: object + properties: + targetUrl: + $ref: '#/components/schemas/httpUrl' + name: + $ref: '#/components/schemas/subscriptionName' + merchantApplicationName: + $ref: '#/components/schemas/subscriptionMerchantApplicationName' + merchantApplicationVersion: + $ref: '#/components/schemas/subscriptionMerchantApplicationVersion' + merchantEmailAlert: + $ref: '#/components/schemas/email' + x-format: Message + subscriptionPushReporting: + required: + - duration + - eventId + - lastOrderModificationUtcDate + - orderCount + - subscriptionId + - succeed + type: object + properties: + subscriptionId: + $ref: '#/components/schemas/subscriptionId' + eventId: + $ref: '#/components/schemas/messageId' + succeed: + type: boolean + description: Indicates if the push operation has succeed + lastOrderModificationUtcDate: + type: string + description: >- + This modification date correspond to the last order pushed by your + subscription consumer + format: date-time + retryCount: + type: integer + description: >- + The retry count. When we the retry count will reach maximum retry + count, the subscription will be deactivated. + maxRetryCount: + type: integer + description: >- + The maximum BeezUP will retry to push orders. When we the retry + count will reach maximum retry count, the subscription will be + deactivated. + nextScheduledRetryUtcDate: + type: string + description: The next scheduled date we retry to send orders + format: date-time + errorMessage: + $ref: '#/components/schemas/errorResponseMessage' + requestUri: + $ref: '#/components/schemas/httpUrl' + responseUri: + $ref: '#/components/schemas/httpUrl' + orderCount: + type: integer + description: The order count sent + format: int32 + duration: + type: string + description: The duration of the push operation + format: TimeSpan + httpStatus: + type: integer + description: The HTTP status received from the consumer + format: int32 + description: The subscription push reporting + activateSubscriptionRequest: + type: object + properties: + recoverBeginPeriodOrderLastModificationUtcDate: + type: string + description: >- + If set, the date must be in the past the subscription will recover + existing orders using the begin period order last modification date. + If not set then you will receive new/updated orders in real-time. + format: date-time + recoverEndPeriodOrderLastModificationUtcDate: + type: string + description: >- + If end period set, first the date must be in the past, the + subscription will recover existing orders using the begin and the + end period order last modification date. + + If end period is not set and the begin period is set, then you will + recover existing orders from the past using the begin period last + modification date and after than you will continue to receive + new/updated orders in real-time. + + If begin/end period are not set then you will receive new/updated + orders in real-time. + + REMARK: The begin period is required if the end period is fulfilled. + + REMARK: If the end period is order last modification date is + indicated then once we have push all orders to your target url the + subscription will be desactivated. + format: date-time + x-format: Message + subscription: + required: + - id + - merchantApplicationName + - merchantApplicationVersion + - name + - status + - targetUrl + type: object + properties: + id: + $ref: '#/components/schemas/subscriptionId' + status: + $ref: '#/components/schemas/subscriptionStatus' + targetUrl: + $ref: '#/components/schemas/httpUrl' + name: + $ref: '#/components/schemas/subscriptionName' + merchantApplicationName: + $ref: '#/components/schemas/subscriptionMerchantApplicationName' + merchantApplicationVersion: + $ref: '#/components/schemas/subscriptionMerchantApplicationVersion' + recoverBeginPeriodOrderLastModificationUtcDate: + type: string + description: >- + Recover existing orders using the begin period order last + modification date. If not set then you will receive new/updated + orders in real-time. + format: date-time + recoverEndPeriodOrderLastModificationUtcDate: + type: string + description: > + Recover existing orders using the begin and the end period order + last modification date. + + Otherwise, you will receive new/updated orders in real-time. + format: date-time + lastOrderPushedModificationUtcDate: + type: string + description: >- + This modification date correspond to the last order pushed by your + subscription consumer + format: date-time + lastSuccessfulOrderPushedUtcDate: + type: string + description: >- + The date of the last pushed order successfully received by your + subscription consumer + format: date-time + consumerHealthStatus: + $ref: '#/components/schemas/consumptionAvailabilityStatus' + consumerUnvailableSinceUtcDate: + type: string + description: >- + This date indicates since when the subscription consumer is + unavailable + format: date-time + lastRetryUtcDate: + type: string + description: The last date we retry to send orders + format: date-time + retryCount: + type: integer + description: >- + The retry count. When we the retry count will reach maximum retry + count, the subscription will be deactivated. + maxRetryCount: + type: integer + description: >- + The maximum BeezUP will retry to push orders. When we the retry + count will reach maximum retry count, the subscription will be + deactivated. + nextScheduledRetryUtcDate: + type: string + description: The next scheduled date we retry to send orders + format: date-time + merchantEmailAlert: + $ref: '#/components/schemas/email' + lastErrorMessage: + $ref: '#/components/schemas/errorResponseMessage' + consumerLastRequestSentUri: + $ref: '#/components/schemas/httpUrl' + description: The subscription definition + subscriptionName: + type: string + description: The subscription name you want to use + example: MySubscriptionName + subscriptionMerchantApplicationName: + type: string + description: The name of your application + example: MyApp + subscriptionMerchantApplicationVersion: + type: string + description: The version of your application + example: '1.0' + default: '1.0' + email: + pattern: ^(.+)@(.+)$ + type: string + description: The email + format: email + example: paulsimon@mysupercompany.com + x-exclude: true + x-pattern: ^(.+)@(.+)$ + subscriptionId: + type: string + description: The identifier of the subscription to the orders for a merchant + format: guid + messageId: + type: string + description: The message identifier. It's a guid. + format: MessageId + example: b0d3faea-f881-439f-ba92-02b1168511ea + x-exclude: true + subscriptionStatus: + type: string + description: The status of your subscription + example: active + enum: + - active + - inactive + consumptionAvailabilityStatus: + type: string + description: The subscription consumption status + enum: + - Available + - Degraded + - Unavailable + getOrderInvoiceGeneralSettingsResponse: + allOf: + - $ref: '#/components/schemas/orderInvoiceGeneralSettings' + - type: object + properties: + lastInvoiceSequenceNumber: + $ref: '#/components/schemas/invoiceSequenceNumber' + getOrderInvoiceDesignPreviewResponse: + required: + - invoiceHtmlContent + type: object + properties: + invoiceHtmlContent: + $ref: '#/components/schemas/invoiceContentHtml' + generateOrderInvoiceRequest: + type: object + properties: + invoiceSequenceNumber: + $ref: '#/components/schemas/invoiceSequenceNumber' + previewOrderInvoiceRequest: + type: object + properties: + invoiceSequenceNumber: + $ref: '#/components/schemas/invoiceSequenceNumber' + previewOrderInvoiceResponse: + required: + - invoiceHtmlContent + type: object + properties: + invoiceHtmlContent: + $ref: '#/components/schemas/invoiceContentHtml' + getOrderInvoicePdfFromHtmlInvoiceUrlRequest: + required: + - orderInvoiceUri + type: object + properties: + orderInvoiceUri: + $ref: '#/components/schemas/orderInvoiceUri' + orderInvoiceGeneralSettings: + required: + - cultureName + - invoicePrefix + - invoiceStartingSequenceNumber + - productVATPercent + - shippingVATPercent + type: object + properties: + cultureName: + $ref: '#/components/schemas/cultureName' + productVATPercent: + $ref: '#/components/schemas/productVATPercent' + shippingVATPercent: + $ref: '#/components/schemas/shippingVATPercent' + invoicePrefix: + $ref: '#/components/schemas/invoicePrefix' + invoiceStartingSequenceNumber: + $ref: '#/components/schemas/invoiceSequenceNumber' + description: Order Invoice General Settings + orderInvoiceDesignSettings: + type: object + properties: + headerContentHtml: + $ref: '#/components/schemas/headerContentHtml' + footerContentHtml: + $ref: '#/components/schemas/footerContentHtml' + productVATPercent: + maximum: 100 + minimum: 0 + type: number + description: Product VAT in percent + example: 4 + shippingVATPercent: + maximum: 100 + minimum: 0 + type: number + description: Shipping cost VAT in percent + example: 8 + invoicePrefix: + pattern: ^[a-zA-Z0-9#_-]{1,50}$ + type: string + description: >- + Invoice Prefix. Can contain 1 to 50 characters, with alphanumeric + characters in lowercase uppercase and #, _, - + example: TOTO + x-pattern: ^[a-zA-Z0-9#_-]{1,50}$ + invoiceSequenceNumber: + minimum: 0 + type: integer + description: Invoice Sequence Number + example: 879 + headerContentHtml: + maxLength: 1000 + type: string + description: Header Content HTML + x-minValueLength: '0' + footerContentHtml: + maxLength: 1000 + type: string + description: Footer Content HTML + x-minValueLength: '0' + invoiceContentHtml: + type: string + description: Invoice Content HTML + orderInvoiceUri: + pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.?&\%-=])*\/?$ + type: string + description: order invoice url + example: http://www.mydomain.com + x-exclude: true + x-pattern: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.?&\%-=])*\/?$ + analyticsIndexLovLinks: + type: object + properties: + performanceIndicatorTypeLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + performanceIndicatorTypeForReportsByChannelLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + performanceIndicatorTypeForReportsByCategoryLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + performanceIndicatorTypeForReportsByProductLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + performanceIndicatorFormulaParameterTypeLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + performanceIndicatorFormulaOperatorNameLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + performanceIndicatorFilterOperatorNameLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + analyticsProductColumnFilterOperatorNameLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + analyticsNumericalProductColumnFilterOperatorNameLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + analyticsStringProductColumnFilterOperatorNameLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + storeOptimisationRuleExecutionStatusLov: + $ref: '#/components/schemas/BeezUP_Common_LOVLink3' + links.AnalyticsIndexLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/analytics + method: GET + links.GetTrackingStatusLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/analytics/tracking/status + method: GET + links.GetStoreTrackingStatusLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/tracking/status + method: GET + links.GetStoreTrackedClicksLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/tracking/clicks + method: GET + links.GetStoreTrackedOrdersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/tracking/orders + method: GET + links.GetStoreTrackedExternalOrdersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/tracking/externalorders + method: GET + links.GetStoreReportByDayLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/byday + method: POST + parameters: + request: + in: body + type: object + schema: reportByDayRequest + links.GetStoreReportByChannelLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/bychannel + method: POST + parameters: + request: + in: body + type: object + schema: reportByChannelRequest + links.GetStoreReportByCategoryLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/bycategory + method: POST + parameters: + request: + in: body + type: object + schema: reportByCategoryRequest + links.GetStoreReportByProductLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/byproduct + method: POST + parameters: + request: + in: body + type: object + schema: reportByProductRequest + links.OptimiseAllLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/optimisations/all/enable + method: POST + parameters: + request: + in: body + type: object + schema: optimiseAllRequest + value: + channelId: 2dc136a7-0d3d-4cc9-a825-a28a42c53e28 + beginPeriodUtcDate: 2006-11-20T00:00:00.000Z + endPeriodUtcDate: 2006-12-20T00:00:00.000Z + categoryFilter: + categoryPath: + - Home + - Bedroom + performanceIndicatorFilters: + - performanceIndicator: Cost + operatorName: Equals + value: '10' + advancedFilters: + marginType: Global + globalmarginPercent: '10' + linkClickToOrderType: OnClickDate + linkClickToOrderMaxDay: '5' + onlyPaymentValidatedOrders: 'true' + onlyDirectSales: 'true' + performanceIndicatorFormula: + firstParameter: Cost + operatorName: Multiply + secondParamter: ROI + thirdParameter: '100' + productState: All + analyticsProductColumnFilters: + sku: M1234 + title: Refrigérateur + additionalAnalyticsProductColumnFilters: + - columnId: 672644c7-5bd0-4e25-88c1-1f732bda5e4c + operatorName: NumericalGreaterThan + values: + - '100' + links.OptimiseLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/optimisations/enable + method: POST + parameters: + request: + in: body + type: object + schema: optimiseRequest + value: + channelId: 2dc136a7-0d3d-4cc9-a825-a28a42c53e28 + beginPeriodUtcDate: 2006-11-20T00:00:00.000Z + endPeriodUtcDate: 2006-12-20T00:00:00.000Z + categoryFilter: + categoryPath: + - Home + - Bedroom + performanceIndicatorFilters: + - performanceIndicator: Cost + operatorName: Equals + value: '10' + advancedFilters: + marginType: Global + globalmarginPercent: '10' + linkClickToOrderType: OnClickDate + linkClickToOrderMaxDay: '5' + onlyPaymentValidatedOrders: 'true' + onlyDirectSales: 'true' + performanceIndicatorFormula: + firstParameter: Cost + operatorName: Multiply + secondParamter: ROI + thirdParameter: '100' + pageSize: '100' + pageNumber: '1' + productState: All + analyticsProductColumnFilters: + sku: M1234 + title: Refrigérateur + additionalAnalyticsProductColumnFilters: + - columnId: 672644c7-5bd0-4e25-88c1-1f732bda5e4c + operatorName: NumericalGreaterThan + values: + - '100' + links.OptimiseByChannelLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/optimisations/byChannel/a2d38563-50f0-43f1-be2b-b16e7ec4f007/enable + method: POST + links.OptimiseByCategoryLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/optimisations/byCategory/4c376178-25b4-4656-a86e-e3bd3a25b139/enable + method: POST + parameters: + request: + in: body + type: ​array + value: + - a2d38563-50f0-43f1-be2b-b16e7ec4f007 + links.OptimiseByProductLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/optimisations/byProduct/6d469a54-8426-4855-abc2-9e062e2056b9/enable + method: POST + parameters: + request: + in: body + type: ​array + value: + - a2d38563-50f0-43f1-be2b-b16e7ec4f007 + links.GetReportFiltersLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/filters + method: GET + links.GetReportFilterLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/reports/filters/fb19c53c-2f63-4262-9d94-2d7faa500acd + method: GET + links.SaveReportFilterLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/filters/{reportFilterId} + method: PUT + templated: 'true' + parameters: + - name: reportFilterId + type: string + in: path + links.DeleteReportFilterLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/8f95eb1a-3691-4750-950d-a13c4a8a9bcc/reports/filters/fb19c53c-2f63-4262-9d94-2d7faa500acd + method: DELETE + links.GetRulesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules + method: GET + links.CreateRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules + method: POST + parameters: + request: + in: body + type: object + schema: createRuleRequest + value: + optimisationActionName: reenable + ruleName: My rule + reportFilterId: fb19c53c-2f63-4262-9d94-2d7faa500acd + startUtcDate: 2016-08-29T09:12:33.001Z + endUtcDate: 2017-09-30T10:42:40.001Z + links.GetRulesExecutionsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/executions + method: GET + links.RunRulesLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/run + method: POST + links.GetRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8 + method: GET + links.UpdateRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8 + method: PATCH + parameters: + request: + in: body + type: object + schema: updateRuleRequest + value: + ruleName: My Rule Renamed + startUtcDate: 2016-08-29T09:12:33.001Z + endUtcDate": 2016-08-29T09:12:33.001Z + links.DeleteRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8 + method: DELETE + links.MoveUpRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8/moveup + method: POST + links.MoveDownRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8/movedown + method: POST + links.EnableRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8/enable + method: POST + links.DisableRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8/disable + method: POST + links.RunRuleLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/analytics/10af9486-e28e-47ab-b045-e13e4acd55c3/rules/c38006b4-29d0-4b8a-978b-701a0b12d5a8/run + method: POST + analyticsIndexLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.AnalyticsIndexLink' + trackingStatus: + $ref: '#/components/schemas/links.GetTrackingStatusLink' + analyticsStoreIndexLinks: + required: + - reportFilters + - self + - trackedClicks + - trackedOrders + - trackingStatus + type: object + properties: + self: + $ref: '#/components/schemas/links.AnalyticsIndexLink' + trackingStatus: + $ref: '#/components/schemas/links.GetStoreTrackingStatusLink' + trackedClicks: + $ref: '#/components/schemas/links.GetStoreTrackedClicksLink' + trackedOrders: + $ref: '#/components/schemas/links.GetStoreTrackedOrdersLink' + trackedExternalOrders: + $ref: '#/components/schemas/links.GetStoreTrackedExternalOrdersLink' + reportByDay: + $ref: '#/components/schemas/links.GetStoreReportByDayLink' + reportByChannel: + $ref: '#/components/schemas/links.GetStoreReportByChannelLink' + reportByCategory: + $ref: '#/components/schemas/links.GetStoreReportByCategoryLink' + reportByProduct: + $ref: '#/components/schemas/links.GetStoreReportByProductLink' + optimiseAll: + $ref: '#/components/schemas/links.OptimiseAllLink' + optimise: + $ref: '#/components/schemas/links.OptimiseLink' + optimiseByChannel: + $ref: '#/components/schemas/links.OptimiseByChannelLink' + optimiseByCategory: + $ref: '#/components/schemas/links.OptimiseByCategoryLink' + optimiseByProduct: + $ref: '#/components/schemas/links.OptimiseByProductLink' + reportFilters: + $ref: '#/components/schemas/links.GetReportFiltersLink' + rules: + $ref: '#/components/schemas/links.GetRulesLink' + reportByCommonResponseLinks: + type: object + properties: + enableAllProducts: + $ref: '#/components/schemas/links.OptimiseAllLink' + disableAllProducts: + $ref: '#/components/schemas/links.OptimiseAllLink' + enableProducts: + $ref: '#/components/schemas/links.OptimiseLink' + disableProducts: + $ref: '#/components/schemas/links.OptimiseLink' + reportByChannelLinks: + type: object + properties: + enableProducts: + $ref: '#/components/schemas/links.OptimiseByChannelLink' + disableProducts: + $ref: '#/components/schemas/links.OptimiseByChannelLink' + reportByCategoryLinks: + type: object + properties: + enableProducts: + $ref: '#/components/schemas/links.OptimiseByCategoryLink' + disableProducts: + $ref: '#/components/schemas/links.OptimiseByCategoryLink' + reportByProductLinks: + type: object + properties: + oneChannelLinks: + $ref: '#/components/schemas/reportByProductOneChannelLinks' + allChannelsLinks: + $ref: '#/components/schemas/reportByProductAllChannelsLinks' + description: Depending if the report concerned multiple channels or one channel. + reportByProductOneChannelLinks: + required: + - disableProductForOneChannel + - enableProductForOneChannel + - productInfo + type: object + properties: + productInfo: + $ref: '#/components/schemas/links.GetChannelCatalogProductInfoLink' + enableProductForOneChannel: + $ref: '#/components/schemas/links.OptimiseByProductLink' + disableProductForOneChannel: + $ref: '#/components/schemas/links.OptimiseByProductLink' + description: >- + If the report concerned one product for one channel the channel catalog + product info will give you all you need to enable or disable the + product. + reportByProductAllChannelsLinks: + required: + - disableProductForAllChannels + - enableProductForAllChannels + type: object + properties: + enableProductForAllChannels: + $ref: '#/components/schemas/links.OptimiseByProductLink' + disableProductForAllChannels: + $ref: '#/components/schemas/links.OptimiseByProductLink' + reportByChannelResponseLinks: + allOf: + - $ref: '#/components/schemas/reportByCommonResponseLinks' + reportByCategoryResponseLinks: + allOf: + - $ref: '#/components/schemas/reportByCommonResponseLinks' + reportByProductResponseLinks: + allOf: + - $ref: '#/components/schemas/reportByCommonResponseLinks' + reportFiltersLinks: + required: + - save + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetReportFiltersLink' + save: + $ref: '#/components/schemas/links.SaveReportFilterLink' + reportFilterHeaderLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetReportFilterLink' + reportFilterLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetReportFilterLink' + save: + $ref: '#/components/schemas/links.SaveReportFilterLink' + delete: + $ref: '#/components/schemas/links.DeleteReportFilterLink' + description: Indicates the actions you can do on this report filter + ruleListLinks: + required: + - create + - history + - run + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetRulesLink' + create: + $ref: '#/components/schemas/links.CreateRuleLink' + history: + $ref: '#/components/schemas/links.GetRulesExecutionsLink' + run: + $ref: '#/components/schemas/links.RunRulesLink' + description: Links to know if the user can create a rule or run all rules + ruleLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetRuleLink' + update: + $ref: '#/components/schemas/links.UpdateRuleLink' + delete: + $ref: '#/components/schemas/links.DeleteRuleLink' + moveup: + $ref: '#/components/schemas/links.MoveUpRuleLink' + movedown: + $ref: '#/components/schemas/links.MoveDownRuleLink' + enable: + $ref: '#/components/schemas/links.EnableRuleLink' + disable: + $ref: '#/components/schemas/links.DisableRuleLink' + run: + $ref: '#/components/schemas/links.RunRuleLink' + reportFilter: + $ref: '#/components/schemas/links.GetReportFilterLink' + description: Links to retrieve/action on other entities + ruleExecutionReportingLinks: + type: object + properties: + rule: + $ref: '#/components/schemas/links.GetRuleLink' + description: Links to retrieve/action on this rule execution + analyticsIndex: + required: + - links + - stores + type: object + properties: + stores: + type: array + items: + $ref: '#/components/schemas/analyticsStoreIndex' + links: + $ref: '#/components/schemas/analyticsIndexLinks' + lovLinks: + $ref: '#/components/schemas/analyticsIndexLovLinks' + description: The Analytics API operation index. + analyticsStoreIndex: + required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/analyticsStoreIndexLinks' + trackingStatus: + required: + - clickSynchronizationUtcDate + - marketplaceOrderSynchonizationUtcDate + - orderSynchonizationUtcDate + type: object + properties: + clickSynchronizationUtcDate: + type: string + description: The utc date of the latest synchronized click + format: date-time + example: 2016-08-29T09:12:33.001Z + orderSynchonizationUtcDate: + type: string + description: The utc date of the latest synchronized order + format: date-time + example: 2016-08-29T09:12:33.001Z + marketplaceOrderSynchonizationUtcDate: + type: string + description: The utc date of the latest synchronized marketplace order + format: date-time + example: 2016-08-29T09:12:33.001Z + storeTrackingStatus: + type: object + properties: + clickSynchronizationUtcDate: + type: string + description: The utc date of the latest synchronized click + format: date-time + example: 2016-08-29T09:12:33.001Z + orderSynchonizationUtcDate: + type: string + description: The utc date of the latest synchronized order + format: date-time + example: 2016-08-29T09:12:33.001Z + marketplaceOrderSynchonizationUtcDate: + type: string + description: The utc date of the latest synchronized marketplace order + format: date-time + example: 2016-08-29T09:12:33.001Z + trackedClicks: + required: + - clicks + type: object + properties: + clicks: + type: array + items: + $ref: '#/components/schemas/trackedClick' + trackedClick: + required: + - channel + - ipAddress + - product + - utcDate + type: object + properties: + utcDate: + type: string + description: The utc date of the click + format: date-time + example: 2016-08-29T09:12:33.001Z + product: + $ref: '#/components/schemas/BeezUP_Common_ProductBasicInfo' + ipAddress: + type: string + description: The user IP address for the click + example: 127.0.0.1 + channel: + $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + trackedOrders: + required: + - orders + type: object + properties: + orders: + type: array + items: + $ref: '#/components/schemas/trackedOrder' + trackedOrder: + required: + - channel + - currencyCode + - merchantOrderId + - paymentValidated + - products + - totalAmount + - utcDate + type: object + properties: + utcDate: + type: string + description: The utc date of the order + format: date-time + example: 2016-08-29T09:12:33.001Z + channel: + $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + merchantOrderId: + type: string + description: The merchant order identifier + example: My_Merchant_Order_Id + totalAmount: + type: number + description: The total amount of the order + example: 101.42 + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + paymentValidated: + type: boolean + description: Indicate if the payment of this order has been validated or not + example: false + products: + type: array + description: The product list of this order + example: + - productId: 00000000-0000-0000-0000-000000000000 + productSku: SKU123345 + productTitle: My super product title + productImageUrl: >- + http://i2.cdscdn.com/pdt2/3/9/0/1/550x550/hai6901018043390/rw/haier-b20fwrss-refrigerateur-americain.jpg + productActive: 'true' + unitPrice: '101' + quantity: '1' + margin: '9' + items: + $ref: '#/components/schemas/trackedOrderProduct' + trackedOrderProduct: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_ProductBasicInfo' + - required: + - margin + - quantity + - unitPrice + type: object + properties: + unitPrice: + type: number + description: The product's unit price for the order + example: 101.42 + quantity: + type: number + description: The quantity of this product for the order + example: 1 + margin: + type: number + description: The product's margin for the order + example: 9.66 + trackedExternalOrders: + required: + - externalOrders + type: object + properties: + externalOrders: + type: array + items: + $ref: '#/components/schemas/trackedExternalOrder' + trackedExternalOrder: + required: + - currencyCode + - merchantOrderId + - paymentValidated + - totalAmount + - utcDate + type: object + properties: + utcDate: + type: string + description: The utc date of the external order + format: date-time + example: 2016-08-29T09:12:33.001Z + merchantOrderId: + type: string + description: The merchant order identifier + example: My_Order_Merchant_Id + visitorId: + type: string + description: Can be null. The visitor identifier of the external order + example: A_VISITOR_ID + totalAmount: + type: number + description: The total amount of the external order + example: 101.42 + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + paymentValidated: + type: boolean + description: >- + Indicate if the payment of this external order has been validated or + not + example: false + products: + type: array + description: Can be null. The product list included in the external order + example: + - productSku: something + productTitle: Something great + productImageUrl: >- + http://cdn3.sarenza.net/static/_img/productsV4/0000010744/MD_0000010744_29411_09.jpg?201308142051 + productActive: 'true' + merchantOrderId: My_Merchant_Order_Id + unitPrice: '101' + quantity: '1' + margin: '9' + items: + $ref: '#/components/schemas/trackedExternalOrderProduct' + trackedExternalOrderProduct: + required: + - productSku + type: object + properties: + productSku: + type: string + description: The product sku received for the external order + example: something + productTitle: + type: string + description: >- + We tried to get the catalog product title based on the product SKU. + This property can be null, if we cannot found the product. This is + possible if the product is not referenced in the imported catalog. + example: Something great + productImageUrl: + type: string + description: >- + We tried to get the catalog product image Url based on the product + SKU. This property can be null, if we cannot found the product. This + is possible if the product is not referenced in the imported + catalog. + format: uri + example: >- + http://cdn3.sarenza.net/static/_img/productsV4/0000010744/MD_0000010744_29411_09.jpg?201308142051 + productActive: + type: boolean + description: >- + We tried to get the catalog product if it's still active based on + the product SKU. This property can be null, if we cannot found the + product. This is possible if the product is not referenced in the + imported catalog. + example: true + productId: + type: string + description: >- + We tried to get the catalog product identifier based on the product + SKU. This property can be null, if we cannot found the product. This + is possible if the product is not referenced in the imported + catalog. + format: guid + example: 6d469a54-8426-4855-abc2-9e062e2056b9 + unitPrice: + type: string + description: >- + The product's unit price for the external order. This property is + voluntarily a string because the value could be an invalid one. + example: '101.42' + quantity: + type: string + description: >- + The quantity of this product for the external order. This property + is voluntarily a string because the value could be an invalid one + example: '1.00' + margin: + type: string + description: >- + The product's margin for the external order. This property is + voluntarily a string because the value could be an invalid one + example: '9.66' + reportAdvancedFilters: + required: + - linkClickToOrderType + - marginType + - onlyDirectSales + - onlyPaymentValidatedOrders + - performanceIndicatorFormula + type: object + properties: + marginType: + $ref: '#/components/schemas/marginType' + globalMarginPercent: + maximum: 100 + minimum: 0 + type: integer + description: >- + If the margin type is 'Global', indicate the percentage of sale + price. + example: 10 + linkClickToOrderType: + $ref: '#/components/schemas/linkClickToOrderType' + linkClickToOrderMaxDay: + maximum: 180 + minimum: 0 + type: integer + description: >- + If the linkOrderType is OnClickDate, indicate the max day to search + the click from the order + example: 5 + onlyPaymentValidatedOrders: + type: boolean + description: >- + If true, you will get the only the orders with payment validated. + Otherwise, you will get all orders validated or not. + example: true + default: false + onlyDirectSales: + type: boolean + description: >- + If true, you will get only direct sales. Otherwise the indirect + sales will be included. + example: true + default: false + performanceIndicatorFormula: + $ref: '#/components/schemas/performanceIndicatorFormula' + marginType: + type: string + example: Global + default: Tracker + enum: + - Tracker + - Global + linkClickToOrderType: + type: string + example: OnClickDate + default: OnPurchaseDate + enum: + - OnPurchaseDate + - OnClickDate + performanceIndicatorFormula: + type: object + properties: + firstParameter: + $ref: '#/components/schemas/performanceIndicatorFormulaParameterType' + operatorName: + $ref: '#/components/schemas/performanceIndicatorFormulaOperatorName' + secondParameter: + $ref: '#/components/schemas/performanceIndicatorFormulaParameterType' + thirdParameter: + type: integer + description: Indicate the value of the third parameter of your formula + example: 100 + description: The KPI formula + example: + firstParameter: Cost + operatorName: Multiply + secondParamter: ROI + thirdParameter: '100' + performanceIndicatorFormulaParameterType: + type: string + description: Indicate on which indicator or value you want to make your formula + example: Cost + enum: + - Cost + - TotalSales + - Margin + - TotalSalesMinusCost + - MarginMinusCost + - OrderCount + - ClickCount + - SoldProductCount + - One + performanceIndicatorFormulaOperatorName: + type: string + example: Multiply + enum: + - Multiply + - Divide + reportByDayRequest: + required: + - beginPeriodUtcDate + - endPeriodUtcDate + type: object + properties: + channelIds: + type: array + description: Indicate the channel identifier list + example: + - 2dc136a7-0d3d-4cc9-a825-a28a42c53e28 + items: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + productId: + $ref: '#/components/schemas/BeezUP_Common_ProductId' + catalogCategoryId: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryId' + beginPeriodUtcDate: + type: string + description: The begin date of the period for the report + format: date + endPeriodUtcDate: + type: string + description: The end date of the period for the report + format: date + advancedFilters: + $ref: '#/components/schemas/reportAdvancedFilters' + reportByDayPerStoreResponse: + type: object + additionalProperties: + $ref: '#/components/schemas/reportByDayResponse' + description: The key is the StoreId. + reportByDayResponse: + required: + - currencyCode + - days + - globalPerformanceIndicators + type: object + properties: + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + globalPerformanceIndicators: + $ref: '#/components/schemas/reportByDayGlobal' + days: + type: array + items: + $ref: '#/components/schemas/reportByDay' + reportByDayGlobal: + required: + - allChannels + - byChannels + type: object + properties: + allChannels: + $ref: '#/components/schemas/reportByDayGlobalAllChannels' + byChannels: + type: array + items: + $ref: '#/components/schemas/reportByDayGlobalByChannel' + reportByDayGlobalAllChannels: + required: + - performanceIndicator + type: object + properties: + performanceIndicator: + type: number + description: Indicates the global performance indicator + example: 10.42 + reportByDayGlobalByChannel: + allOf: + - $ref: '#/components/schemas/reportByDayGlobalAllChannels' + - required: + - channel + type: object + properties: + channel: + $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + reportByDay: + required: + - allChannels + - byChannels + - day + type: object + properties: + day: + type: string + format: date + allChannels: + $ref: '#/components/schemas/reportByDayAllChannels' + byChannels: + type: array + items: + $ref: '#/components/schemas/reportByDayByChannel' + reportByDayAllChannels: + required: + - clickCount + - cost + - margin + - orderCount + - performanceIndicator + - roi + - soldProductCount + - totalSales + type: object + properties: + clickCount: + type: integer + description: The click count + example: 101 + cost: + type: number + description: The cost + example: 10.42 + orderCount: + type: integer + description: The order count + example: 42 + roi: + type: number + description: The Return On Investment + example: 23.11 + margin: + type: number + description: The margin + example: 42.42 + performanceIndicator: + type: number + description: >- + The performance indicator based on the performance indicator formula + indicated in the request + example: 23.09 + totalSales: + type: number + description: The total sales + example: 234.42 + soldProductCount: + type: integer + description: The product sold count count + example: 2 + reportByDayByChannel: + allOf: + - $ref: '#/components/schemas/reportByDayAllChannels' + - required: + - channel + type: object + properties: + channel: + $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + reportFilterCommonParameters: + required: + - advancedFilters + - periodType + type: object + properties: + channelId: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + periodType: + $ref: '#/components/schemas/reportFilterPeriodType' + beginPeriodUtcDate: + type: string + description: >- + The begin date period you want to get the report. It's required only + in case of custom period type ! + format: date-time + example: 2006-11-20T00:00:00.000Z + endPeriodUtcDate: + type: string + description: >- + The end date period you want to get the report. It's required only + in case of custom period type ! + format: date-time + example: 2006-12-20T00:00:00.000Z + categoryFilter: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryFilter' + performanceIndicatorFilters: + type: array + example: + - indicator: Cost + operatorName: Equals + value: '10' + items: + $ref: '#/components/schemas/performanceIndicatorFilter' + advancedFilters: + $ref: '#/components/schemas/reportAdvancedFilters' + description: Contains common filter parameters + reportFilterPeriodType: + type: string + description: Indicates the period type we want use for the report filter + enum: + - Custom + - Yesterday + - Last7Days + - LastWeek + - ThisMonth + - Last30Days + - LastMonth + - Last60Days + - Last90Days + - Last3Months + performanceIndicatorFilter: + required: + - operatorName + - performanceIndicator + - value + type: object + properties: + performanceIndicator: + $ref: '#/components/schemas/performanceIndicatorType' + operatorName: + $ref: '#/components/schemas/performanceIndicatorFilterOperatorName' + value: + type: number + description: Indicates the filter value to apply on this indicator + example: 10.42 + performanceIndicatorType: + type: string + description: Indicate on which indicator or value you want to make your formula + example: Cost + enum: + - ClickCount + - Cost + - OrderCount + - ProductCount + - SoldProductCount + - DisabledProductCount + - EnabledProductCount + - TotalSales + - Margin + - ROI + - PerformanceIndicator + performanceIndicatorFilterOperatorName: + type: string + description: Indicates the operator you want to apply on this indicator + example: Equals + x-lov: PerformanceIndicatorFilterOperatorName + orderedReportFilterCommonParameters: + description: Contains common filter parameters with Order By functionnality + allOf: + - $ref: '#/components/schemas/reportFilterCommonParameters' + - type: object + properties: + orderBy: + $ref: '#/components/schemas/performanceIndicatorType' + orderByDirection: + $ref: '#/components/schemas/orderByDirection' + orderByDirection: + type: string + description: Indicate which direction to order results by + example: Ascending + enum: + - Ascending + - Descending + paginationRequestParameters: + type: object + properties: + pageSize: + $ref: '#/components/schemas/BeezUP_Common_PageSize' + pageNumber: + $ref: '#/components/schemas/BeezUP_Common_PageNumber' + reportByChannelRequest: + allOf: + - $ref: '#/components/schemas/orderedReportFilterCommonParameters' + - $ref: '#/components/schemas/paginationRequestParameters' + reportByChannelResponse: + required: + - channels + - currencyCode + - links + - paginationResult + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + channels: + type: array + items: + $ref: '#/components/schemas/reportByChannel' + links: + $ref: '#/components/schemas/reportByChannelResponseLinks' + reportByChannel: + required: + - catalogProductCount + - channel + - clickCount + - cost + - enabledProductCount + - links + - orderCount + - performanceIndicator + - soldProductCount + - totalSales + type: object + properties: + channel: + $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + catalogProductCount: + type: integer + description: The catalog product count + example: 101 + enabledProductCount: + type: integer + description: The enabled product count + example: 101 + clickCount: + type: integer + description: The click count + example: 1024 + cost: + type: number + description: The cost for + example: 1234.12 + orderCount: + type: integer + description: The order count + example: 42 + roi: + type: number + description: The Return On Investment + example: 42.42 + margin: + type: number + description: The margin + example: 23.1 + performanceIndicator: + type: number + description: >- + The performance indicator based on the performance indicator formula + indicated in the request + example: 12.21 + totalSales: + type: number + description: The total sales + example: 234.42 + soldProductCount: + type: integer + description: The product sold count count + example: 2 + links: + $ref: '#/components/schemas/reportByChannelLinks' + reportByCategoryRequest: + allOf: + - $ref: '#/components/schemas/orderedReportFilterCommonParameters' + - $ref: '#/components/schemas/paginationRequestParameters' + reportByCategoryResponse: + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + categories: + type: array + items: + $ref: '#/components/schemas/reportByCategory' + links: + $ref: '#/components/schemas/reportByCategoryResponseLinks' + reportByCategory: + required: + - allProductCount + - catalogCategoryId + - catalogProductCount + - clickCount + - cost + - enabledProductCount + - links + - orderCount + - performanceIndicator + - soldProductCount + - totalSales + type: object + properties: + catalogCategoryId: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryId' + catalogCategoryPath: + $ref: '#/components/schemas/BeezUP_Common_CatalogCategoryPath' + allProductCount: + type: integer + description: >- + The product count for this category. This includes all the products + that have been imported and can still have associated clicks and + orders. + example: 101 + catalogProductCount: + type: integer + description: >- + The catalog product count for this category. This includes all + products that are still present in your imported catalog. + example: 101 + enabledProductCount: + type: integer + description: >- + The enabled product count for this category. This includes all + products that are still present in your imported catalog and have + not been disabled via the optimisation feature. + example: 101 + clickCount: + type: integer + description: The click count for this category + example: 1001 + cost: + type: number + description: The cost for this category + example: 12.42 + orderCount: + type: integer + description: The order count for this category + example: 25 + roi: + type: number + description: The Return On Investment for this category + example: 25.33 + margin: + type: number + description: The margin for this category + example: 3.33 + performanceIndicator: + type: number + description: >- + The performance indicator based on the performance indicator formula + indicated in the request for this category + example: 25.33 + totalSales: + type: number + description: The total sales for this category + example: 234.42 + soldProductCount: + type: integer + description: The product sold count count for this category + example: 2 + links: + $ref: '#/components/schemas/reportByCategoryLinks' + reportByProductRequest: + allOf: + - $ref: '#/components/schemas/orderedReportFilterCommonParameters' + - $ref: '#/components/schemas/paginationRequestParameters' + - required: + - productState + type: object + properties: + productColumnsToDisplay: + $ref: '#/components/schemas/productColumnsToDisplay' + productState: + $ref: '#/components/schemas/productStateFilter' + analyticsProductColumnFilters: + $ref: '#/components/schemas/analyticsProductColumnFilters' + analyticsProductColumnFilters: + type: object + properties: + sku: + type: string + description: The product sku filter + example: M1234 + title: + type: string + description: The product title filter + example: Refrigérateur + additionalAnalyticsProductColumnFilters: + $ref: '#/components/schemas/additionalAnalyticsProductColumnFilters' + additionalAnalyticsProductColumnFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/analyticsProductColumnFilter' + description: | + Describes a filter on a product's column. + The key is the column identifier of your catalog or a custom column. + analyticsProductColumnFilter: + required: + - operatorName + type: object + properties: + operatorName: + $ref: '#/components/schemas/analyticsProductColumnFilterOperatorName' + values: + type: array + description: > + Must be null if the operator is "IsNull" or "IsNotNull". + + Can contains multiple value in case of "InList" operator. Otherwise + a single value is expected. + example: + - My value + items: + type: string + example: + 672644c7-5bd0-4e25-88c1-1f732bda5e4c: + operatorName: NumericalGreaterThan + values: + - '100' + analyticsProductColumnFilterOperatorName: + type: string + description: Indicate the operator you want to apply on the columnId + x-lov: AnalyticsProductColumnFilterOperatorName + productColumnsToDisplay: + maxItems: 1 + minItems: 0 + type: array + example: + - 4b460e31-3d1f-4117-922d-b159a64ec1d2 + items: + $ref: '#/components/schemas/BeezUP_Common_CatalogColumnId' + productStateFilter: + type: string + description: You can filter on the product state. + example: All + default: All + enum: + - All + - Enabled + - Disabled + reportByProductResponse: + required: + - currencyCode + - links + - paginationResult + - products + type: object + properties: + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + currencyCode: + $ref: '#/components/schemas/BeezUP_Common_CurrencyCode' + products: + type: array + items: + $ref: '#/components/schemas/reportByProduct' + links: + $ref: '#/components/schemas/reportByProductResponseLinks' + reportByProduct: + required: + - channelCount + - clickCount + - cost + - enabledOnChannelCount + - links + - orderCount + - performanceIndicator + - product + - soldProductCount + - totalSales + type: object + properties: + product: + $ref: '#/components/schemas/BeezUP_Common_ProductBasicInfo' + enabledOnChannelCount: + type: integer + description: The count of channel where this product is enabled + example: 1 + channelCount: + type: integer + description: The channel count where this product can be enabled + example: 2 + clickCount: + type: integer + description: The click count for this product + example: 1234 + cost: + type: number + description: The cost for this product + example: 101.42 + orderCount: + type: integer + description: The order count for this product + example: 234 + roi: + type: number + description: The Return On Investment for this product + example: 42.01 + margin: + type: number + description: The margin for this product + example: 50 + performanceIndicator: + type: number + description: >- + The performance indicator based on the performance indicator formula + indicated in the request for this product + example: 10.12 + totalSales: + type: number + description: The total sales for this product + example: 234.42 + soldProductCount: + type: integer + description: The product sold count count for this product + example: 2 + links: + $ref: '#/components/schemas/reportByProductLinks' + optimiseAllRequest: + allOf: + - $ref: '#/components/schemas/orderedReportFilterCommonParameters' + - required: + - reportType + type: object + properties: + reportType: + $ref: '#/components/schemas/reportType' + productColumnsToDisplay: + $ref: '#/components/schemas/productColumnsToDisplay' + productState: + $ref: '#/components/schemas/productStateFilter' + analyticsProductColumnFilters: + $ref: '#/components/schemas/analyticsProductColumnFilters' + optimiseRequest: + allOf: + - $ref: '#/components/schemas/optimiseAllRequest' + - $ref: '#/components/schemas/paginationRequestParameters' + copyOptimisationRequest: + required: + - channelIdSource + - channelIdTarget + - keepExistingOptimisation + type: object + properties: + channelIdSource: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + channelIdTarget: + $ref: '#/components/schemas/BeezUP_Common_ChannelId' + keepExistingOptimisation: + type: boolean + description: If true the existing optimisation will be kept + example: false + description: Copy the optimisation between 2 channels + copyOptimisationResponse: + required: + - catalogProductCount + - channel + - enabledProductCount + type: object + properties: + channel: + $ref: '#/components/schemas/BeezUP_Common_ChannelBasicInfo' + catalogProductCount: + type: integer + description: The catalog product count + example: 101 + enabledProductCount: + type: integer + description: The enabled product count + example: 101 + description: Products optimisatisation copied + reportType: + type: string + description: The report type + example: ByProduct + enum: + - ByChannel + - ByCategory + - ByProduct + - ByDay + reportFilterList: + required: + - links + - reportFilters + type: object + properties: + reportFilters: + type: array + items: + $ref: '#/components/schemas/reportFilterHeader' + links: + $ref: '#/components/schemas/reportFiltersLinks' + reportFilterHeader: + required: + - links + - reportFilterId + - reportFilterName + - reportType + type: object + properties: + reportFilterId: + type: string + description: Report filter identifier + format: guid + example: fb19c53c-2f63-4262-9d94-2d7faa500acd + reportFilterName: + type: string + description: Report filter name + example: My report filter + reportType: + $ref: '#/components/schemas/reportType' + links: + $ref: '#/components/schemas/reportFilterHeaderLinks' + reportFilter: + required: + - parameters + - reportFilterId + - reportFilterName + type: object + properties: + reportFilterId: + type: string + description: Report filter identifier + format: guid + example: fb19c53c-2f63-4262-9d94-2d7faa500acd + reportFilterName: + type: string + description: Report filter name + example: My report filter + parameters: + $ref: '#/components/schemas/reportFilterParameters' + links: + $ref: '#/components/schemas/reportFilterLinks' + saveReportFilterRequest: + required: + - parameters + - reportFilterName + type: object + properties: + reportFilterName: + type: string + description: Report filter name + example: My report filter + parameters: + $ref: '#/components/schemas/reportFilterParameters' + reportFilterParameters: + allOf: + - $ref: '#/components/schemas/reportFilterCommonParameters' + - required: + - reportType + type: object + properties: + reportType: + $ref: '#/components/schemas/reportType' + productColumnsToDisplay: + $ref: '#/components/schemas/productColumnsToDisplay' + productState: + $ref: '#/components/schemas/productStateFilter' + analyticsProductColumnFilters: + $ref: '#/components/schemas/analyticsProductColumnFilters' + ruleList: + required: + - links + - rules + type: object + properties: + rules: + type: array + description: Rule list + items: + $ref: '#/components/schemas/rule' + links: + $ref: '#/components/schemas/ruleListLinks' + rule: + required: + - actionName + - enabled + - links + - position + - reportFilterId + - ruleId + - ruleName + type: object + properties: + ruleId: + type: string + description: The identifier of the rule + format: guid + example: c38006b4-29d0-4b8a-978b-701a0b12d5a8 + ruleName: + type: string + description: The name of the rule + example: My Rule + lastExecutionStatus: + $ref: '#/components/schemas/ruleLastExecutionStatus' + lastExecutionUtcDate: + type: string + description: The utc date of the last execution + format: date-time + example: 2016-08-29T09:12:33.001Z + actionName: + $ref: '#/components/schemas/optimisationActionName' + reportFilterId: + type: string + description: Report filter identifier linked to the rule + format: guid + example: fb19c53c-2f63-4262-9d94-2d7faa500acd + position: + type: integer + description: Rule execution position + example: 1 + enabled: + type: boolean + description: Is the rule enabled + example: true + validityStartUtcDate: + type: string + description: Rule validity start utc date + format: date-time + example: 2016-08-29T09:12:33.001Z + validityEndUtcDate: + type: string + description: Rule validity end utc date + format: date-time + example: 3016-08-29T09:12:33.001Z + links: + $ref: '#/components/schemas/ruleLinks' + createRuleRequest: + required: + - optimisationActionName + - reportFilterId + - ruleName + type: object + properties: + optimisationActionName: + $ref: '#/components/schemas/optimisationActionName' + ruleName: + type: string + description: The name of the rule + example: My rule + reportFilterId: + type: string + description: The report filter to use for the rule + format: guid + example: fb19c53c-2f63-4262-9d94-2d7faa500acd + startUtcDate: + type: string + description: The start validity utc date of the rule + format: date-time + example: 2016-08-29T09:12:33.001Z + endUtcDate: + type: string + description: The end validity utc date of the rule + format: date-time + example: 2017-09-30T10:42:40.001Z + updateRuleRequest: + required: + - ruleName + type: object + properties: + ruleName: + type: string + description: The name of the rule + example: My Rule Renamed + startUtcDate: + type: string + description: Not required. The start validity utc date of the rule. + format: date-time + example: 2016-08-29T09:12:33.001Z + endUtcDate: + type: string + description: Not required. The end validity utc date of the rule + format: date-time + example: 2016-08-29T09:12:33.001Z + description: This update will replace the following values. + optimisationActionName: + type: string + description: The optimisation action + example: reenable + enum: + - reenable + - disable + ruleExecutionReportings: + type: object + properties: + executions: + type: array + description: The rules executions history + items: + $ref: '#/components/schemas/ruleExecutionReporting' + paginationResult: + $ref: '#/components/schemas/BeezUP_Common_PaginationResult' + ruleExecutionReporting: + required: + - executionSource + - ruleId + - ruleName + - status + type: object + properties: + ruleId: + type: string + description: The rule identifier + format: guid + example: fd9a23a1-569b-40af-af91-f7275a57bf89 + ruleName: + type: string + description: The name of the rule + example: toto + startedUtcDate: + type: string + description: The start utc date of the execution of the rule + format: date-time + example: 2016-08-29T09:12:33.001Z + completedUtcDate: + type: string + description: The completed utc date of the execution of the rule + format: date-time + example: 2016-08-29T09:12:33.001Z + status: + $ref: '#/components/schemas/ruleExecutionReportingStatus' + errorType: + $ref: '#/components/schemas/ruleExecutionReportingErrorType' + affectedProductCount: + type: integer + description: The count of affected products, active or not + example: 1 + activeAffectedProductCount: + type: integer + description: The count of affected active products + example: 1 + affectedChannelCount: + type: integer + description: The count of affected Channels across all products + example: 1 + optimisationActionName: + $ref: '#/components/schemas/optimisationActionName' + userId: + type: string + description: The userId that executed the rule if any + format: guid + example: e8289350-69f8-45a6-b0ca-b641c83e0422 + executionSource: + $ref: '#/components/schemas/ruleExecutionReportingExecutionSource' + reportUrl: + type: string + description: The url for the excel report for this execution + example: http://www.google.com + links: + $ref: '#/components/schemas/ruleExecutionReportingLinks' + ruleLastExecutionStatus: + type: string + description: The status of the last execution + example: Succeeded + enum: + - InProgress + - Succeeded + - Failed + - Unknown + ruleExecutionReportingStatus: + type: string + description: The status of the execution of the rule + example: Succeeded + enum: + - InProgress + - Succeeded + - AlreadyInProgress + - Aborted + - Failed + - Unknown + ruleExecutionReportingExecutionSource: + type: string + description: The requestor type for the execution of the rule + example: User + enum: + - Scheduler + - User + ruleExecutionReportingErrorType: + type: string + description: The error type for this execution if any + example: ChannelNotPresent + enum: + - ChannelNotPresent + - StoreIsInSystemBlockState + links.GetLegacyTrackingChannelCatalogsLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: /v2/user/legacyTracking/channelCatalogs + method: GET + links.GetLegacyTrackingChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/legacyTracking/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + method: GET + links.MigrateLegacyTrackingChannelCatalogLink: + allOf: + - $ref: '#/components/schemas/BeezUP_Common_Link3' + - type: object + example: + href: >- + /v2/user/legacyTracking/channelCatalogs/6d6b04de-406b-4539-8e7e-bf3e8da5dfb0/migrate + method: POST + legacyTrackingChannelCatalogListLinks: + type: object + properties: + self: + $ref: '#/components/schemas/links.GetLegacyTrackingChannelCatalogsLink' + description: > + Indicates how global actions you can do like how to create a channel + catalog, exclusion filter operators, etc... + legacyTrackingChannelCatalogLinks: + required: + - self + type: object + properties: + self: + $ref: '#/components/schemas/links.GetLegacyTrackingChannelCatalogLink' + migrate: + $ref: '#/components/schemas/links.MigrateLegacyTrackingChannelCatalogLink' + description: Indicates the actions you can do on a channel catalog + legacyTrackingChannelCatalogList: + type: object + properties: + links: + $ref: '#/components/schemas/legacyTrackingChannelCatalogListLinks' + channelCatalogs: + type: object + additionalProperties: + $ref: '#/components/schemas/legacyTrackingChannelCatalog' + description: The channel catalog list. The key is the channel catalog identifier + description: This is the index of the channel catalog API + legacyTrackingChannelCatalog: + required: + - links + type: object + properties: + links: + $ref: '#/components/schemas/legacyTrackingChannelCatalogLinks' + description: The channel catalog + responses: + 304_NotModified: + description: >- + The ETag sent in the http header If-None-Match did not change. So you + are up to date ! + headers: + ETag: + description: > + ETag value to identify the current version of the resource\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + Last-Modified: + description: > + Last modification UTC date of the resource\ + + For more details go to this link: + https://tools.ietf.org/html/rfc7232#section-2.2 + schema: + type: string + format: date-time + content: {} + 412_PreConditionFailed: + description: >- + The ETag sent in the http header If-Match did not match with the current + version. Please refresh the information related to this resource. + headers: + ETag: + description: > + The ETag value to identify the resource.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + content: {} + BadRequestResponse: + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + GeneralError: + description: Occurs when something goes wrong + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + StoreNotFoundResponse: + description: Store or resource not found + content: + application/json: + schema: + $ref: '#/components/schemas/BeezUP_Common_ErrorResponseMessage' + importAlreadyInProgress: + description: A catalog importation is already in progress! + content: + application/json: + schema: + $ref: '#/components/schemas/importAlreadyInProgressResponse' + importStarted: + description: Catalog importation started + headers: + Retry-After: + description: The duration in second to wait before polling this resource + schema: + minimum: 5 + type: integer + Location: + description: The location of the new resource to poll + schema: + type: string + content: + application/json: + schema: + $ref: >- + #/components/schemas/links.Importation_GetImportationMonitoringLink + orderGenerateForbiddenResponse: + description: | + OwnerId not authorized + The required order invoice settings have not been set + BeezUPOrderStatus forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + - OrderInvoiceDesignSettingsNotFoundException + - OrderInvoiceGeneralSettingsNotFoundException + - OrderInvoiceGenerationBeezUPOrderStatusForbiddenException + orderGenerateTooManyRequestsResponse: + description: | + Too many Requests. Please retry in a few seconds + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceTooManyRequestsException + orderInvoiceConflictResponse: + description: | + The InvoiceNumber is already used + There is already an invoice for this order + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceNumberAlreadyUsedException + - OrderAlreadyHasInvoiceException + orderInvoiceDesignSettingsNotFoundResponse: + description: | + The order invoice design is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceDesignSettingsNotFoundException + orderInvoiceGeneralSettingsNotFoundResponse: + description: | + The order invoice general settings are not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceGeneralSettingsNotFoundException + orderInvoiceNotFound: + description: | + The order invoice does not exist + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceNotFoundException + orderNotFoundResponse: + description: | + The order cannot be retrieved + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderNotFoundException + orderSubscriptionTargetNotAvailableResponse: + description: The target url is not available + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionTargetNotAvailableException + ownerIdNotAuthorizedResponse: + description: The ownerId is not found or not authorized + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - UserNotOwnerException + processingResponse: + description: >- + The marketplace configuration related to this channel catalog is + currently in progress. Please retry later. + headers: + Retry-After: + description: Indicate the duration to before the next retry in second. + schema: + type: integer + format: int32 + content: {} + retryRejectedResponse: + description: >- + The subscription is deactivated or your subscription consumption + availability status is available. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionRetryRejectedException + saveOrderInvoiceDesignSettingsBadRequestResponse: + description: | + The design did not pass the validation + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceDesignSettingsValidationFailedException + saveOrderInvoiceGeneralSettingsBadRequestResponse: + description: | + The settingsgeneral did not pass the validation + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderInvoiceGeneralSettingsValidationFailedException + subscriptionAlreadyExistsResponse: + description: The subscription id is already used. + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionAlreadyExistsException + subscriptionNotFoundResponse: + description: The subscription is not found + content: + application/json: + schema: + $ref: '#/components/schemas/errorResponseMessage' + x-exceptions: + - OrderSubscriptionNotFoundException + parameters: + ifNoneMatchParameter: + name: If-None-Match + in: header + description: > + ETag value to identify the last known version of requested resource.\ + + To avoid useless exchange, we recommend you to indicate the ETag you + previously got from this operation.\ + + If the ETag value does not match the response will be 200 to give you a + new content, otherwise the response will be: 304 Not Modified, without + any content.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + schema: + type: string + acceptEncodingRequiredParameter: + name: Accept-Encoding + in: header + description: >- + Allows the client to indicate whether it accepts a compressed encoding + to reduce traffic size. + required: true + style: simple + explode: false + schema: + type: array + items: + type: string + acceptLanguageParameter: + name: Accept-Language + in: header + description: Indicates that the client accepts the following languages. + style: simple + explode: false + schema: + type: array + items: + type: string + storeIdOnlyGeneralParameters: + name: storeId + in: path + description: Your store identifier + required: true + schema: + type: string + format: guid + executionId: + name: executionId + in: path + description: The execution identifier of you catalog importation + required: true + schema: + type: string + format: guid + catalogColumnId: + name: columnId + in: path + description: The catalog column identifier + required: true + schema: + type: string + format: guid + customColumnId: + name: columnId + in: path + description: The custom column identifier + required: true + schema: + type: string + format: guid + productSampleIndex: + name: productSampleIndex + in: path + description: Index of the product sample. Starting from 0 to 99. + required: true + schema: + maximum: 99 + minimum: 0 + type: integer + format: int32 + channelIdParameter: + name: channelId + in: path + description: The channel identifier + required: true + schema: + type: string + format: guid + example: 2dc136a7-0d3d-4cc9-a825-a28a42c53e28 + channelCatalogIdParameter: + name: channelCatalogId + in: path + description: The channel catalog identifier + required: true + schema: + type: string + format: guid + example: 6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + productIdParameter: + name: productId + in: path + description: The product identifier + required: true + schema: + type: string + format: guid + example: 578419df-1bbf-41a6-96fa-862e42182b67 + exportFormatInQueryGeneralParameter: + name: format + in: query + description: The file type of the exportation + required: true + schema: + type: string + enum: + - xlsx + - csv + groupIdParameter: + name: groupId + in: path + description: The exclusion filter group identifier + required: true + schema: + type: string + format: guid + example: 6d6b04de-406b-4539-8e7e-bf3e8da5dfb0 + pageNumberQueryStrngParameter: + name: pageNumber + in: query + description: The page number you want to get + required: true + schema: + minimum: 1 + type: integer + format: int32 + example: '1' + pageSizeQueryStrngParameter: + name: pageSize + in: query + description: The entry count you want to get + required: true + schema: + maximum: 100 + minimum: 25 + type: integer + format: int32 + example: '25' + marketplaceTechnicalCodeParameter: + name: marketplaceTechnicalCode + in: path + description: The marketplace technical code + required: true + schema: + type: string + example: Amazon + accountIdParameter: + name: accountId + in: path + required: true + schema: + type: integer + format: int32 + example: '1001' + beezUPOrderIdParameter: + name: beezUPOrderId + in: path + description: The BeezUP Order identifier + required: true + schema: + type: string + format: uuid + example: '00000000000000000000000000000000000000000000000' + changeOrderTypeParameter: + name: changeOrderType + in: path + description: The Order change type + required: true + schema: + type: string + x-lov: OrderChangeBusinessOperationType + x-lov: OrderChangeBusinessOperationType + userNameInQueryParameter: + name: userName + in: query + description: >- + Sometimes the user in the e-commerce application is not the same as user + associated with the current subscription key. We recommend providing + your application's user login. + required: true + schema: + type: string + testModeInQueryParameter: + name: testMode + in: query + description: >- + If true, the operation will be not be sent to marketplace. But the + validation will be taken in account. + schema: + type: boolean + default: false + example: 'false' + ifMatchParameter: + name: If-Match + in: header + description: > + ETag value to identify the last known version of requested resource.\ + + To ensure that you are making a change on the lastest version of the + resource.\ + + For more details go to this link: + http://tools.ietf.org/html/rfc7232#section-2.3 + required: true + schema: + type: string + storeIdsParameter: + name: storeIds + in: query + description: StoredIds to filter + style: form + explode: false + schema: + type: array + items: + type: string + subscriptionIdPathParameter: + name: id + in: path + required: true + schema: + type: string + format: SubscriptionId + marketplaceTechnicalCode: + name: marketplaceTechnicalCode + in: path + description: The Marketplace Technical Code + required: true + schema: + type: string + format: MarketplaceTechnicalCode + accountId: + name: accountId + in: path + description: The Account Identifier + required: true + schema: + type: string + format: MarketplaceAccountId + beezUPOrderUUID: + name: beezUPOrderUUID + in: path + description: The BeezUP Order UUID + required: true + schema: + type: string + format: BeezUPOrderUUID + optimisationActionNameGeneralParameters: + name: actionName + in: path + required: true + schema: + type: string + format: optimisationActionName + enum: + - reenable + - disable + reportFilterIdOnlyGeneralParameters: + name: reportFilterId + in: path + description: Your report filter identifier + required: true + schema: + type: string + format: guid + ruleIdOnlyGeneralParameters: + name: ruleId + in: path + description: Your rule identifier + required: true + schema: + type: string + format: guid + securitySchemes: + api_key: + type: apiKey + name: Ocp-Apim-Subscription-Key + in: header + description: Represents API Key 'Ocp-Apim-Subscription-Key' +x-tagGroups: + - name: Public - Security + tags: + - Public - Security - Security + - name: Public - Channels + tags: + - Public - Channels - Public Channels + - name: Public - List of Values + tags: + - Public - List of Values - LOV + - name: User - List of Values + tags: + - User - List of Values - LOV + - name: Customer + tags: + - Customer - Global + - Customer - Account + - Customer - Security + - Customer - Stores + - Customer - Shares + - Customer - Alerts + - Customer - Rights + - Customer - Friends + - Customer - Contracts + - Customer - Invoices + - name: Catalogs + tags: + - Catalogs - Auto + - Catalogs - Global + - Catalogs - Importation Process + - Catalogs - Importation Catalog Info + - Catalogs - Catalog + - name: Channels + tags: + - Channels - Channels Global + - name: Channel Catalogs + tags: + - Channel Catalogs - Global + - Channel Catalogs - Settings + - Channel Catalogs - Column Mappings + - Channel Catalogs - Categories + - Channel Catalogs - Exclusion Filters + - Channel Catalogs - Products + - Channel Catalogs - Products Overrides + - Channel Catalogs - Products Optimisation + - Channel Catalogs - Exportations + - name: Marketplaces - Channel catalogs + tags: + - Marketplaces - Channel catalogs - Global + - Marketplaces - Channel catalogs - Publications + - Marketplaces - Channel catalogs - Settings + - name: Marketplaces - Orders + tags: + - Marketplaces - Orders - Global + - Marketplaces - Orders - AutoTransitions + - Marketplaces - Orders - List + - Marketplaces - Orders - Order + - Marketplaces - Orders - Batches + - Marketplaces - Orders - Exports + - name: Marketplaces - Orders V3 + tags: + - Marketplaces - Orders V3 - Global + - Marketplaces - Orders V3 - List + - Marketplaces - Orders V3 - Order + - Marketplaces - Orders V3 - Batches + - name: Marketplaces - Orders - Subscriptions + tags: + - Marketplaces - Orders - Subscriptions - Subscriptions + - name: OM Invoice - API + tags: + - OM Invoice - API - Settings + - OM Invoice - API - Generation + - name: Analytics + tags: + - Analytics - Global + - Analytics - Tracking + - Analytics - Statistics + - Analytics - Optimisations + - Analytics - Reports + - Analytics - Rules + - name: Channel Catalogs - Legacy Tracking + tags: + - Channel Catalogs - Legacy Tracking - Global diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/box.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/box.yaml new file mode 100644 index 000000000..4c8eb9127 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/box.yaml @@ -0,0 +1,16423 @@ +openapi: 3.0.2 +info: + x-ballerina-display: + label: Box + iconPath: "icon.png" + title: Box Platform API + description: > + This is a generated connector for [Box Platform API v2.0.0](https://developer.box.com/guides/) OpenAPI specification. + + [Box Platform](https://box.dev) provides functionality to provide access to content stored within [Box](https://box.com). It provides endpoints for basic manipulation of files and folders, management of users within an enterprise, as well as more complex topics such as legal holds and retention policies. + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Create a [Box Developer Account](https://developer.box.com/) and obtain tokens following [this guide](https://developer.box.com/guides/). + termsOfService: 'https://cloud.app.box.com/s/rmwxu64h1ipr41u49w3bbuvbsa29wku9' + contact: + name: 'Box, Inc' + url: 'https://box.dev' + email: devrel@box.com + license: + name: Apache-2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0' + version: 2.0.0 +servers: + - url: 'https://api.box.com/2.0' + description: Box Platform API server +paths: + /authorize: + get: + operationId: get_authorize + summary: Authorize user + description: 'Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user''s authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format.' + tags: + - Authorization + x-box-tag: authorization + security: [] + servers: + - url: 'https://account.box.com/api/oauth2' + description: Server for client-side authentication + parameters: + - name: response_type + description: The type of response we'd like to receive. + in: query + example: code + required: true + schema: + type: string + format: token + enum: + - code + - name: client_id + description: 'The Client ID of the application that is requesting to authenticate the user. To get the Client ID for your application, log in to your Box developer console and click the **Edit Application** link for the application you''re working with. In the OAuth 2.0 Parameters section of the configuration page, find the item labelled `client_id`. The text of that item is your application''s Client ID.' + in: query + example: ly1nj6n11vionaie65emwzk575hnnmrk + required: true + schema: + type: string + - name: redirect_uri + description: The URL to which Box redirects the browser after the user has granted or denied the application permission. This URL must match the redirect URL in the configuration of your application. It must be a valid HTTPS URL and it needs to be able to handle the redirection to complete the next step in the OAuth 2.0 flow. + in: query + example: 'http://example.com/auth/callback' + required: false + schema: + type: string + format: url + - name: state + description: 'A custom string of your choice. Box will pass the same string to the redirect URL when authentication is complete. This parameter can be used to identify a user on redirect, as well as protect against hijacked sessions and other exploits.' + in: query + example: my_state + required: false + schema: + type: string + - name: scope + description: A comma-separated list of application scopes you'd like to authenticate the user for. This defaults to all the scopes configured for the application in its configuration page. + in: query + example: admin_readwrite + required: false + schema: + type: string + responses: + '200': + description: 'Does not return any data, but rather should be used in the browser.' + content: + text/html: + schema: + type: string + format: html + default: + description: 'Does not return any data, but rather should be used in the browser.' + content: + text/html: + schema: + type: string + format: html + /oauth2/token: + post: + operationId: post_oauth2_token + summary: Request access token + description: 'Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls.' + tags: + - Authorization + servers: + - url: 'https://api.box.com' + description: Server for server-side authentication + x-box-tag: authorization + security: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PostOAuth2Token' + responses: + '200': + description: 'Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer `.' + content: + application/json: + schema: + $ref: '#/components/schemas/AccessToken' + '400': + description: An authentication error. + content: + application/json: + schema: + $ref: '#/components/schemas/OAuth2Error' + default: + description: An authentication error. + content: + application/json: + schema: + $ref: '#/components/schemas/OAuth2Error' + /oauth2/token#refresh: + post: + operationId: post_oauth2_token#refresh + summary: Refresh access token + description: 'Refresh an Access Token using its client ID, secret, and refresh token.' + tags: + - Authorization + servers: + - url: 'https://api.box.com' + description: Server for server-side authentication + x-box-tag: authorization + x-box-is-variation: true + security: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PostOAuth2Token--RefreshAccessToken' + responses: + '200': + description: 'Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer `.' + content: + application/json: + schema: + $ref: '#/components/schemas/AccessToken' + '400': + description: An authentication error. + content: + application/json: + schema: + $ref: '#/components/schemas/OAuth2Error' + default: + description: An authentication error. + content: + application/json: + schema: + $ref: '#/components/schemas/OAuth2Error' + /oauth2/revoke: + post: + operationId: post_oauth2_revoke + summary: Revoke access token + description: 'Revoke an active Access Token, effectively logging a user out that has been previously authenticated.' + tags: + - Authorization + servers: + - url: 'https://api.box.com' + description: Server for server-side authentication + x-box-tag: authorization + security: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PostOAuth2Revoke' + responses: + '200': + content: {} + description: Returns an empty response when the token was successfully revoked. + '400': + description: An authentication error. + content: + application/json: + schema: + $ref: '#/components/schemas/OAuth2Error' + default: + description: An authentication error. + content: + application/json: + schema: + $ref: '#/components/schemas/OAuth2Error' + '/files/{file_id}': + get: + operationId: get_files_id + summary: Get file information + tags: + - Files + x-box-tag: files + x-box-enable-explorer: true + description: Retrieves the details about a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. Additionally this field can be used to query any metadata applied to the file by specifying the `metadata` field as well as the scope and key of the template to retrieve, for example `?field=metadata.enterprise_12345.contractTemplate`.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: if-none-match + description: Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: boxapi + description: 'The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item.' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: false + schema: + type: string + - name: x-rep-hints + description: 'A header required to request specific `representations` of a file. Use this in combination with the `fields` query parameter to request a specific file representation. The general format for these representations is `X-Rep-Hints: [...]` where `[...]` is one or many hints in the format `[fileType?query]`. For example, to request a `png` representation in `32x32` as well as `94x94` pixel dimensions provide the following hints. `X-Rep-Hints: [jpg?dimensions=32x32][jpg?dimensions=94x94]` Additionally, a `text` representation is available for all document file types in Box using the `[extracted_text]` representation. `X-Rep-Hints: [extracted_text]`' + example: '[pdf]' + in: header + required: true + schema: + type: string + nullable: true + responses: + '200': + description: 'Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/File' + '304': + description: Returns an empty response when the `If-None-Match` header matches the current `etag` value of the folder. This indicates that the folder has not changed since it was last requested. + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '415': + description: Returns an error if an action is performed on a file with an incorrect media type. * `unsupported_media_type` when requesting an `expiring_embed_link` for a file that is not supported by Box Embed. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_files_id + summary: Restore file + tags: + - Trashed files + x-box-tag: trashed_files + description: Restores a file that has been moved to the trash. An optional new parent ID can be provided to restore the file to in case the original folder has been deleted. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + description: An optional new name for the file. + example: Restored.docx + type: string + parent: + type: object + description: The parent for this item + properties: + id: + type: string + description: The ID of parent item + example: '123' + responses: + '201': + description: Returns a file object when the file has been restored. + content: + application/json: + schema: + $ref: '#/components/schemas/File' + '403': + description: 'Returns an error if the user does not have access to the folder the file is being restored to, or the user does not have permission to restore files from the trash.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the file is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: Returns an error if there is an file with the same name in the folder the file is being restored to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_files_id + summary: Update file + tags: + - Files + x-box-tag: files + x-box-enable-explorer: true + x-box-sanitized: true + description: 'Updates a file. This can be used to rename or move a file, create a shared link, or lock a file.' + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: An optional different name for the file. This can be used to rename the file. + example: NewFile.txt + description: + type: string + description: 'The description for a file. This can be seen in the right-hand sidebar panel when viewing a file in the Box web app. Additionally, this index is used in the search index of the file, allowing users to find the file by the content in the description.' + maxLength: 256 + example: The latest reports. Automatically updated + parent: + type: object + description: The parent for this item + properties: + id: + type: string + description: The ID of parent item + example: '123' + shared_link: + description: Defines a shared link for an item. Set this to `null` to remove the shared link. + type: object + properties: + access: + type: string + description: 'The level of access for the shared link. This can be restricted to anyone with the link (`open`), only people within the company (`company`) and only those who have been invited to the folder (`collaborators`). If not set, this field defaults to the access level specified by the enterprise admin. To create a shared link with this default setting pass the `shared_link` object with no `access` field, for example `{ "shared_link": {} }`. The `company` access level is only available to paid accounts.' + enum: + - open + - company + - collaborators + example: open + password: + type: string + description: The password required to access the shared link. Set the password to `null` to remove it. A password can only be set when `access` is set to `open`. + example: do-not-use-this-password + vanity_name: + type: string + description: 'Defines a custom vanity name to use in the shared link URL, for example `https://app.box.com/v/my-shared-link`. Custom URLs should not be used when sharing sensitive content as vanity URLs are a lot easier to guess than regular shared links.' + example: my-shared-link + unshared_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The timestamp at which this shared link will expire. This field can only be set by users with paid accounts. + permissions: + type: object + description: The permissions for the shared link. + properties: + can_download: + type: boolean + example: true + description: If the shared link allows for downloading of files. This can only be set when `access` is set to `open` or `company`. + lock: + type: object + description: 'Defines a lock on an item. This prevents the item from being moved, renamed, or otherwise changed by anyone other than the user who created the lock. Set this to `null` to remove the lock.' + required: + - type + properties: + access: + type: string + description: The type of this object. + enum: + - lock + example: lock + expires_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: Defines the time at which the lock expires. + is_download_prevented: + type: boolean + example: true + description: Defines if the file can be downloaded while it is locked. + permissions: + description: Defines who can download a file. + type: object + properties: + can_download: + description: 'Defines who is allowed to download this file. The possible values are either `open` for everyone or `company` for the other members of the user''s enterprise. This setting overrides the download permissions that are normally part of the `role` of a collaboration. When set to `company`, this essentially removes the download option for external users with `viewer` or `editor` a roles.' + type: string + example: open + enum: + - open + - company + tags: + type: array + example: + - approved + items: + type: string + minItems: 1 + maxItems: 100 + description: 'The tags for this item. These tags are shown in the Box web app and mobile apps next to an item. To add or remove a tag, retrieve the item''s current tags, modify them, and then update this field. There is a limit of 100 tags per item, and 10,000 unique tags per enterprise.' + responses: + '200': + description: 'Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/File' + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. * `access_denied_insufficient_permissions` when the authenticated user does not have access the destination folder to move the file to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file. This indicates that the file has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_files_id + summary: Delete file + tags: + - Files + x-box-tag: files + x-box-sanitized: true + description: 'Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash.' + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the file has been successfully deleted. + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found or has already been deleted, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file. This indicates that the file has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/content': + get: + operationId: get_files_id_content + summary: Download file + tags: + - Downloads + x-box-tag: downloads + description: Returns the contents of a file in binary format. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: range + description: 'The byte range of the content to download. The format `{start_byte}-{end_byte}` can be used to specify what section of the file to download.' + example: 0-1024 + in: header + required: false + schema: + type: string + - name: boxapi + description: 'The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item.' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: false + schema: + type: string + - name: version + description: The file version to download + example: '4' + in: query + required: false + schema: + type: string + - name: access_token + description: 'An optional access token that can be used to pre-authenticate this request, which means that a download link can be shared with a browser or a third party service without them needing to know how to handle the authentication. When using this parameter, please make sure that the access token is sufficiently scoped down to only allow read access to that file and no other files or folders.' + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + in: query + required: false + schema: + type: string + responses: + '202': + content: {} + description: If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. + headers: + Retry-After: + description: The time in seconds after which to retry the download + schema: + type: integer + '302': + description: If the file is available to be downloaded the response will include a `Location` header for the file on `dl.boxcloud.com`. The `dl.boxcloud.com` URL is not persistent and clients will need to follow the redirect in order to actually download the file. + headers: + Location: + description: A pointer to the download URL + schema: + type: string + format: url + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_files_id_content + tags: + - Uploads + x-box-tag: uploads + summary: Upload file version + description: 'Update a file''s content. For file sizes over 50MB we recommend using the Chunk Upload APIs. # Request body order The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code.' + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: content-md5 + required: false + schema: + type: string + example: 134b65991ed521fcfe4724b7d814ab8ded5185dc + in: header + description: An optional header containing the SHA1 hash of the file to ensure that the file was not corrupted in transit. + requestBody: + content: + multipart/form-data: + schema: + type: object + required: + - attributes + - file + properties: + attributes: + description: The additional attributes of the file being uploaded. Mainly the name and the parent folder. These attributes are part of the multi part request body and are in JSON format. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. + type: object + required: + - name + properties: + name: + type: string + description: 'An optional new name for the file. If specified, the file will be renamed when the new version is uploaded.' + example: Photo 2.0.png + content_modified_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: 'Defines the time the file was last modified at. If not set, the upload time will be used.' + file: + type: string + format: binary + description: The content of the file to upload to Box. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. + responses: + '200': + description: Returns the new file object in a list. + content: + application/json: + schema: + $ref: '#/components/schemas/Files' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file. This indicates that the file has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /files/content: + post: + operationId: post_files_content + tags: + - Uploads + x-box-tag: uploads + summary: Upload file + description: 'Uploads a small file to Box. For file sizes over 50MB we recommend using the Chunk Upload APIs. # Request body order The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code.' + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: content-md5 + required: false + schema: + type: string + example: 134b65991ed521fcfe4724b7d814ab8ded5185dc + in: header + description: An optional header containing the SHA1 hash of the file to ensure that the file was not corrupted in transit. + requestBody: + content: + multipart/form-data: + schema: + type: object + required: + - attributes + - file + properties: + attributes: + description: The additional attributes of the file being uploaded. Mainly the name and the parent folder. These attributes are part of the multi part request body and are in JSON format. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. + type: object + required: + - name + - parent + properties: + name: + type: string + description: The name of the file + example: Photo.png + parent: + type: object + description: The parent folder to upload the file to + required: + - id + properties: + id: + type: string + example: '124132' + description: The id of the parent folder. Use `0` for the user's root folder. + content_created_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: 'Defines the time the file was originally created at. If not set, the upload time will be used.' + content_modified_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: 'Defines the time the file was last modified at. If not set, the upload time will be used.' + file: + type: string + format: binary + description: The content of the file to upload to Box. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. + responses: + '201': + description: Returns the new file object in a list. + content: + application/json: + schema: + $ref: '#/components/schemas/Files' + '409': + description: 'Returns an error if the file already exists, or the account has run out of disk space.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /files/upload_sessions: + post: + operationId: post_files_upload_sessions + summary: Create upload session + tags: + - Uploads (Chunked) + x-box-tag: chunked_uploads + description: Creates an upload session for a new file. + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + requestBody: + content: + application/json: + schema: + type: object + required: + - folder_id + - file_size + - file_name + properties: + folder_id: + description: The ID of the folder to upload the new file to. + type: string + example: '0' + file_size: + description: The total number of bytes of the file to be uploaded + example: 104857600 + type: integer + format: int64 + file_name: + description: The name of new file + example: Project.mov + type: string + responses: + '201': + description: Returns a new upload session. + content: + application/json: + schema: + $ref: '#/components/schemas/UploadSession' + '400': + description: 'Returns an error if some of the parameters are missing or not valid. * `missing_destination`: No `folder_id` was provided * `invalid_folder_id`: `folder_id` is not valid * `item_name_invalid`: `file_name` is not valid * `missing_file_size`: `file_size` was not provided * `invalid_file_size`: `file_size` was not a valid number * `file_size_too_small`: `file_size` is below minimum file size for uploads via this API * `missing_file_name`: `file_name` was not provided' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: 'Returns an error if the operation is not allowed for some reason. * `storage_limit_exceeded`: Account storage limit reached' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if the parent folder could not be found, or the authenticated user does not have access to it. * `invalid_parameter`: The `folder_id` value represents a folder that the user does not have access to, or does not exist.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: 'Returns an error if the file already exists, or the account has run out of disk space.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/upload_sessions': + post: + operationId: post_files_id_upload_sessions + summary: Create upload session for existing file + tags: + - Uploads (Chunked) + x-box-tag: chunked_uploads + description: Creates an upload session for an existing file. + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - file_size + properties: + file_size: + description: The total number of bytes of the file to be uploaded + example: 104857600 + type: integer + format: int64 + file_name: + description: The optional new name of new file + example: Project.mov + type: string + responses: + '201': + description: Returns a new upload session. + content: + application/json: + schema: + $ref: '#/components/schemas/UploadSession' + '409': + description: 'Returns an error if the file already exists, or if the account has run out of disk space.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/upload_sessions/{upload_session_id}': + get: + operationId: get_files_upload_sessions_id + summary: Get upload session + tags: + - Uploads (Chunked) + description: Return information about an upload session. + x-box-tag: chunked_uploads + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + parameters: + - name: upload_session_id + description: The ID of the upload session. + example: D5E3F7A + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns an upload session object. + content: + application/json: + schema: + $ref: '#/components/schemas/UploadSession' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_files_upload_sessions_id + summary: Upload part of file + tags: + - Uploads (Chunked) + x-box-tag: chunked_uploads + description: Updates a chunk of an upload session for a file. + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + parameters: + - name: upload_session_id + description: The ID of the upload session. + example: D5E3F7A + in: path + required: true + schema: + type: string + - name: digest + description: 'The [RFC3230][1] message digest of the chunk uploaded. Only SHA1 is supported. The SHA1 digest must be Base64 encoded. The format of this header is as `sha=BASE64_ENCODED_DIGEST`. [1]: https://tools.ietf.org/html/rfc3230' + example: sha=fpRyg5eVQletdZqEKaFlqwBXJzM= + in: header + required: true + schema: + type: string + - name: content-range + description: The byte range of the chunk. Must not overlap with the range of a part already uploaded this session. + example: bytes 8388608-16777215/445856194 + in: header + required: true + schema: + type: string + requestBody: + content: + application/octet-stream: + schema: + type: string + format: binary + description: The binary content of the file + responses: + '200': + description: Chunk has been uploaded successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UploadedPart' + '409': + description: Returns an error if the chunk conflicts with another chunk previously uploaded. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error if a precondition was not met. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '416': + description: Returns an error if the content range does not match a specified range for the session. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_files_upload_sessions_id + summary: Remove upload session + tags: + - Uploads (Chunked) + description: Abort an upload session and discard all data uploaded. This cannot be reversed. + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + x-box-tag: chunked_uploads + parameters: + - name: upload_session_id + description: The ID of the upload session. + example: D5E3F7A + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: A blank response is returned if the session was successfully aborted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/upload_sessions/{upload_session_id}/parts': + get: + operationId: get_files_upload_sessions_id_parts + summary: List parts + tags: + - Uploads (Chunked) + x-box-tag: chunked_uploads + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + description: Return a list of the chunks uploaded to the upload session so far. + parameters: + - name: upload_session_id + description: The ID of the upload session. + example: D5E3F7A + in: path + required: true + schema: + type: string + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a list of parts that have been uploaded. + content: + application/json: + schema: + $ref: '#/components/schemas/UploadParts' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/upload_sessions/{upload_session_id}/commit': + post: + operationId: post_files_upload_sessions_id_commit + summary: Commit upload session + tags: + - Uploads (Chunked) + x-box-tag: chunked_uploads + servers: + - url: 'https://upload.box.com/api/2.0' + description: Server for file uploads + description: Close an upload session and create a file from the uploaded chunks. + parameters: + - name: upload_session_id + description: The ID of the upload session. + example: D5E3F7A + in: path + required: true + schema: + type: string + - name: digest + description: 'The [RFC3230][1] message digest of the whole file. Only SHA1 is supported. The SHA1 digest must be Base64 encoded. The format of this header is as `sha=BASE64_ENCODED_DIGEST`. [1]: https://tools.ietf.org/html/rfc3230' + in: header + example: sha=fpRyg5eVQletdZqEKaFlqwBXJzM= + required: true + schema: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: if-none-match + description: Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. + in: header + required: false + example: '1' + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - parts + properties: + parts: + type: array + description: The list details for the uploaded parts + items: + $ref: '#/components/schemas/UploadPart' + responses: + '201': + description: Returns the file object in a list. + content: + application/json: + schema: + $ref: '#/components/schemas/Files' + '202': + content: {} + description: 'Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed.' + headers: + Retry-After: + description: Indicates the number of seconds the client should wait before attempting their commit request again. + schema: + type: integer + '409': + description: Returns an error if there is already a file with the same name in the target folder. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error if the `If-Match` or `If-None-Match` conditions fail. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/copy': + post: + operationId: post_files_id_copy + summary: Copy file + description: Creates a copy of a file. + tags: + - Files + x-box-tag: files + x-box-enable-explorer: true + x-box-sanitized: true + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - parent + nullable: false + properties: + name: + type: string + description: 'An optional new name for the copied file. There are some restrictions to the file name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), and protected names like `.` and `..` are automatically sanitized by removing the non-allowed characters.' + example: FileCopy.txt + maxLength: 255 + version: + type: string + description: An optional ID of the specific file version to copy. + example: '0' + parent: + type: object + description: The destination folder to copy the file to. + required: + - id + properties: + id: + type: string + description: The ID of folder to copy the file to. + example: '0' + responses: + '201': + description: 'Returns a new file object representing the copied file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/File' + '304': + description: Returns an empty response when the `If-None-Match` header matches the current `etag` value of the file. This indicates that the file has not changed since it was last requested. + '400': + description: Returns an error if some of the parameters are missing or not valid. * `bad_request` when a parameter is missing. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if either the source file or the destination folder could not be found, or the authenticated user does not have access to either. * `not_found` when the authenticated user does not have access to the source file or the destination folder' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: '* `operation_blocked_temporary`: Returned if either of the destination or source folders is locked due to another move, copy, delete or restore operation in process. The operation can be retried at a later point. * `item_name_in_use` when a folder with the same name already exists.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/thumbnail.{extension}': + get: + operationId: get_files_id_thumbnail_id + summary: Get file thumbnail + description: 'Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `94x94`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site][1]. [1]: https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327' + tags: + - Files + x-box-tag: files + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: extension + description: The file format for the thumbnail + in: path + required: true + example: png + schema: + type: string + enum: + - png + - jpg + - name: min_height + description: The minimum height of the thumbnail + in: query + example: 32 + schema: + type: integer + minimum: 32 + maximum: 320 + - name: min_width + description: The minimum width of the thumbnail + in: query + example: 32 + schema: + type: integer + minimum: 32 + maximum: 320 + - name: max_height + description: The maximum height of the thumbnail + in: query + required: false + example: 320 + schema: + type: integer + minimum: 32 + maximum: 320 + - name: max_width + description: The maximum width of the thumbnail + in: query + required: false + example: 320 + schema: + type: integer + minimum: 32 + maximum: 320 + responses: + '200': + description: When a thumbnail can be created the thumbnail data will be returned in the body of the response. + content: + image/png: + schema: + type: string + format: binary + description: The thumbnail + image/jpg: + schema: + type: string + format: binary + description: The thumbnail + '202': + content: {} + description: 'Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail.' + headers: + Retry-After: + description: The time in seconds after which the thumbnail will be available. Your application only attempt to get the thumbnail again after this time. + schema: + type: integer + format: int64 + Location: + description: A pointer to a placeholder graphic that can be used until the thumbnail has been generated. + schema: + type: string + format: url + '302': + description: 'Returns an error when Box is not able to create a thumbnail for this file type. Instead, a `Location`-header pointing to a placeholder graphic for this file type will be returned.' + headers: + Location: + description: A pointer to a placeholder graphic that can be used for this file type. + schema: + type: string + format: url + '400': + description: 'Returns an error if some of the parameters are missing or not valid. * `requested_preview_unavailable` - an incorrect dimension was requested. This will happen if the dimension requested is larger or smaller than the available file sizes for the thumbnail format, or when when any of the size constraints contradict each other.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file, or for additional reasons. * `preview_cannot_be_generated` - Box does not support thumbnails for this type of file' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/collaborations': + get: + operationId: get_files_id_collaborations + summary: List file collaborations + description: Retrieves a list of pending and active collaborations for a file. This returns all the users that have access to the file or have been invited to the file. + tags: + - Collaborations (List) + x-box-tag: list_collaborations + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + responses: + '200': + description: 'Returns a collection of collaboration objects. If there are no collaborations on this file an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted.' + content: + application/json: + schema: + $ref: '#/components/schemas/Collaborations' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/comments': + get: + operationId: get_files_id_comments + summary: List file comments + description: Retrieves a list of comments for a file. + tags: + - Comments + x-box-tag: comments + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + responses: + '200': + description: Returns a collection of comment objects. If there are no comments on this file an empty collection will be returned. + content: + application/json: + schema: + $ref: '#/components/schemas/Comments' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/tasks': + get: + operationId: get_files_id_tasks + summary: List tasks on file + description: Retrieves a list of all the tasks for a file. This endpoint does not support pagination. + tags: + - Tasks + x-box-tag: tasks + x-box-sanitized: true + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a list of tasks on a file. If there are no tasks on this file an empty collection is returned instead. + content: + application/json: + schema: + $ref: '#/components/schemas/Tasks' + '404': + description: Returns an error when the file could not be found or the user does not have access to the file. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returns an error when the `file_id` was not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '500': + description: Returns an error when an attempt was made to retrieve tasks for the file with ID `0`. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/trash': + get: + operationId: get_files_id_trash + summary: Get trashed file + tags: + - Trashed files + x-box-tag: trashed_files + description: 'Retrieves a file that has been moved to the trash. Please note that only if the file itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API.' + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: 'Returns the file that was trashed, including information about when the it was moved to the trash.' + content: + application/json: + schema: + $ref: '#/components/schemas/File' + '404': + description: 'Returns an error if the file can not be found directly in the trash. Please note that a `HTTP 404` is also returned if any of the file''s parent folders have been moved to the trash. In that case, only that parent folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_files_id_trash + summary: Permanently remove file + tags: + - Trashed files + x-box-tag: trashed_files + description: Permanently deletes a file that is in the trash. This action cannot be undone. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the file was permanently deleted. + '404': + description: Returns an error if the file is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/versions': + get: + operationId: get_files_id_versions + summary: List all file versions + tags: + - File versions + x-box-tag: file_versions + description: 'Retrieve a list of the past versions for a file. Versions are only tracked by Box users with premium accounts. To fetch the ID of the current version of a file, use the `GET /file/:id` API.' + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + responses: + '200': + description: Returns an array of past versions for this file. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersions' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/versions/{file_version_id}': + get: + operationId: get_files_id_versions_id + summary: Get file version + tags: + - File versions + x-box-tag: file_versions + description: Retrieve a specific version of a file. Versions are only tracked for Box users with premium accounts. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: file_version_id + description: The ID of the file version + in: path + required: true + example: '1234' + schema: + type: string + responses: + '200': + description: 'Returns a specific version of a file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersion' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_files_id_versions_id + summary: Remove file version + tags: + - File versions + x-box-tag: file_versions + description: Move a file version to the trash. Versions are only tracked for Box users with premium accounts. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: file_version_id + description: The ID of the file version + in: path + required: true + example: '1234' + schema: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the file has been successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/versions/current': + post: + operationId: post_files_id_versions_current + summary: Revert file version + tags: + - File versions + x-box-tag: file_versions + description: 'Revert to a previous version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This actually creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same hash digest, `etag`, and name as the original. Other properties such as comments do not get updated to their former values.' + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + description: The file version to revert to + properties: + id: + type: string + description: The file version ID + example: '11446498' + type: + type: string + description: The type to revert to + example: file_version + enum: + - file_version + responses: + '201': + description: Returns a newly created file version object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersion' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}/watermark': + get: + operationId: get_files_id_watermark + summary: Get watermark on file + tags: + - Watermarks (Files) + x-box-tag: file_watermarks + description: Retrieve the watermark for a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns an object containing information about the watermark associated for to this file. + content: + application/json: + schema: + $ref: '#/components/schemas/Watermark' + '404': + description: Returns an error if the file does not have a watermark applied. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_files_id_watermark + summary: Apply watermark to file + tags: + - Watermarks (Files) + x-box-tag: file_watermarks + description: Applies or update a watermark on a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - watermark + properties: + watermark: + type: object + description: The watermark to imprint on the file + required: + - imprint + properties: + imprint: + type: string + example: default + description: The type of watermark to apply. Currently only supports one option. + enum: + - default + responses: + '200': + description: Returns an updated watermark if a watermark already existed on this file. + content: + application/json: + schema: + $ref: '#/components/schemas/Watermark' + '201': + description: Returns a new watermark if no watermark existed on this file yet. + content: + application/json: + schema: + $ref: '#/components/schemas/Watermark' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_files_id_watermark + summary: Remove watermark from file + tags: + - Watermarks (Files) + x-box-tag: file_watermarks + description: Removes the watermark from a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: An empty response will be returned when the watermark was successfully deleted. + '404': + description: Returns an error if the file did not have a watermark applied to it + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/file_requests/{file_request_id}': + get: + operationId: get_file_requests_id + summary: Get file request + tags: + - File requests + x-box-tag: file_requests + x-box-enable-explorer: true + description: Retrieves the information about a file request. + parameters: + - name: file_request_id + description: 'The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`.' + example: '123' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a file request object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileRequest' + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file request is not found, or the user does not have access to the associated folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_request_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_file_requests_id + summary: Update file request + tags: + - File requests + x-box-tag: file_requests + x-box-enable-explorer: true + x-box-sanitized: true + description: Updates a file request. This can be used to activate or deactivate a file request. + parameters: + - name: file_request_id + description: 'The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`.' + example: '123' + in: path + required: true + schema: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileRequestUpdateRequest' + responses: + '200': + description: Returns the updated file request object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileRequest' + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. * `access_denied_insufficient_permissions` when the authenticated user does not have access to update the file request. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file request is not found, or the user does not have access to the associated folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_request_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file request. This indicates that the file request has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_file_requests_id + summary: Delete file request + tags: + - File requests + x-box-tag: file_requests + x-box-sanitized: true + description: Deletes a file request permanently. + parameters: + - name: file_request_id + description: 'The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`.' + example: '123' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the file request has been successfully deleted. + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file request is not found or has already been deleted, or the user does not have access to the associated folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_request_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/file_requests/{file_request_id}/copy': + post: + operationId: post_file_requests_id_copy + summary: Copy file request + tags: + - File requests + x-box-tag: file_requests + x-box-enable-explorer: true + x-box-sanitized: true + description: 'Copies an existing file request that is already present on one folder, and applies it to another folder.' + parameters: + - name: file_request_id + description: 'The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`.' + example: '123' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileRequestCopyRequest' + responses: + '200': + description: Returns updated file request object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileRequest' + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. * `access_denied_insufficient_permissions` when the authenticated user does not have access to update the file request. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file request is not found, or the user does not have access to the associated folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_request_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}': + get: + operationId: get_folders_id + summary: Get folder information + tags: + - Folders + x-box-tag: folders + x-box-enable-explorer: true + x-box-sanitized: true + description: 'Retrieves details for a folder, including the first 100 entries in the folder. To fetch more items within the folder, please use the [Get items in a folder](#get-folders-id-items) endpoint.' + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. Additionally this field can be used to query any metadata applied to the file by specifying the `metadata` field as well as the scope and key of the template to retrieve, for example `?field=metadata.enterprise_12345.contractTemplate`.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: if-none-match + description: Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: boxapi + description: 'The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item.' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: false + schema: + type: string + responses: + '200': + description: 'Returns a folder, including the first 100 entries in the folder. To fetch more items within the folder, please use the [Get items in a folder](#get-folders-id-items) endpoint. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '304': + description: Returns an empty response when the `If-None-Match` header matches the current `etag` value of the folder. This indicates that the folder has not changed since it was last requested. + '403': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_folders_id + summary: Restore folder + tags: + - Trashed folders + x-box-tag: trashed_folders + description: 'Restores a folder that has been moved to the trash. An optional new parent ID can be provided to restore the folder to in case the original folder has been deleted. # Folder locking During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders.' + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + description: An optional new name for the folder. + example: Restored Photos + type: string + parent: + allOf: + - type: object + description: The parent for this item + properties: + id: + type: string + description: The ID of parent item + example: '123' + - description: Specifies an optional ID of a folder to restore the folder to when the original folder no longer exists. Please be aware that this ID will only be used if the original folder no longer exists. Use this ID to provide a fallback location to restore the folder to if the original location has been deleted. + responses: + '201': + description: Returns a folder object when the folder has been restored. + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '403': + description: 'Returns an error if the user does not have access to the folder the folder is being restored to, or the user does not have permission to restore folders from the trash.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the folder is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: '* Returned an error if there is a folder with the same name in the destination folder. * `operation_blocked_temporary`: Returned if either of the destination or source folders is locked due to another move, copy, delete or restore operation in process. The operation can be retried at a later point.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_folders_id + summary: Update folder + description: 'Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more.' + tags: + - Folders + x-box-tag: folders + x-box-sanitized: true + x-box-enable-explorer: true + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: The optional new name for this folder. + example: New Folder + description: + type: string + description: The optional description of this folder + maxLength: 256 + example: Legal contracts for the new ACME deal + nullable: false + sync_state: + type: string + example: synced + nullable: false + description: Specifies whether a folder should be synced to a user's device or not. This is used by Box Sync (discontinued) and is not used by Box Drive. + enum: + - synced + - not_synced + - partially_synced + can_non_owners_invite: + type: boolean + example: true + description: Specifies if users who are not the owner of the folder can invite new collaborators to the folder. + parent: + type: object + description: The parent folder for this folder. Use this to move the folder or to restore it out of the trash. + properties: + id: + type: string + description: The ID of the new parent folder + example: '0' + shared_link: + allOf: + - description: Defines a shared link for an item. Set this to `null` to remove the shared link. + type: object + properties: + access: + type: string + description: 'The level of access for the shared link. This can be restricted to anyone with the link (`open`), only people within the company (`company`) and only those who have been invited to the folder (`collaborators`). If not set, this field defaults to the access level specified by the enterprise admin. To create a shared link with this default setting pass the `shared_link` object with no `access` field, for example `{ "shared_link": {} }`. The `company` access level is only available to paid accounts.' + enum: + - open + - company + - collaborators + example: open + password: + type: string + description: The password required to access the shared link. Set the password to `null` to remove it. A password can only be set when `access` is set to `open`. + example: do-not-use-this-password + vanity_name: + type: string + description: 'Defines a custom vanity name to use in the shared link URL, for example `https://app.box.com/v/my-shared-link`. Custom URLs should not be used when sharing sensitive content as vanity URLs are a lot easier to guess than regular shared links.' + example: my-shared-link + unshared_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The timestamp at which this shared link will expire. This field can only be set by users with paid accounts. + permissions: + type: object + description: The permissions on shared link. + properties: + can_download: + type: boolean + example: true + description: If the shared link allows for downloading of files. This can only be set when `access` is set to `open` or `company`. + - description: Enables the creation of a shared link for a folder. + folder_upload_email: + allOf: + - title: Folder upload email + type: object + description: The Write Folder Upload Email object + properties: + access: + type: string + example: open + nullable: false + enum: + - open + - collaborators + description: 'When this parameter has been set, users can email files to the email address that has been automatically created for this folder. To create an email address, set this property either when creating or updating the folder. When set to `collaborators`, only emails from registered email addresses for collaborators will be accepted. This includes any email aliases a user might have registered. When set to `open` it will accept emails from any email address.' + - description: Setting this object enables the upload email address. This email address can be used by users to directly upload files directly to the folder via email. Setting the value to `null` will disable the email address. + tags: + type: array + example: + - approved + items: + type: string + minItems: 1 + maxItems: 100 + description: 'The tags for this item. These tags are shown in the Box web app and mobile apps next to an item. To add or remove a tag, retrieve the item''s current tags, modify them, and then update this field. There is a limit of 100 tags per item, and 10,000 unique tags per enterprise.' + is_collaboration_restricted_to_enterprise: + type: boolean + example: true + description: Specifies if new invites to this folder are restricted to users within the enterprise. This does not affect existing collaborations. + collections: + type: array + description: 'An array of collections to make this folder a member of. Currently we only support the `favorites` collection. To get the ID for a collection, use the [List all collections][1] endpoint. Passing an empty array `[]` or `null` will remove the folder from all collections. [1]: ../advanced-files-and-folders/#get-collections' + items: + title: Reference + description: The bare basic reference for an object + type: object + properties: + id: + type: string + description: The unique identifier for this object + example: '11446498' + type: + type: string + description: The type for this object + example: file + can_non_owners_view_collaborators: + type: boolean + example: true + description: 'Restricts collaborators who are not the owner of this folder from viewing other collaborations on this folder. It also restricts non-owners from inviting new collaborators. When setting this field to `false`, it is required to also set `can_non_owners_invite_collaborators` to `false` if it has not already been set.' + responses: + '200': + description: 'Returns a folder object for the updated folder Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. This call will return synchronously. This holds true even when moving folders with a large a large number of items in all of its descendants. For very large folders, this means the call could take minutes or hours to return.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '400': + description: 'Returns an error if some of the parameters are missing or not valid, or if a folder lock is preventing a move operation. * `bad_request` when a parameter is missing or incorrect. This error also happens when a password is set for a shared link with an access type of `open`. * `item_name_too_long` when the folder name is too long. * `item_name_invalid` when the folder name contains non-valid characters.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: 'Returns an error if the user does not have the required access to perform the action. * `access_denied_insufficient_permissions`: Returned when the user does not have access to the folder or parent folder, or if the folder is being moved and a folder lock has been applied to prevent such operations. * `insufficient_scope`: Returned an error if the application does not have the right scope to update folders. Make sure your application has been configured to read and write all files and folders stored in Box. * `forbidden`: Returned when the user is not allowed to perform this action for other users. This can include trying to create a Shared Link with a `company` access level on a free account.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if the folder or parent folder could not be found, or the authenticated user does not have access to either folder. * `not_found` when the authenticated user does not have access to the folder or parent folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: '* `operation_blocked_temporary`: Returned if either of the destination or source folders is locked due to another move, copy, delete or restore operation in progress. The operation can be retried at a later point. * `item_name_in_use`: Returned if a folder with the name already exists in the parent folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the folder. This indicates that the folder has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '503': + description: Returns an error when the operation takes longer than 60 seconds. The operation will continue after this response has been returned. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_folders_id + summary: Delete folder + description: 'Deletes a folder, either permanently or by moving it to the trash.' + tags: + - Folders + x-box-tag: folders + x-box-sanitized: true + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: if-match + description: Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: recursive + description: Delete a folder that is not empty by recursively deleting the folder and all of its content. + in: query + required: false + example: true + schema: + type: boolean + responses: + '204': + content: {} + description: Returns an empty response when the folder is successfully deleted or moved to the trash. + '403': + description: 'Returns an error if the user does not have the required access to perform the action. * `access_denied_insufficient_permissions`: Returned when the user does not have access to the folder, or when a folder lock has been applied to the folder to prevent deletion. * `insufficient_scope`: Returned an error if the application does not have the right scope to delete folders. Make sure your application has been configured to read and write all files and folders stored in Box.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if the folder could not be found, or the authenticated user does not have access to the folder. * `not_found` when the authenticated user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: '* `folder_not_empty`: Returned if the folder is not empty. Use the `recursive` query parameter to recursively delete the folder and its contents. * `operation_blocked_temporary`: Returned if the folder is locked due to another move, copy, delete or restore operation in progress. The operation can be retried at a later point.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the folder. This indicates that the folder has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '503': + description: Returns an error when the operation takes longer than 60 seconds. The operation will continue after this response has been returned. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}/items': + get: + operationId: get_folders_id_items + summary: List items in folder + tags: + - Folders + x-box-tag: folders + x-box-sanitized: true + x-box-enable-explorer: true + description: 'Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, please use the [Get a folder](#get-folders-id) endpoint instead.' + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. Additionally this field can be used to query any metadata applied to the file by specifying the `metadata` field as well as the scope and key of the template to retrieve, for example `?field=metadata.enterprise_12345.contractTemplate`.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: usemarker + description: 'Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response.' + in: query + required: false + example: true + schema: + type: boolean + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: boxapi + description: 'The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item.' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: false + schema: + type: string + - name: sort + description: 'Defines the **second** attribute by which items are sorted. Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. This parameter is not supported for marker-based pagination on the root folder (the folder with an ID of `0`).' + in: query + required: false + example: id + schema: + type: string + enum: + - id + - name + - date + - size + - name: direction + description: The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. + in: query + required: false + example: ASC + schema: + type: string + enum: + - ASC + - DESC + responses: + '200': + description: 'Returns a collection of files, folders, and web links contained in a folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/Items' + '403': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /folders: + post: + operationId: post_folders + summary: Create folder + tags: + - Folders + x-box-tag: folders + x-box-enable-explorer: true + description: Creates a new empty folder within the specified parent folder. + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - name + - parent + properties: + name: + type: string + description: 'The name for the new folder. There are some restrictions to the file name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are not allowed either.' + example: New Folder + maxLength: 255 + minLength: 1 + parent: + type: object + description: The parent folder to create the new folder within. + required: + - id + properties: + id: + type: string + description: The ID of parent folder + example: '0' + folder_upload_email: + allOf: + - title: Folder upload email + type: object + description: The Write Folder Upload Email object + properties: + access: + type: string + example: open + nullable: false + enum: + - open + - collaborators + description: 'When this parameter has been set, users can email files to the email address that has been automatically created for this folder. To create an email address, set this property either when creating or updating the folder. When set to `collaborators`, only emails from registered email addresses for collaborators will be accepted. This includes any email aliases a user might have registered. When set to `open` it will accept emails from any email address.' + - description: Setting this object enables the upload email address. This email address can be used by users to directly upload files directly to the folder via email. + sync_state: + type: string + example: synced + nullable: false + description: Specifies whether a folder should be synced to a user's device or not. This is used by Box Sync (discontinued) and is not used by Box Drive. + enum: + - synced + - not_synced + - partially_synced + responses: + '201': + description: 'Returns a folder object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '400': + description: Returns an error if some of the parameters are missing or not valid. * `bad_request` when a parameter is missing or incorrect. * `item_name_too_long` when the folder name is too long. * `item_name_invalid` when the folder name contains non-valid characters. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: 'Returns an error if the user does not have the required access to perform the action. This might be because they don''t have access to the folder or parent folder, or because the application does not have permission to write files and folders.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if the parent folder could not be found, or the authenticated user does not have access to the parent folder. * `not_found` when the authenticated user does not have access to the parent folder' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: '* `operation_blocked_temporary`: Returned if either of the destination or source folders is locked due to another move, copy, delete or restore operation in process. The operation can be retried at a later point. * `item_name_in_use`: Returned if a folder with the name already exists in the parent folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}/copy': + post: + operationId: post_folders_id_copy + summary: Copy folder + x-box-enable-explorer: true + x-box-tag: folders + description: Creates a copy of a folder within a destination folder. The original folder will not be changed. + tags: + - Folders + parameters: + - name: folder_id + description: 'The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied.' + example: '0' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - parent + nullable: false + properties: + name: + type: string + description: 'An optional new name for the copied folder. There are some restrictions to the file name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are not allowed either.' + example: New Folder + maxLength: 255 + minLength: 1 + parent: + type: object + description: The destination folder to copy the folder to. + required: + - id + properties: + id: + type: string + description: The ID of parent folder + example: '0' + responses: + '201': + description: 'Returns a new folder object representing the copied folder. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '304': + description: Returns an empty response when the `If-None-Match` header matches the current `etag` value of the folder. This indicates that the folder has not changed since it was last requested. + '400': + description: Returns an error if some of the parameters are missing or not valid. * `bad_request` when a parameter is missing. * `item_name_too_long` when the new folder name is too long. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if either the source or destination folder could not be found, or the authenticated user does not have access to either folders. * `not_found` when the authenticated user does not have access to the parent folder' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: 'Returns an error if a folder by this name already exists in the destination folder, or if the destination folder is locked. * `item_name_in_use` when a folder with the same name already exists.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '500': + description: Returns an error when trying to copy the root folder. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}/collaborations': + get: + operationId: get_folders_id_collaborations + summary: List folder collaborations + description: Retrieves a list of pending and active collaborations for a folder. This returns all the users that have access to the folder or have been invited to the folder. + tags: + - Collaborations (List) + x-box-tag: list_collaborations + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: 'Returns a collection of collaboration objects. If there are no collaborations on this folder an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted.' + content: + application/json: + schema: + $ref: '#/components/schemas/Collaborations' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}/trash': + get: + operationId: get_folders_id_trash + summary: Get trashed folder + tags: + - Trashed folders + x-box-tag: trashed_folders + description: 'Retrieves a folder that has been moved to the trash. Please note that only if the folder itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API.' + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: 'Returns the folder that was trashed, including information about when the it was moved to the trash.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '404': + description: 'Returns an error if the folder can not be found directly in the trash. Please note that a `HTTP 404` is also returned if any of the folder''s parent folders have been moved to the trash. In that case, only that parent folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_folders_id_trash + summary: Permanently remove folder + tags: + - Trashed folders + x-box-tag: trashed_folders + description: Permanently deletes a folder that is in the trash. This action cannot be undone. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + responses: + '204': + content: {} + description: Returns an empty response when the folder was permanently deleted. + '404': + description: Returns an error if the folder is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /folders/trash/items: + get: + operationId: get_folders_trash_items + summary: List trashed items + tags: + - Trashed items + x-box-tag: trashed_items + description: 'Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. This endpoint defaults to use offset-based pagination, yet also supports marker-based pagination using the `marker` parameter.' + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: usemarker + description: 'Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response.' + in: query + required: false + example: true + schema: + type: boolean + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: direction + description: The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. + in: query + required: false + example: ASC + schema: + type: string + enum: + - ASC + - DESC + - name: sort + description: 'Defines the **second** attribute by which items are sorted. Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. This parameter is not supported when using marker-based pagination.' + in: query + required: false + example: id + schema: + type: string + enum: + - id + - name + - date + - size + responses: + '200': + description: Returns a list of items that have been deleted + content: + application/json: + schema: + $ref: '#/components/schemas/Items' + '400': + description: 'Returns an error if some of the parameters are missing or not valid. * `invalid_parameter` can appear when the `sort`, `direction` or `offset` parameter is provided when using marker based pagination, or when the `marker` parameter is provided but `usemarker` is set to `false` or `null`.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}/watermark': + get: + operationId: get_folders_id_watermark + summary: Get watermark for folder + tags: + - Watermarks (Folders) + x-box-tag: folder_watermarks + description: Retrieve the watermark for a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + responses: + '200': + description: Returns an object containing information about the watermark associated for to this folder. + content: + application/json: + schema: + $ref: '#/components/schemas/Watermark' + '404': + description: Returns an error if the folder does not have a watermark applied. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_folders_id_watermark + summary: Apply watermark to folder + tags: + - Watermarks (Folders) + x-box-tag: folder_watermarks + description: Applies or update a watermark on a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + requestBody: + content: + application/json: + schema: + type: object + required: + - watermark + properties: + watermark: + type: object + description: The watermark to imprint on the folder + required: + - imprint + properties: + imprint: + type: string + example: default + description: The type of watermark to apply. Currently only supports one option. + enum: + - default + responses: + '200': + description: Returns an updated watermark if a watermark already existed on this folder. + content: + application/json: + schema: + $ref: '#/components/schemas/Watermark' + '201': + description: Returns a new watermark if no watermark existed on this folder yet. + content: + application/json: + schema: + $ref: '#/components/schemas/Watermark' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_folders_id_watermark + summary: Remove watermark from folder + tags: + - Watermarks (Folders) + x-box-tag: folder_watermarks + description: Removes the watermark from a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + responses: + '204': + content: {} + description: An empty response will be returned when the watermark was successfully deleted. + '404': + description: Returns an error if the folder did not have a watermark applied to it + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /folder_locks: + get: + operationId: get_folder_locks + summary: List folder locks + tags: + - Folder Locks + x-box-tag: folder_locks + x-box-sanitized: true + x-box-enable-explorer: true + description: Retrieves folder lock details for a given folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: query + required: true + schema: + type: string + nullable: false + responses: + '200': + description: 'Returns details for all folder locks applied to the folder, including the lock type and user that applied the lock.' + content: + application/json: + schema: + $ref: '#/components/schemas/FolderLocks' + '403': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_folder_locks + summary: Create folder lock + tags: + - Folder Locks + x-box-tag: folder_locks + x-box-sanitized: true + x-box-enable-explorer: true + description: 'Creates a folder lock on a folder, preventing it from being moved and/or deleted.' + requestBody: + content: + application/json: + schema: + type: object + required: + - folder + properties: + locked_operations: + type: object + description: 'The operations to lock for the folder. If `locked_operations` is included in the request, both `move` and `delete` must also be included and both set to `true`.' + required: + - move + - delete + properties: + move: + type: boolean + description: Whether moving the folder should be locked. + example: true + delete: + type: boolean + description: Whether deleting the folder should be locked. + example: true + folder: + type: object + description: The folder to apply the lock to. + required: + - type + - id + properties: + type: + type: string + description: The content type the lock is being applied to. Only `folder` is supported. + example: folder + id: + type: string + description: The ID of the folder. + example: '1234567890' + responses: + '200': + description: 'Returns the instance of the folder lock that was applied to the folder, including the user that applied the lock and the operations set.' + content: + application/json: + schema: + $ref: '#/components/schemas/FolderLock' + '400': + description: 'Returns an error when the request body is not valid. * `schema_validation_failed` - The request body contains a value for a field that either does not exist, or for which the value or type does not match the expected field type. An example might be an unknown option for an `enum` or `multiSelect` field.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error when the folder could not be found. * `not_found` - The folder could not be found, the user does not have access to the folder, or the user making call is not an owner or co-owner of folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folder_locks/{folder_lock_id}': + delete: + operationId: delete_folder_locks_id + summary: Delete folder lock + description: Deletes a folder lock on a given folder. + tags: + - Folder Locks + x-box-tag: folder_locks + x-box-sanitized: true + parameters: + - name: folder_lock_id + description: The ID of the folder lock. + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + responses: + '204': + content: {} + description: Returns an empty response when the folder lock is successfully deleted. + '403': + description: 'Returns an error if the user does not have the required access to perform the action. * `access_denied_insufficient_permissions`: Returned when the user does not have access to the folder. * `insufficient_scope`: Returned an error if the application does not have the right scope to delete folders. Make sure your application has been configured to read and write all files and folders stored in Box.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if the folder could not be found, or the authenticated user does not have access to the folder. * `not_found` when the authenticated user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/comments/{comment_id}': + get: + operationId: get_comments_id + summary: Get comment + tags: + - Comments + x-box-tag: comments + description: 'Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment.' + parameters: + - name: comment_id + description: The ID of the comment. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns a full comment object. + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_comments_id + summary: Update comment + tags: + - Comments + x-box-tag: comments + description: Update the message of a comment. + parameters: + - name: comment_id + description: The ID of the comment. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + message: + type: string + description: The text of the comment to update + example: Review completed! + responses: + '200': + description: Returns the updated comment object. + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_comments_id + summary: Remove comment + tags: + - Comments + x-box-tag: comments + description: Permanently deletes a comment. + parameters: + - name: comment_id + description: The ID of the comment. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the comment has been deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /comments: + post: + operationId: post_comments + tags: + - Comments + x-box-tag: comments + summary: Create comment + description: 'Adds a comment by the user to a specific file, or as a reply to an other comment.' + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - message + properties: + message: + type: string + description: 'The text of the comment. To mention a user, use the `tagged_message` parameter instead.' + example: Review completed! + tagged_message: + type: string + description: 'The text of the comment, including `@[user_id:name]` somewhere in the message to mention another user, which will send them an email notification, letting them know they have been mentioned. The `user_id` is the target user''s ID, where the `name` can be any custom phrase. In the Box UI this name will link to the user''s profile. If you are not mentioning another user, use `message` instead.' + example: '@[1234:John] Review completed!' + item: + type: object + description: The item to attach the comment to. + required: + - id + - type + properties: + id: + type: string + description: The ID of the item + example: '11446498' + type: + type: string + description: The type of the item that this comment will be placed on. + example: file + enum: + - file + - comment + responses: + '201': + description: 'Returns the newly created comment object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields.' + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/collaborations/{collaboration_id}': + get: + operationId: get_collaborations_id + summary: Get collaboration + x-box-tag: user_collaborations + tags: + - Collaborations + description: Retrieves a single collaboration. + parameters: + - name: collaboration_id + description: The ID of the collaboration + in: path + required: true + example: '1234' + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns a collaboration object. + content: + application/json: + schema: + $ref: '#/components/schemas/Collaboration' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_collaborations_id + tags: + - Collaborations + x-box-tag: user_collaborations + summary: Update collaboration + description: 'Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites.' + parameters: + - name: collaboration_id + description: The ID of the collaboration + in: path + required: true + example: '1234' + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - role + properties: + role: + type: string + description: The level of access granted. + example: editor + enum: + - editor + - viewer + - previewer + - uploader + - previewer uploader + - viewer uploader + - co-owner + - owner + status: + type: string + description: ' Set the status of a `pending` collaboration invitation, effectively accepting, or rejecting the invite.' + example: accepted + enum: + - pending + - accepted + - rejected + expires_at: + type: string + format: date-time + description: 'Update the expiration date for the collaboration. At this date, the collaboration will be automatically removed from the item. This feature will only work if the **Automatically remove invited collaborators: Allow folder owners to extend the expiry date** setting has been enabled in the **Enterprise Settings** of the **Admin Console**. When the setting is not enabled, collaborations can not have an expiry date and a value for this field will be result in an error. Additionally, a collaboration can only be given an expiration if it was created after the **Automatically remove invited collaborator** setting was enabled.' + example: '2019-08-29T23:59:00-07:00' + can_view_path: + type: boolean + description: 'Determines if the invited users can see the entire parent path to the associated folder. The user will not gain privileges in any parent folder and therefore can not see content the user is not collaborated on. Be aware that this meaningfully increases the time required to load the invitee''s **All Files** page. We recommend you limit the number of collaborations with `can_view_path` enabled to 1,000 per user.' + example: true + responses: + '200': + description: Returns an updated collaboration object unless the owner has changed. + content: + application/json: + schema: + $ref: '#/components/schemas/Collaboration' + '204': + description: 'If the role is changed to `owner`, the collaboration is deleted and a new collaboration is created. The previous `owner` of the old collaboration will be a `co-owner` on the new collaboration.' + content: + application/json: + schema: + $ref: '#/components/schemas/Collaboration' + '403': + description: 'Returns an error if the authenticated user does not have the right permissions to update the collaboration. Additionally, this error may occur when attempting to update the `expires_at` field for the collaboration without the **Automatically remove invited collaborators: Allow folder owners to extend the expiry date** setting enabled in the admin dashboard of the enterprise.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_collaborations_id + summary: Remove collaboration + tags: + - Collaborations + x-box-tag: user_collaborations + description: Deletes a single collaboration. + parameters: + - name: collaboration_id + description: The ID of the collaboration + in: path + required: true + example: '1234' + schema: + type: string + responses: + '204': + content: {} + description: A blank response is returned if the collaboration was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /collaborations: + get: + operationId: get_collaborations + summary: List pending collaborations + tags: + - Collaborations (List) + x-box-tag: list_collaborations + description: Retrieves all pending collaboration invites for this user. + parameters: + - name: status + description: The status of the collaborations to retrieve + in: query + required: true + example: pending + schema: + type: string + enum: + - pending + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: 'Returns a collection of pending collaboration objects. If the user has no pending collaborations, the collection will be empty.' + content: + application/json: + schema: + $ref: '#/components/schemas/Collaborations' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_collaborations + tags: + - Collaborations + x-box-tag: user_collaborations + summary: Create collaboration + description: 'Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group''s ability to be invited.' + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: notify + description: Determines if users should receive email notification for the action performed. + in: query + required: false + example: true + schema: + type: boolean + requestBody: + content: + application/json: + schema: + type: object + required: + - item + - accessible_by + - role + properties: + item: + type: object + description: The item to attach the comment to. + required: + - id + - type + properties: + type: + type: string + description: The type of the item that this collaboration will be granted access to + example: file + enum: + - file + - folder + id: + type: string + description: The ID of the item that will be granted access to + example: '11446498' + accessible_by: + type: object + description: The user or group to give access to the item. + required: + - type + properties: + type: + type: string + description: The type of collaborator to invite. + example: user + enum: + - user + - group + id: + type: string + description: 'The ID of the user or group. Alternatively, use `login` to specify a user by email address.' + example: '23522323' + login: + type: string + description: 'The email address of the user to grant access to the item. Alternatively, use `id` to specify a user by user ID.' + example: john@example.com + role: + type: string + description: The level of access granted. + example: editor + enum: + - editor + - viewer + - previewer + - uploader + - previewer uploader + - viewer uploader + - co-owner + can_view_path: + type: boolean + description: 'Determines if the invited users can see the entire parent path to the associated folder. The user will not gain privileges in any parent folder and therefore can not see content the user is not collaborated on. Be aware that this meaningfully increases the time required to load the invitee''s **All Files** page. We recommend you limit the number of collaborations with `can_view_path` enabled to 1,000 per user.' + example: true + expires_at: + type: string + format: date-time + description: 'Set the expiration date for the collaboration. At this date, the collaboration will be automatically removed from the item. This feature will only work if the **Automatically remove invited collaborators: Allow folder owners to extend the expiry date** setting has been enabled in the **Enterprise Settings** of the **Admin Console**. When the setting is not enabled, collaborations can not have an expiry date and a value for this field will be result in an error.' + example: '2019-08-29T23:59:00-07:00' + responses: + '201': + description: Returns a new collaboration object. + content: + application/json: + schema: + $ref: '#/components/schemas/Collaboration' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /tasks: + post: + operationId: post_tasks + tags: + - Tasks + summary: Create task + x-box-tag: tasks + x-box-santized: true + description: Creates a single task on a file. This task is not assigned to any user and will need to be assigned separately. + requestBody: + content: + application/json: + schema: + type: object + required: + - item + properties: + item: + type: object + description: The file to attach the task to. + required: + - id + - type + properties: + id: + type: string + description: The ID of the file + example: '11446498' + type: + type: string + description: '`file`' + example: file + enum: + - file + action: + type: string + description: The action the task assignee will be prompted to do. Must be * `review` defines an approval task that can be approved or rejected * `complete` defines a general task which can be completed + example: review + default: review + enum: + - review + - complete + message: + type: string + default: '' + description: An optional message to include with the task. + example: Please review + due_at: + type: string + format: date-time + description: Defines when the task is due. Defaults to `null` if not provided. + example: '2012-12-12T10:53:43-08:00' + completion_rule: + type: string + description: Defines which assignees need to complete this task before the task is considered completed. * `all_assignees` (default) requires all assignees to review or approve the the task in order for it to be considered completed. * `any_assignee` accepts any one assignee to review or approve the the task in order for it to be considered completed. + example: all_assignees + default: all_assignees + enum: + - all_assignees + - any_assignee + responses: + '201': + description: Returns the newly created task. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '400': + description: Returned if the request parameters or body is not valid. * `bad_request` when the body does not contain a valid request. This may be because the `action` or `completion_rule` are not one of the allowed values. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returns an error when the user does not have the permission to create a task on the file. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error when the file could not be found or the user does not have access to the file. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/tasks/{task_id}': + get: + operationId: get_tasks_id + summary: Get task + tags: + - Tasks + x-box-tag: tasks + x-box-sanitized: true + description: Retrieves information about a specific task. + parameters: + - name: task_id + description: The ID of the task. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a task object. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '404': + description: Returns an error when the task could not be found or the user does not have access to the file the task is assigned to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_tasks_id + tags: + - Tasks + summary: Update task + x-box-tag: tasks + x-box-sanitized: true + description: 'Updates a task. This can be used to update a task''s configuration, or to update its completion state.' + parameters: + - name: task_id + description: The ID of the task. + example: '12345' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + action: + type: string + description: The action the task assignee will be prompted to do. Must be * `review` defines an approval task that can be approved or rejected * `complete` defines a general task which can be completed + example: review + enum: + - review + - complete + message: + type: string + description: The message included with the task. + example: Please review + due_at: + type: string + format: date-time + description: When the task is due at. + example: '2012-12-12T10:53:43-08:00' + completion_rule: + type: string + description: Defines which assignees need to complete this task before the task is considered completed. * `all_assignees` (default) requires all assignees to review or approve the the task in order for it to be considered completed. * `any_assignee` accepts any one assignee to review or approve the the task in order for it to be considered completed. + example: all_assignees + enum: + - all_assignees + - any_assignee + responses: + '200': + description: Returns the updated task object + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '400': + description: Returned if the request parameters or body is not valid. * `bad_request` when the body does not contain a valid request. This may be because the `action` or `completion_rule` are not one of the allowed values. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returns an error when the user does not have the permission to update a task on the file. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error when the file could not be found or the user does not have access to the file. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_tasks_id + tags: + - Tasks + summary: Remove task + x-box-tag: tasks + x-box-sanitized: true + description: Removes a task from a file. + parameters: + - name: task_id + description: The ID of the task. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the task was successfully deleted. + '404': + description: Returns an error when the task could not be found or the user does not have access to the file the task is assigned to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/tasks/{task_id}/assignments': + get: + operationId: get_tasks_id_assignments + summary: List task assignments + tags: + - Task assignments + x-box-tag: task_assignments + x-box-sanitized: true + description: Lists all of the assignments for a given task. + parameters: + - name: task_id + description: The ID of the task. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a collection of task assignment defining what task on a file has been assigned to which users and by who. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskAssignments' + '404': + description: Returns an error when the task could not be found or the user does not have access to the file the task is assigned to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '500': + description: Returns an error if the task assignment ID was omitted in the request. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /task_assignments: + post: + operationId: post_task_assignments + summary: Assign task + tags: + - Task assignments + x-box-tag: task_assignments + x-box-sanitized: true + description: Assigns a task to a user. A task can be assigned to more than one user by creating multiple assignments. + requestBody: + content: + application/json: + schema: + type: object + required: + - task + - assign_to + properties: + task: + type: object + description: The task to assign to a user. + required: + - id + - type + properties: + id: + type: string + description: The ID of the task + example: '11446498' + type: + type: string + description: The type of the item to assign. + example: task + enum: + - task + assign_to: + type: object + description: The user to assign the task to. + properties: + id: + type: string + description: The ID of the user to assign to the task. To specify a user by their email address use the `login` parameter. + example: '3242343' + login: + type: string + description: The email address of the user to assign to the task. To specify a user by their user ID please use the `id` parameter. + example: john@example.com + responses: + '201': + description: Returns a new task assignment object. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskAssignment' + '403': + description: Returns an error if a change to a completed task is attempted + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error when the task could not be found or the user does not have access to the file the task is assigned to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '500': + description: 'Returns an error if any of the IDs for this request were not valid, or if the targeted user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/task_assignments/{task_assignment_id}': + get: + operationId: get_task_assignments_id + summary: Get task assignment + tags: + - Task assignments + x-box-tag: task_assignments + x-box-sanitized: true + description: Retrieves information about a task assignment. + parameters: + - name: task_assignment_id + description: The ID of the task assignment. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: 'Returns a task assignment, specifying who the task has been assigned to and by whom.' + content: + application/json: + schema: + $ref: '#/components/schemas/TaskAssignment' + '404': + description: Returns an error when the task assignment could not be found or the user does not have access to the file the task is assigned to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_task_assignments_id + summary: Update task assignment + tags: + - Task assignments + x-box-tag: task_assignments + x-box-sanitized: true + description: Updates a task assignment. This endpoint can be used to update the state of a task assigned to a user. + parameters: + - name: task_assignment_id + description: The ID of the task assignment. + example: '12345' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + message: + type: string + description: An optional message by the assignee that can be added to the task. + example: Looks good to me + resolution_state: + type: string + description: 'The state of the task assigned to the user. * For a task with an `action` value of `complete` this can be `incomplete` or `completed`. * For a task with an `action` of `review` this can be `incomplete`, `approved`, or `rejected`.' + example: completed + enum: + - completed + - incomplete + - approved + - rejected + responses: + '200': + description: Returns the updated task assignment object. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskAssignment' + '400': + description: Returns an error if a resolution state is incompatible with the action type of the task. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error when the task assignment could not be found or the user does not have access to the file the task is assigned to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_task_assignments_id + summary: Unassign task + tags: + - Task assignments + x-box-tag: task_assignments + x-box-sanitized: true + description: Deletes a specific task assignment. + parameters: + - name: task_assignment_id + description: The ID of the task assignment. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the task assignment was successfully deleted. + '404': + description: Returns an error if the task assignment for the given ID does not exist or is inaccessible to your account. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /shared_items: + get: + operationId: get_shared_items + summary: Find file for shared link + tags: + - Shared links (Files) + x-box-tag: shared_links_files + x-box-enable-explorer: true + description: 'Return the file represented by a shared link. A shared file can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared file when only given a shared link.' + parameters: + - name: if-none-match + description: Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: boxapi + description: 'A header containing the shared link and optional password for the shared link. The format for this header is as follows. `shared_link=[link]&shared_link_password=[password]`' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: true + schema: + type: string + responses: + '200': + description: Returns a full file resource if the shared link is valid and the user has access to it. + content: + application/json: + schema: + $ref: '#/components/schemas/File' + '304': + description: Returns an empty response when the `If-None-Match` header matches the current `etag` value of the folder. This indicates that the folder has not changed since it was last requested. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}#get_shared_link': + get: + operationId: get_files_id#get_shared_link + summary: Get shared link for file + tags: + - Shared links (Files) + x-box-tag: shared_links_files + x-box-enable-explorer: true + x-box-sanitized: true + description: Gets the information for a shared link on a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + responses: + '200': + description: Returns the base representation of a file with the additional shared link information. + content: + application/json: + schema: + $ref: '#/components/schemas/File' + examples: + default: + value: + id: '12345' + type: file + etag: '1' + shared_link: + url: 'https://app.box.com/s/kwio6b4ovt1264rnfbyqo1' + download_url: 'https://app.box.com/shared/static/kwio6b4ovt1264rnfbyqo1.pdf' + vanity_url: null + vanity_name: null + effective_access: open + effective_permission: can_download + is_password_enabled: false + unshared_at: '2020-09-21T10:34:41-07:00' + download_count: 0 + preview_count: 0 + access: open + permissions: + can_preview: true + can_download: true + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}#add_shared_link': + put: + operationId: put_files_id#add_shared_link + summary: Add shared link to file + tags: + - Shared links (Files) + x-box-tag: shared_links_files + x-box-enable-explorer: true + x-box-sanitized: true + description: Adds a shared link to a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + shared_link: + description: 'The settings for the shared link to create on the file. Use an empty object (`{}`) to use the default settings for shared links.' + type: object + properties: + access: + type: string + description: 'The level of access for the shared link. This can be restricted to anyone with the link (`open`), only people within the company (`company`) and only those who have been invited to the file (`collaborators`). If not set, this field defaults to the access level specified by the enterprise admin. To create a shared link with this default setting pass the `shared_link` object with no `access` field, for example `{ "shared_link": {} }`. The `company` access level is only available to paid accounts.' + enum: + - open + - company + - collaborators + example: open + password: + type: string + description: The password required to access the shared link. Set the password to `null` to remove it. A password can only be set when `access` is set to `open`. + example: do-not-use-this-password + vanity_name: + type: string + description: 'Defines a custom vanity name to use in the shared link URL, for example `https://app.box.com/v/my-shared-link`. Custom URLs should not be used when sharing sensitive content as vanity URLs are a lot easier to guess than regular shared links.' + example: my-shared-link + unshared_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The timestamp at which this shared link will expire. This field can only be set by users with paid accounts. The value must be greater than the current date and time. + permissions: + type: object + description: The permissions on shared link. + properties: + can_download: + type: boolean + example: true + description: If the shared link allows for downloading of files. This can only be set when `access` is set to `open` or `company`. + responses: + '200': + description: Returns the base representation of a file with a new shared link attached. + content: + application/json: + schema: + $ref: '#/components/schemas/File' + examples: + default: + value: + id: '12345' + type: file + etag: '1' + shared_link: + url: 'https://app.box.com/s/kwio6b4ovt1264rnfbyqo1' + download_url: 'https://app.box.com/shared/static/kwio6b4ovt1264rnfbyqo1.pdf' + vanity_url: null + vanity_name: null + effective_access: open + effective_permission: can_download + is_password_enabled: false + unshared_at: '2020-09-21T10:34:41-07:00' + download_count: 0 + preview_count: 0 + access: open + permissions: + can_preview: true + can_download: true + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file. This indicates that the file has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}#update_shared_link': + put: + operationId: put_files_id#update_shared_link + summary: Update shared link on file + tags: + - Shared links (Files) + x-box-tag: shared_links_files + x-box-enable-explorer: true + x-box-sanitized: true + description: Updates a shared link on a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + shared_link: + description: The settings for the shared link to update. + type: object + properties: + access: + type: string + description: 'The level of access for the shared link. This can be restricted to anyone with the link (`open`), only people within the company (`company`) and only those who have been invited to the folder (`collaborators`). If not set, this field defaults to the access level specified by the enterprise admin. To create a shared link with this default setting pass the `shared_link` object with no `access` field, for example `{ "shared_link": {} }`. The `company` access level is only available to paid accounts.' + enum: + - open + - company + - collaborators + example: open + password: + type: string + description: The password required to access the shared link. Set the password to `null` to remove it. A password can only be set when `access` is set to `open`. + example: do-not-use-this-password + vanity_name: + type: string + description: 'Defines a custom vanity name to use in the shared link URL, for example `https://app.box.com/v/my-shared-link`. Custom URLs should not be used when sharing sensitive content as vanity URLs are a lot easier to guess than regular shared links.' + example: my-shared-link + unshared_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The timestamp at which this shared link will expire. This field can only be set by users with paid accounts. The value must be greater than the current date and time. + permissions: + type: object + description: The permissions on shared link. + properties: + can_download: + type: boolean + example: true + description: If the shared link allows for downloading of files. This can only be set when `access` is set to `open` or `company`. + responses: + '200': + description: 'Returns a basic representation of the file, with the updated shared link attached.' + content: + application/json: + schema: + $ref: '#/components/schemas/File' + examples: + default: + value: + id: '12345' + type: file + etag: '1' + shared_link: + url: 'https://app.box.com/s/kwio6b4ovt1264rnfbyqo1' + download_url: 'https://app.box.com/shared/static/kwio6b4ovt1264rnfbyqo1.pdf' + vanity_url: null + vanity_name: null + effective_access: open + effective_permission: can_download + is_password_enabled: false + unshared_at: '2020-09-21T10:34:41-07:00' + download_count: 0 + preview_count: 0 + access: open + permissions: + can_preview: true + can_download: true + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file. This indicates that the file has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/files/{file_id}#remove_shared_link': + put: + operationId: put_files_id#remove_shared_link + summary: Remove shared link from file + tags: + - Shared links (Files) + x-box-tag: shared_links_files + x-box-enable-explorer: true + x-box-sanitized: true + description: Removes a shared link from a file. + parameters: + - name: file_id + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + shared_link: + description: 'By setting this value to `null`, the shared link is removed from the file.' + type: object + example: null + nullable: true + responses: + '200': + description: 'Returns a basic representation of a file, with the shared link removed.' + content: + application/json: + schema: + $ref: '#/components/schemas/File' + examples: + default: + value: + id: '12345' + type: file + etag: '1' + shared_link: null + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the file is not found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `file_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the file. This indicates that the file has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /shared_items#folders: + get: + operationId: get_shared_items#folders + summary: Find folder for shared link + tags: + - Shared links (Folders) + x-box-tag: shared_links_folders + x-box-enable-explorer: true + description: 'Return the folder represented by a shared link. A shared folder can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared folder when only given a shared link.' + parameters: + - name: if-none-match + description: Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. + in: header + required: false + example: '1' + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: boxapi + description: 'A header containing the shared link and optional password for the shared link. The format for this header is as follows. `shared_link=[link]&shared_link_password=[password]`' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: true + schema: + type: string + responses: + '200': + description: Returns a full folder resource if the shared link is valid and the user has access to it. + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '304': + description: Returns an empty response when the `If-None-Match` header matches the current `etag` value of the folder. This indicates that the folder has not changed since it was last requested. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}#get_shared_link': + get: + operationId: get_folders_id#get_shared_link + summary: Get shared link for folder + tags: + - Shared links (Folders) + x-box-tag: shared_links_folders + x-box-enable-explorer: true + x-box-sanitized: true + description: Gets the information for a shared link on a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + responses: + '200': + description: Returns the base representation of a folder with the additional shared link information. + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + examples: + default: + value: + id: '12345' + type: folder + etag: '1' + shared_link: + url: 'https://app.box.com/s/kwio6b4ovt1264rnfbyqo1' + download_url: 'https://app.box.com/shared/static/kwio6b4ovt1264rnfbyqo1.pdf' + vanity_url: null + vanity_name: null + effective_access: open + effective_permission: can_download + is_password_enabled: false + unshared_at: '2020-09-21T10:34:41-07:00' + download_count: 0 + preview_count: 0 + access: open + permissions: + can_preview: true + can_download: true + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}#add_shared_link': + put: + operationId: put_folders_id#add_shared_link + summary: Add shared link to folder + tags: + - Shared links (Folders) + x-box-tag: shared_links_folders + x-box-enable-explorer: true + x-box-sanitized: true + description: Adds a shared link to a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + shared_link: + description: 'The settings for the shared link to create on the folder. Use an empty object (`{}`) to use the default settings for shared links.' + type: object + properties: + access: + type: string + description: 'The level of access for the shared link. This can be restricted to anyone with the link (`open`), only people within the company (`company`) and only those who have been invited to the folder (`collaborators`). If not set, this field defaults to the access level specified by the enterprise admin. To create a shared link with this default setting pass the `shared_link` object with no `access` field, for example `{ "shared_link": {} }`. The `company` access level is only available to paid accounts.' + enum: + - open + - company + - collaborators + example: open + password: + type: string + description: The password required to access the shared link. Set the password to `null` to remove it. A password can only be set when `access` is set to `open`. + example: do-not-use-this-password + unshared_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The timestamp at which this shared link will expire. This field can only be set by users with paid accounts. The value must be greater than the current date and time. + permissions: + type: object + description: The permissions on shared link. + properties: + can_download: + type: boolean + example: true + description: If the shared link allows for downloading of folders. This can only be set when `access` is set to `open` or `company`. + responses: + '200': + description: Returns the base representation of a folder with a new shared link attached. + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + examples: + default: + value: + id: '12345' + type: folder + etag: '1' + shared_link: + url: 'https://app.box.com/s/kwio6b4ovt1264rnfbyqo1' + download_url: 'https://app.box.com/shared/static/kwio6b4ovt1264rnfbyqo1.pdf' + vanity_url: null + vanity_name: null + effective_access: open + effective_permission: can_download + is_password_enabled: false + unshared_at: '2020-09-21T10:34:41-07:00' + download_count: 0 + preview_count: 0 + access: open + permissions: + can_preview: true + can_download: true + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the folder. This indicates that the folder has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}#update_shared_link': + put: + operationId: put_folders_id#update_shared_link + summary: Update shared link on folder + tags: + - Shared links (Folders) + x-box-tag: shared_links_folders + x-box-enable-explorer: true + x-box-sanitized: true + description: Updates a shared link on a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + shared_link: + description: The settings for the shared link to update. + type: object + properties: + access: + type: string + description: 'The level of access for the shared link. This can be restricted to anyone with the link (`open`), only people within the company (`company`) and only those who have been invited to the folder (`collaborators`). If not set, this field defaults to the access level specified by the enterprise admin. To create a shared link with this default setting pass the `shared_link` object with no `access` field, for example `{ "shared_link": {} }`. The `company` access level is only available to paid accounts.' + enum: + - open + - company + - collaborators + example: open + password: + type: string + description: The password required to access the shared link. Set the password to `null` to remove it. A password can only be set when `access` is set to `open`. + example: do-not-use-this-password + unshared_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The timestamp at which this shared link will expire. This field can only be set by users with paid accounts. The value must be greater than the current date and time. + permissions: + type: object + description: The permissions on shared link. + properties: + can_download: + type: boolean + example: true + description: If the shared link allows for downloading of folders. This can only be set when `access` is set to `open` or `company`. + responses: + '200': + description: 'Returns a basic representation of the folder, with the updated shared link attached.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + examples: + default: + value: + id: '12345' + type: folder + etag: '1' + shared_link: + url: 'https://app.box.com/s/kwio6b4ovt1264rnfbyqo1' + download_url: 'https://app.box.com/shared/static/kwio6b4ovt1264rnfbyqo1.pdf' + vanity_url: null + vanity_name: null + effective_access: open + effective_permission: can_download + is_password_enabled: false + unshared_at: '2020-09-21T10:34:41-07:00' + download_count: 0 + preview_count: 0 + access: open + permissions: + can_preview: true + can_download: true + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the folder. This indicates that the folder has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/folders/{folder_id}#remove_shared_link': + put: + operationId: put_folders_id#remove_shared_link + summary: Remove shared link from folder + tags: + - Shared links (Folders) + x-box-tag: shared_links_folders + x-box-enable-explorer: true + x-box-sanitized: true + description: Removes a shared link from a folder. + parameters: + - name: folder_id + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`.' + example: '12345' + in: path + required: true + schema: + type: string + nullable: false + - name: fields + description: Explicitly request the `shared_link` fields to be returned for this item. + example: shared_link + in: query + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + shared_link: + description: 'By setting this value to `null`, the shared link is removed from the folder.' + type: object + example: null + nullable: true + responses: + '200': + description: 'Returns a basic representation of a folder, with the shared link removed.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + examples: + default: + value: + id: '12345' + type: folder + etag: '1' + shared_link: null + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned if the user does not have all the permissions to complete the update. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returned if the folder is not found, or the user does not have access to the folder.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '405': + description: Returned if the `folder_id` is not in a recognized format. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '412': + description: Returns an error when the `If-Match` header does not match the current `etag` value of the folder. This indicates that the folder has changed since it was last requested. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /web_links: + post: + operationId: post_web_links + summary: Create web link + tags: + - Web links + x-box-tag: web_links + description: Creates a web link object within a folder. + requestBody: + content: + application/json: + schema: + type: object + required: + - parent + - url + properties: + url: + type: string + example: 'https://box.com' + description: 'The URL that this web link links to. Must start with `"http://"` or `"https://"`.' + parent: + type: object + description: The parent folder to create the web link within. + required: + - id + properties: + id: + type: string + description: The ID of parent folder + example: '0' + name: + type: string + example: Box Website + description: Name of the web link. Defaults to the URL if not set. + description: + type: string + example: Cloud Content Management + description: Description of the web link. + responses: + '200': + description: Returns the newly created web link object. + content: + application/json: + schema: + $ref: '#/components/schemas/WebLink' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/web_links/{web_link_id}': + get: + operationId: get_web_links_id + summary: Get web link + tags: + - Web links + x-box-tag: web_links + description: Retrieve information about a web link. + parameters: + - name: web_link_id + description: The ID of the web link. + example: '12345' + in: path + required: true + schema: + type: string + - name: boxapi + description: 'The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item.' + example: 'shared_link=[link]&shared_link_password=[password]' + in: header + required: false + schema: + type: string + responses: + '200': + description: Returns the web link object. + content: + application/json: + schema: + $ref: '#/components/schemas/WebLink' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_web_links_id + summary: Restore web link + tags: + - Trashed web links + x-box-tag: trashed_web_links + description: Restores a web link that has been moved to the trash. An optional new parent ID can be provided to restore the web link to in case the original folder has been deleted. + parameters: + - name: web_link_id + description: The ID of the web link. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + description: An optional new name for the web link. + example: Restored.docx + type: string + parent: + allOf: + - type: object + description: The parent for this item + properties: + id: + type: string + description: The ID of parent item + example: '123' + - description: Specifies an optional ID of a folder to restore the web link to when the original folder no longer exists. Please be aware that this ID will only be used if the original folder no longer exists. Use this ID to provide a fallback location to restore the web link to if the original location has been deleted. + responses: + '201': + description: Returns a web link object when it has been restored. + content: + application/json: + schema: + $ref: '#/components/schemas/WebLink' + '403': + description: 'Returns an error if the user does not have access to the folder the web link is being restored to, or the user does not have permission to restore web link from the trash.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the web link is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: Returns an error if there is an web link with the same name in the folder the web link is being restored to. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_web_links_id + summary: Update web link + tags: + - Web links + x-box-tag: web_links + description: Updates a web link object. + parameters: + - name: web_link_id + description: The ID of the web link. + example: '12345' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + url: + type: string + example: 'https://box.com' + description: 'The new URL that the web link links to. Must start with `"http://"` or `"https://"`.' + parent: + allOf: + - type: object + description: The parent for this item + properties: + id: + type: string + description: The ID of parent item + example: '123' + - description: The new parent folder to put the web link in. Use this to move the web link to a different folder. + name: + type: string + example: Box Website + description: A new name for the web link. Defaults to the URL if not set. + description: + type: string + example: Cloud Content Management + description: A new description of the web link. + responses: + '200': + description: Returns the updated web link object. + content: + application/json: + schema: + $ref: '#/components/schemas/WebLink' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_web_links_id + summary: Remove web link + tags: + - Web links + x-box-tag: web_links + description: Deletes a web link. + parameters: + - name: web_link_id + description: The ID of the web link. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: An empty response will be returned when the web link was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/web_links/{web_link_id}/trash': + get: + operationId: get_web_links_id_trash + summary: Get trashed web link + tags: + - Trashed web links + x-box-tag: trashed_web_links + description: Retrieves a web link that has been moved to the trash. + parameters: + - name: web_link_id + description: The ID of the web link. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: 'Returns the web link that was trashed, including information about when the it was moved to the trash.' + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + '404': + description: Returns an error if the web link is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_web_links_id_trash + summary: Permanently remove web link + tags: + - Trashed web links + x-box-tag: trashed_web_links + description: Permanently deletes a web link that is in the trash. This action cannot be undone. + parameters: + - name: web_link_id + description: The ID of the web link. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the web link was permanently deleted. + '404': + description: Returns an error if the web link is not in the trash. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /users: + get: + operationId: get_users + x-box-tag: users + summary: List enterprise users + tags: + - Users + description: 'Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`. The application and the authenticated user need to have the permission to look up users in the entire enterprise.' + parameters: + - name: filter_term + description: 'Limits the results to only users who''s `name` or `login` start with the search term. For externally managed users, the search term needs to completely match the in order to find the user, and it will only return one user at a time.' + in: query + required: false + example: john + schema: + type: string + - name: user_type + description: 'Limits the results to the kind of user specified. * `all` returns every kind of user for whom the `login` or `name` partially matches the `filter_term`. It will only return an external user if the login matches the `filter_term` completely, and in that case it will only return that user. * `managed` returns all managed and app users for whom the `login` or `name` partially matches the `filter_term`. * `external` returns all external users for whom the `login` matches the `filter_term` exactly.' + in: query + required: false + example: managed + schema: + type: string + enum: + - all + - managed + - external + - name: external_app_user_id + in: query + required: false + schema: + type: string + example: my-user-1234 + description: 'Limits the results to app users with the given `external_app_user_id` value. When creating an app user, an `external_app_user_id` value can be set. This value can then be used in this endpoint to find any users that match that `external_app_user_id` value.' + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: usemarker + description: 'Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response.' + in: query + required: false + example: true + schema: + type: boolean + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + responses: + '200': + description: Returns all of the users in the enterprise. + content: + application/json: + schema: + $ref: '#/components/schemas/Users' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_users + summary: Create user + tags: + - Users + x-box-tag: users + description: Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - name + properties: + name: + type: string + description: The name of the user + example: Aaron Levie + maxLength: 50 + login: + type: string + description: 'The email address the user uses to log in Required, unless `is_platform_access_only` is set to `true`.' + example: boss@box.com + is_platform_access_only: + type: boolean + example: true + description: Specifies that the user is an app user. + role: + type: string + enum: + - coadmin + - user + description: The user’s enterprise role + example: user + language: + type: string + description: 'The language of the user, formatted in modified version of the [ISO 639-1](/guides/api-calls/language-codes) format.' + example: en + is_sync_enabled: + type: boolean + description: Whether the user can use Box Sync + example: true + job_title: + type: string + description: The user’s job title + maxLength: 100 + example: CEO + phone: + type: string + description: The user’s phone number + maxLength: 100 + example: '6509241374' + address: + type: string + description: The user’s address + maxLength: 255 + example: '900 Jefferson Ave, Redwood City, CA 94063' + space_amount: + type: integer + format: int64 + description: The user’s total available space in bytes. Set this to `-1` to indicate unlimited storage. + example: 11345156112 + tracking_codes: + type: array + description: Tracking codes allow an admin to generate reports from the admin console and assign an attribute to a specific group of users. This setting must be enabled for an enterprise before it can be used. + example: + - 'code1: 12345' + items: + type: string + can_see_managed_users: + type: boolean + example: true + description: Whether the user can see other enterprise users in their contact list + timezone: + type: string + format: timezone + description: The user's timezone + example: Africa/Bujumbura + is_external_collab_restricted: + type: boolean + example: true + description: Whether the user is allowed to collaborate with users outside their enterprise + is_exempt_from_device_limits: + type: boolean + example: true + description: Whether to exempt the user from enterprise device limits + is_exempt_from_login_verification: + type: boolean + example: true + description: Whether the user must use two-factor authentication + status: + type: string + enum: + - active + - inactive + - cannot_delete_edit + - cannot_delete_edit_upload + description: The user's account status + example: active + external_app_user_id: + type: string + example: my-user-1234 + description: 'An external identifier for an app user, which can be used to look up the user. This can be used to tie user IDs from external identity providers to Box users.' + responses: + '201': + description: Returns a user object for the newly created user. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /users/me: + get: + operationId: get_users_me + x-box-tag: users + summary: Get current user + tags: + - Users + description: 'Retrieves information about the user who is currently authenticated. In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of.' + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns a single user object. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/users/{user_id}': + get: + operationId: get_users_id + x-box-tag: users + summary: Get user + tags: + - Users + description: 'Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead.' + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: 'Returns a single user object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields using the [fields](#get-users-id--request--fields) parameter.' + content: + application/json: + schema: + $ref: '#/components/schemas/User' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_users_id + summary: Update user + tags: + - Users + x-box-tag: users + x-box-enable-explorer: true + description: Updates a managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + enterprise: + type: string + nullable: true + example: null + description: Set this to `null` to roll the user out of the enterprise and make them a free user + notify: + type: boolean + example: true + description: Whether the user should receive an email when they are rolled out of an enterprise + name: + type: string + description: The name of the user + example: Aaron Levie + maxLength: 50 + login: + type: string + description: The email address the user uses to log in + example: boss@box.com + role: + type: string + enum: + - coadmin + - user + description: The user’s enterprise role + example: user + language: + type: string + description: 'The language of the user, formatted in modified version of the [ISO 639-1](/guides/api-calls/language-codes) format.' + example: en + is_sync_enabled: + type: boolean + description: Whether the user can use Box Sync + example: true + job_title: + type: string + description: The user’s job title + maxLength: 100 + example: CEO + phone: + type: string + description: The user’s phone number + maxLength: 100 + example: '6509241374' + address: + type: string + description: The user’s address + maxLength: 255 + example: '900 Jefferson Ave, Redwood City, CA 94063' + tracking_codes: + type: array + description: Tracking codes allow an admin to generate reports from the admin console and assign an attribute to a specific group of users. This setting must be enabled for an enterprise before it can be used. + example: + - 'code1: 12345' + items: + type: string + can_see_managed_users: + type: boolean + example: true + description: Whether the user can see other enterprise users in their contact list + timezone: + type: string + format: timezone + description: The user's timezone + example: Africa/Bujumbura + is_external_collab_restricted: + type: boolean + example: true + description: Whether the user is allowed to collaborate with users outside their enterprise + is_exempt_from_device_limits: + type: boolean + example: true + description: Whether to exempt the user from enterprise device limits + is_exempt_from_login_verification: + type: boolean + example: true + description: Whether the user must use two-factor authentication + is_password_reset_required: + type: boolean + example: true + description: Whether the user is required to reset their password + status: + type: string + enum: + - active + - inactive + - cannot_delete_edit + - cannot_delete_edit_upload + description: The user's account status + example: active + space_amount: + type: integer + format: int64 + description: The user’s total available space in bytes. Set this to `-1` to indicate unlimited storage. + example: 11345156112 + notification_email: + type: object + nullable: true + description: 'An alternate notification email address to which email notifications are sent. When it''s confirmed, this will be the email address to which notifications are sent instead of to the primary email address. Set this value to `null` to remove the notification email.' + properties: + email: + type: string + example: notifications@example.com + description: The email address to send the notifications to. + responses: + '200': + description: Returns the updated user object. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: 'Returns an error if some of the parameters are missing or not valid. * `invalid_parameter` when a parameter is formatted incorrectly, for example when the `notification_email` has an incorrectly formatted email address.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: 'Returns an error if the user is not allowed to make the changes. * `access_denied_insufficient_permissions` when the user does not have the right permissions, for example when updating the notification email is turned off for the enterprise.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_users_id + x-box-tag: users + summary: Delete user + tags: + - Users + description: 'Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files.' + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + - name: notify + schema: + type: boolean + in: query + example: true + description: Whether the user will receive email notification of the deletion + - name: force + schema: + type: boolean + in: query + example: true + description: Whether the user should be deleted even if this user still own files + responses: + '204': + content: {} + description: Removes the user and returns an empty response. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/users/{user_id}/avatar': + get: + operationId: get_users_id_avatar + x-box-tag: avatars + summary: Get user avatar + tags: + - User avatars + description: Retrieves an image of a the user's avatar. + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: When an avatar can be found for the user the image data will be returned in the body of the response. + content: + image/jpg: + schema: + type: string + format: binary + description: The avatar + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/users/{user_id}/folders/0': + put: + operationId: put_users_id_folders_0 + x-box-tag: transfer + summary: Transfer owned folders + tags: + - Transfer folders + description: 'Move all of the items (files, folders and workflows) owned by a user into another user''s account Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. All existing shared links and folder-level collaborations are transferred during the operation. Please note that while collaborations at the individual file-level are transferred during the operation, the collaborations are deleted when the original user is deleted. This call will be performed synchronously which might lead to a slow response when the source user has a large number of items in all of its folders. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. The destination folder''s name will be in the format `{User}''s Files and Folders`, where `{User}` is the display name of the user. To make this API call your application will need to have the "Read and write all files and folders stored in Box" scope enabled. Please make sure the destination user has access to `Relay` or `Relay Lite`, and has access to the files and folders involved in the workflows being transferred. Admins will receive an email when the operation is completed.' + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: notify + description: Determines if users should receive email notification for the action performed. + in: query + required: false + example: true + schema: + type: boolean + requestBody: + content: + application/json: + schema: + type: object + required: + - owned_by + properties: + owned_by: + type: object + description: The user who the folder will be transferred to + required: + - id + properties: + id: + type: string + example: '1232234' + description: The ID of the user who the folder will be transferred to + responses: + '200': + description: Returns the information for the newly created destination folder. + content: + application/json: + schema: + $ref: '#/components/schemas/Folder' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/users/{user_id}/email_aliases': + get: + operationId: get_users_id_email_aliases + summary: List user's email aliases + tags: + - Email aliases + x-box-tag: email_aliases + description: Retrieves all email aliases for a user. The collection does not include the primary login for the user. + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a collection of email aliases. + content: + application/json: + schema: + $ref: '#/components/schemas/EmailAliases' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_users_id_email_aliases + x-box-tag: email_aliases + summary: Create email alias + tags: + - Email aliases + description: Adds a new email alias to a user account.. + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - email + properties: + email: + type: string + example: alias@example.com + description: The email address to add to the account as an alias. + responses: + '201': + description: Returns the newly created email alias object. + content: + application/json: + schema: + $ref: '#/components/schemas/EmailAlias' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/users/{user_id}/email_aliases/{email_alias_id}': + delete: + operationId: delete_users_id_email_aliases_id + x-box-tag: email_aliases + summary: Remove email alias + tags: + - Email aliases + description: Removes an email alias from a user. + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + - name: email_alias_id + description: The ID of the email alias. + example: '23432' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Removes the alias and returns an empty response. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/users/{user_id}/memberships': + get: + operationId: get_users_id_memberships + summary: List user's groups + x-box-tag: memberships + tags: + - Group memberships + description: Retrieves all the groups for a user. Only members of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: user_id + description: The ID of the user. + example: '12345' + in: path + required: true + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + responses: + '200': + description: 'Returns a collection of membership objects. If there are no memberships, an empty collection will be returned.' + content: + application/json: + schema: + $ref: '#/components/schemas/GroupMemberships' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /invites: + post: + operationId: post_invites + summary: Create user invite + tags: + - Invites + x-box-tag: invites + description: 'Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console.' + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - enterprise + - actionable_by + properties: + enterprise: + type: object + description: The enterprise to invite the user to + required: + - id + properties: + id: + type: string + example: '1232234' + description: The ID of the enterprise + actionable_by: + type: object + description: The user to invite + required: + - id + properties: + login: + type: string + example: john@example.com + description: The login of the invited user + responses: + '200': + description: Returns a new invite object. + content: + application/json: + schema: + $ref: '#/components/schemas/Invite' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/invites/{invite_id}': + get: + operationId: get_invites_id + summary: Get user invite status + tags: + - Invites + description: Returns the status of a user invite. + x-box-tag: invites + parameters: + - name: invite_id + description: The ID of an invite. + example: '213723' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns an invite object + content: + application/json: + schema: + $ref: '#/components/schemas/Invite' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /groups: + get: + operationId: get_groups + summary: List groups for enterprise + x-box-tag: groups + tags: + - Groups + description: Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. + parameters: + - name: filter_term + description: Limits the results to only groups whose `name` starts with the search term. + in: query + required: false + example: Engineering + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + responses: + '200': + description: 'Returns a collection of group objects. If there are no groups, an empty collection will be returned.' + content: + application/json: + schema: + $ref: '#/components/schemas/Groups' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_groups + summary: Create group + tags: + - Groups + x-box-tag: groups + description: Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - name + properties: + name: + type: string + example: Customer Support + description: The name of the new group to be created. This name must be unique within the enterprise. + provenance: + type: string + description: 'Keeps track of which external source this group is coming, for example `Active Directory`, or `Okta`. Setting this will also prevent Box admins from editing the group name and its members directly via the Box web application. This is desirable for one-way syncing of groups.' + maxLength: 255 + example: Active Directory + external_sync_identifier: + type: string + description: An arbitrary identifier that can be used by external group sync tools to link this Box Group to an external group. Example values of this field could be an **Active Directory Object ID** or a **Google Group ID**. We recommend you use of this field in order to avoid issues when group names are updated in either Box or external systems. + example: 'AD:123456' + description: + type: string + description: A human readable description of the group. + maxLength: 255 + example: '"Customer Support Group - as imported from Active Directory"' + invitability_level: + type: string + example: admins_only + description: 'Specifies who can invite the group to collaborate on folders. When set to `admins_only` the enterprise admin, co-admins, and the group''s admin can invite the group. When set to `admins_and_members` all the admins listed above and group members can invite the group. When set to `all_managed_users` all managed users in the enterprise can invite the group.' + enum: + - admins_only + - admins_and_members + - all_managed_users + member_viewability_level: + type: string + example: admins_only + description: 'Specifies who can see the members of the group. * `admins_only` - the enterprise admin, co-admins, group''s group admin * `admins_and_members` - all admins and group members * `all_managed_users` - all managed users in the enterprise' + enum: + - admins_only + - admins_and_members + - all_managed_users + responses: + '201': + description: Returns the new group object. + content: + application/json: + schema: + $ref: '#/components/schemas/Group' + '409': + description: 'Returns an error a conflict is stopping the group from being created. * `invalid_parameter`: Often returned if the group name is not unique in the enterprise.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/groups/{group_id}': + get: + operationId: get_groups_id + summary: Get group + tags: + - Groups + x-box-tag: groups + description: Retrieves information about a group. Only members of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: group_id + description: The ID of the group. + example: '57645' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns the group object + content: + application/json: + schema: + $ref: '#/components/schemas/Group' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_groups_id + summary: Update group + tags: + - Groups + x-box-tag: groups + description: Updates a specific group. Only admins of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: group_id + description: The ID of the group. + example: '57645' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + name: + type: string + example: Customer Support + description: The name of the new group to be created. Must be unique within the enterprise. + provenance: + type: string + description: 'Keeps track of which external source this group is coming, for example `Active Directory`, or `Okta`. Setting this will also prevent Box admins from editing the group name and its members directly via the Box web application. This is desirable for one-way syncing of groups.' + maxLength: 255 + example: Active Directory + external_sync_identifier: + type: string + description: An arbitrary identifier that can be used by external group sync tools to link this Box Group to an external group. Example values of this field could be an **Active Directory Object ID** or a **Google Group ID**. We recommend you use of this field in order to avoid issues when group names are updated in either Box or external systems. + example: 'AD:123456' + description: + type: string + description: A human readable description of the group. + maxLength: 255 + example: '"Customer Support Group - as imported from Active Directory"' + invitability_level: + type: string + example: admins_only + description: 'Specifies who can invite the group to collaborate on folders. When set to `admins_only` the enterprise admin, co-admins, and the group''s admin can invite the group. When set to `admins_and_members` all the admins listed above and group members can invite the group. When set to `all_managed_users` all managed users in the enterprise can invite the group.' + enum: + - admins_only + - admins_and_members + - all_managed_users + member_viewability_level: + type: string + example: admins_only + description: 'Specifies who can see the members of the group. * `admins_only` - the enterprise admin, co-admins, group''s group admin * `admins_and_members` - all admins and group members * `all_managed_users` - all managed users in the enterprise' + enum: + - admins_only + - admins_and_members + - all_managed_users + responses: + '200': + description: Returns the updated group object. + content: + application/json: + schema: + $ref: '#/components/schemas/Group' + '409': + description: 'Returns an error a conflict is stopping the group from being created. * `invalid_parameter`: Often returned if the group name is not unique in the enterprise.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_groups_id + summary: Remove group + tags: + - Groups + x-box-tag: groups + description: Permanently deletes a group. Only users with admin-level permissions will be able to use this API. + parameters: + - name: group_id + description: The ID of the group. + example: '57645' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: A blank response is returned if the group was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/groups/{group_id}/memberships': + get: + operationId: get_groups_id_memberships + summary: List members of group + x-box-tag: memberships + tags: + - Group memberships + description: Retrieves all the members for a group. Only members of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: group_id + description: The ID of the group. + example: '57645' + in: path + required: true + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + responses: + '200': + description: 'Returns a collection of membership objects. If there are no memberships, an empty collection will be returned.' + content: + application/json: + schema: + $ref: '#/components/schemas/GroupMemberships' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/groups/{group_id}/collaborations': + get: + operationId: get_groups_id_collaborations + summary: List group collaborations + x-box-tag: list_collaborations + tags: + - Collaborations (List) + description: Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. + parameters: + - name: group_id + description: The ID of the group. + example: '57645' + in: path + required: true + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + responses: + '200': + description: 'Returns a collection of collaboration objects. If there are no collaborations, an empty collection will be returned.' + content: + application/json: + schema: + $ref: '#/components/schemas/Collaborations' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /group_memberships: + post: + operationId: post_group_memberships + summary: Add user to group + tags: + - Group memberships + x-box-tag: memberships + description: Creates a group membership. Only users with admin-level permissions will be able to use this API. + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - user + - group + properties: + user: + type: object + description: The user to add to the group. + required: + - id + properties: + id: + type: string + description: The ID of the user to add to the group + example: '1434325' + group: + type: object + description: The group to add the user to. + required: + - id + properties: + id: + type: string + description: The ID of the group to add the user to + example: '4545523' + role: + type: string + example: member + description: The role of the user in the group. + enum: + - member + - admin + configurable_permissions: + type: object + example: + can_run_reports: true + description: 'Custom configuration for the permissions an admin if a group will receive. This option has no effect on members with a role of `member`. Setting these permissions overwrites the default access levels of an admin. Specifying a value of "null" for this object will disable all configurable permissions. Specifying permissions will set them accordingly, omitted permissions will be enabled by default.' + additionalProperties: + type: boolean + description: A key value pair of custom permissions. + example: true + x-box-example-key: can_run_reports + responses: + '201': + description: Returns a new group membership object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupMembership' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/group_memberships/{group_membership_id}': + get: + operationId: get_group_memberships_id + summary: Get group membership + tags: + - Group memberships + x-box-tag: memberships + description: Retrieves a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: group_membership_id + description: The ID of the group membership. + example: '434534' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns the group membership object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupMembership' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_group_memberships_id + summary: Update group membership + tags: + - Group memberships + x-box-tag: memberships + description: Updates a user's group membership. Only admins of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: group_membership_id + description: The ID of the group membership. + example: '434534' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + role: + type: string + example: member + description: The role of the user in the group. + enum: + - member + - admin + configurable_permissions: + type: object + example: + can_run_reports: true + description: 'Custom configuration for the permissions an admin if a group will receive. This option has no effect on members with a role of `member`. Setting these permissions overwrites the default access levels of an admin. Specifying a value of "null" for this object will disable all configurable permissions. Specifying permissions will set them accordingly, omitted permissions will be enabled by default.' + additionalProperties: + type: boolean + description: A key value pair of custom permissions. + example: true + x-box-example-key: can_run_reports + responses: + '200': + description: Returns a new group membership object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupMembership' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_group_memberships_id + summary: Remove user from group + tags: + - Group memberships + x-box-tag: memberships + description: Deletes a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. + parameters: + - name: group_membership_id + description: The ID of the group membership. + example: '434534' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: A blank response is returned if the membership was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /webhooks: + get: + operationId: get_webhooks + summary: List all webhooks + tags: + - Webhooks + x-box-tag: webhooks + description: 'Returns all defined webhooks for the requesting application. This API only returns webhooks that are applied to files or folders that are owned by the authenticated user. This means that an admin can not see webhooks created by a service account unless the admin has access to those folders, and vice versa.' + parameters: + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a list of webhooks. + content: + application/json: + schema: + $ref: '#/components/schemas/Webhooks' + '403': + description: Returns an error if the application does not have the permission to manage webhooks. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_webhooks + summary: Create webhook + tags: + - Webhooks + x-box-tag: webhooks + description: Creates a webhook. + requestBody: + content: + application/json: + schema: + type: object + required: + - target + - triggers + - address + properties: + target: + type: object + description: The item that will trigger the webhook + properties: + id: + description: The ID of the item to trigger a webhook + type: string + example: '1231232' + type: + description: The type of item to trigger a webhook + type: string + example: file + enum: + - file + - folder + address: + type: string + example: 'https://example.com/webhooks' + description: The URL that is notified by this webhook + triggers: + type: array + example: + - FILE.UPLOADED + description: An array of event names that this webhook is to be triggered for + items: + title: Webhook Trigger + example: FILE.UPLOADED + type: string + description: The event name that triggered this webhook + enum: + - FILE.UPLOADED + - FILE.PREVIEWED + - FILE.DOWNLOADED + - FILE.TRASHED + - FILE.DELETED + - FILE.RESTORED + - FILE.COPIED + - FILE.MOVED + - FILE.LOCKED + - FILE.UNLOCKED + - FILE.RENAMED + - COMMENT.CREATED + - COMMENT.UPDATED + - COMMENT.DELETED + - TASK_ASSIGNMENT.CREATED + - TASK_ASSIGNMENT.UPDATED + - METADATA_INSTANCE.CREATED + - METADATA_INSTANCE.UPDATED + - METADATA_INSTANCE.DELETED + - FOLDER.CREATED + - FOLDER.RENAMED + - FOLDER.DOWNLOADED + - FOLDER.RESTORED + - FOLDER.DELETED + - FOLDER.COPIED + - FOLDER.MOVED + - FOLDER.TRASHED + - WEBHOOK.DELETED + - COLLABORATION.CREATED + - COLLABORATION.ACCEPTED + - COLLABORATION.REJECTED + - COLLABORATION.REMOVED + - COLLABORATION.UPDATED + - SHARED_LINK.DELETED + - SHARED_LINK.CREATED + - SHARED_LINK.UPDATED + responses: + '201': + description: Returns the new webhook object. + content: + application/json: + schema: + $ref: '#/components/schemas/Webhook' + '400': + description: Returns an error if the parameters were incorrect. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returns an error if the application does not have the permission to manage webhooks. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the target item could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: 'Returns an error if the a webhook for this combination of target, application, and user already exists.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/webhooks/{webhook_id}': + get: + operationId: get_webhooks_id + tags: + - Webhooks + x-box-tag: webhooks + summary: Get webhook + description: Retrieves a specific webhook + parameters: + - name: webhook_id + description: The ID of the webhook. + example: '3321123' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a webhook object + content: + application/json: + schema: + $ref: '#/components/schemas/Webhook' + '403': + description: Returns an error if the application does not have the permission to manage webhooks. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the webhook could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_webhooks_id + summary: Update webhook + tags: + - Webhooks + x-box-tag: webhooks + description: Updates a webhook. + parameters: + - name: webhook_id + description: The ID of the webhook. + example: '3321123' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + target: + type: object + description: The item that will trigger the webhook + properties: + id: + description: The ID of the item to trigger a webhook + type: string + example: '1231232' + type: + description: The type of item to trigger a webhook + type: string + example: file + enum: + - file + - folder + address: + type: string + example: 'https://example.com/webhooks' + description: The URL that is notified by this webhook + triggers: + type: array + example: + - FILE.UPLOADED + description: An array of event names that this webhook is to be triggered for + items: + title: Webhook Trigger + example: FILE.UPLOADED + type: string + description: The event name that triggered this webhook + enum: + - FILE.UPLOADED + - FILE.PREVIEWED + - FILE.DOWNLOADED + - FILE.TRASHED + - FILE.DELETED + - FILE.RESTORED + - FILE.COPIED + - FILE.MOVED + - FILE.LOCKED + - FILE.UNLOCKED + - FILE.RENAMED + - COMMENT.CREATED + - COMMENT.UPDATED + - COMMENT.DELETED + - TASK_ASSIGNMENT.CREATED + - TASK_ASSIGNMENT.UPDATED + - METADATA_INSTANCE.CREATED + - METADATA_INSTANCE.UPDATED + - METADATA_INSTANCE.DELETED + - FOLDER.CREATED + - FOLDER.RENAMED + - FOLDER.DOWNLOADED + - FOLDER.RESTORED + - FOLDER.DELETED + - FOLDER.COPIED + - FOLDER.MOVED + - FOLDER.TRASHED + - WEBHOOK.DELETED + - COLLABORATION.CREATED + - COLLABORATION.ACCEPTED + - COLLABORATION.REJECTED + - COLLABORATION.REMOVED + - COLLABORATION.UPDATED + - SHARED_LINK.DELETED + - SHARED_LINK.CREATED + - SHARED_LINK.UPDATED + responses: + '200': + description: Returns the new webhook object. + content: + application/json: + schema: + $ref: '#/components/schemas/Webhook' + '400': + description: Returns an error if the parameters were incorrect. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returns an error if the application does not have the permission to manage webhooks. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the target item or webhook could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: 'Returns an error if the a webhook for this combination of target, application, and user already exists.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_webhooks_id + summary: Remove webhook + tags: + - Webhooks + x-box-tag: webhooks + description: Deletes a webhook. + parameters: + - name: webhook_id + description: The ID of the webhook. + example: '3321123' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: An empty response will be returned when the webhook was successfully deleted. + '403': + description: Returns an error if the application does not have the permission to manage webhooks. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if the webhook could not be found + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/skill_invocations/{skill_id}': + put: + operationId: put_skill_invocations_id + summary: Update all Box Skill cards on file + tags: + - Skills + x-box-tag: skills + description: An alternative method that can be used to overwrite and update all Box Skill metadata cards on a file. + parameters: + - name: skill_id + description: The ID of the skill to apply this metadata for. + example: '33243242' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - status + - metadata + - file + properties: + status: + type: string + description: Defines the status of this invocation. Set this to `success` when setting Skill cards. + example: success + enum: + - invoked + - processing + - success + - transient_failure + - permanent_failure + metadata: + type: object + description: The metadata to set for this skill. This is a list of Box Skills cards. These cards will overwrite any existing Box skill cards on the file. + properties: + cards: + type: array + description: A list of Box Skill cards to apply to this file. + items: + oneOf: + - $ref: '#/components/schemas/SkillCard' + - $ref: '#/components/schemas/KeywordSkillCard' + - $ref: '#/components/schemas/TimelineSkillCard' + - $ref: '#/components/schemas/TranscriptSkillCard' + - $ref: '#/components/schemas/StatusSkillCard' + file: + type: object + description: The file to assign the cards to. + properties: + type: + type: string + description: '`file`' + example: file + enum: + - file + id: + type: string + description: The ID of the file + example: '3243244' + file_version: + type: object + description: The optional file version to assign the cards to. + properties: + type: + type: string + description: '`file_version`' + example: file_version + enum: + - file_version + id: + type: string + description: The ID of the file version + example: '731381601045' + usage: + type: object + description: 'A descriptor that defines what items are affected by this call. Set this to the default values when setting a card to a `success` state, and leave it out in most other situations.' + properties: + unit: + type: string + example: file + description: '`file`' + value: + type: number + example: 1 + description: '`1`' + responses: + '200': + content: {} + description: Returns an empty response when the card has been successfully updated. + '400': + description: 'Returns an error when the request body is not valid. * `schema_validation_failed` - The request body contains a value for a for a field that either does not exist, or for which the value or type does not match the expected field type. An example might be an unknown option for an `enum` or `multiSelect` field.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error when the file could not be found or the user does not have access. * `not_found` - The file could not be found, or the user does not have access to the file.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /events: + options: + operationId: options_events + summary: Get events long poll endpoint + tags: + - Events + x-box-tag: events + description: 'Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it only serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first.' + responses: + '200': + description: Returns a paginated array of servers that can be used instead of the regular endpoints for long-polling events. + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeServers' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + get: + operationId: get_events + summary: List user and enterprise events + tags: + - Events + x-box-tag: events + description: 'Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs`. The user making the API call will need to have admin privileges, and the application will need to have the permission to access the event feed to get the enterprise event feed.' + parameters: + - name: stream_type + description: Defines the type of events that are returned * `all` returns everything for a user and is the default * `changes` returns events that may cause file tree changes such as file updates or collaborations. * `sync` is similar to `changes` but only applies to synced folders * `admin_logs` returns all events for an entire enterprise and requires the user making the API call to have admin permissions. + in: query + example: all + schema: + type: string + default: all + enum: + - all + - changes + - sync + - admin_logs + - name: stream_position + description: The location in the event stream to start receiving events from. * `now` will return an empty list events and the latest stream position for initialization. * `0` or `null` will return all events. + example: '1348790499819' + in: query + schema: + type: string + - name: limit + description: Limits the number of events returned + in: query + example: 50 + schema: + type: integer + format: int64 + default: 100 + maximum: 500 + - name: event_type + description: A comma-separated list of events to filter by. This can only be used when requesting the events with a `stream_type` of `admin_logs`. For any other `stream_type` this value will be ignored. + in: query + explode: false + example: + - ACCESS_GRANTED + schema: + type: array + items: + type: string + description: An event type that can be filtered by + enum: + - ACCESS_GRANTED + - ACCESS_REVOKED + - ADD_DEVICE_ASSOCIATION + - ADD_LOGIN_ACTIVITY_DEVICE + - ADMIN_LOGIN + - APPLICATION_CREATED + - APPLICATION_PUBLIC_KEY_ADDED + - APPLICATION_PUBLIC_KEY_DELETED + - CHANGE_ADMIN_ROLE + - CHANGE_FOLDER_PERMISSION + - COLLABORATION_ACCEPT + - COLLABORATION_EXPIRATION + - COLLABORATION_INVITE + - COLLABORATION_REMOVE + - COLLABORATION_ROLE_CHANGE + - COMMENT_CREATE + - COMMENT_DELETE + - CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY + - CONTENT_WORKFLOW_AUTOMATION_ADD + - CONTENT_WORKFLOW_AUTOMATION_DELETE + - CONTENT_WORKFLOW_POLICY_ADD + - CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION + - CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION + - COPY + - DATA_RETENTION_CREATE_RETENTION + - DATA_RETENTION_REMOVE_RETENTION + - DELETE + - DELETE_USER + - DEVICE_TRUST_CHECK_FAILED + - DOWNLOAD + - EDIT + - EDIT_USER + - EMAIL_ALIAS_CONFIRM + - EMAIL_ALIAS_REMOVE + - ENTERPRISE_APP_AUTHORIZATION_UPDATE + - EXTERNAL_COLLAB_SECURITY_SETTINGS + - FAILED_LOGIN + - FILE_MARKED_MALICIOUS + - FILE_WATERMARKED_DOWNLOAD + - GROUP_ADD_ITEM + - GROUP_ADD_USER + - GROUP_CREATION + - GROUP_DELETION + - GROUP_EDITED + - GROUP_REMOVE_ITEM + - GROUP_REMOVE_USER + - ITEM_MODIFY + - ITEM_OPEN + - ITEM_SHARED_UPDATE + - ITEM_SYNC + - ITEM_UNSYNC + - LEGAL_HOLD_ASSIGNMENT_CREATE + - LEGAL_HOLD_ASSIGNMENT_DELETE + - LEGAL_HOLD_POLICY_CREATE + - LEGAL_HOLD_POLICY_DELETE + - LEGAL_HOLD_POLICY_UPDATE + - LOCK + - LOGIN + - METADATA_INSTANCE_CREATE + - METADATA_INSTANCE_DELETE + - METADATA_INSTANCE_UPDATE + - METADATA_TEMPLATE_CREATE + - METADATA_TEMPLATE_DELETE + - METADATA_TEMPLATE_UPDATE + - MOVE + - NEW_USER + - OAUTH2_ACCESS_TOKEN_REVOKE + - PREVIEW + - REMOVE_DEVICE_ASSOCIATION + - REMOVE_LOGIN_ACTIVITY_DEVICE + - RENAME + - RETENTION_POLICY_ASSIGNMENT_ADD + - SHARE + - SHARE_EXPIRATION + - SHIELD_ALERT + - STORAGE_EXPIRATION + - TASK_ASSIGNMENT_CREATE + - TASK_ASSIGNMENT_DELETE + - TASK_ASSIGNMENT_UPDATE + - TASK_CREATE + - TASK_UPDATE + - TERMS_OF_SERVICE_ACCEPT + - TERMS_OF_SERVICE_REJECT + - UNDELETE + - UNLOCK + - UNSHARE + - UPDATE_COLLABORATION_EXPIRATION + - UPDATE_SHARE_EXPIRATION + - UPLOAD + - USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE + - WATERMARK_LABEL_CREATE + - WATERMARK_LABEL_DELETE + - name: created_after + description: The lower bound date and time to return events for. This can only be used when requesting the events with a `stream_type` of `admin_logs`. For any other `stream_type` this value will be ignored. + in: query + example: '2012-12-12T10:53:43-08:00' + schema: + type: string + format: date-time + - name: created_before + description: The upper bound date and time to return events for. This can only be used when requesting the events with a `stream_type` of `admin_logs`. For any other `stream_type` this value will be ignored. + in: query + required: false + example: '2013-12-12T10:53:43-08:00' + schema: + type: string + format: date-time + responses: + '200': + description: 'Returns a list of event objects. Events objects are returned in pages, with each page (chunk) including a list of event objects. The response includes a `chunk_size` parameter indicating how many events were returned in this chunk, as well as the next `stream_position` that can be queried.' + content: + application/json: + schema: + $ref: '#/components/schemas/Events' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /collections: + get: + operationId: get_collections + summary: List all collections + tags: + - Collections + x-box-tag: collections + description: 'Retrieves all collections for a given user. Currently, only the `favorites` collection is supported.' + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns all collections for the given user + content: + application/json: + schema: + $ref: '#/components/schemas/Collections' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/collections/{collection_id}/items': + get: + operationId: get_collections_id_items + summary: List collection items + tags: + - Collections + x-box-tag: collections + description: Retrieves the files and/or folders contained within this collection. + parameters: + - name: collection_id + description: The ID of the collection. + example: '926489' + in: path + required: true + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: offset + description: The offset of the item at which to begin the response. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + default: 0 + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns an array of items in the collection. + content: + application/json: + schema: + $ref: '#/components/schemas/Items' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /recent_items: + get: + operationId: get_recent_items + summary: List recently accessed items + tags: + - Recent items + description: 'Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed.' + x-box-tag: recent_items + x-box-enable-explorer: true + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + responses: + '200': + description: Returns a list recent items access by a user. + content: + application/json: + schema: + $ref: '#/components/schemas/RecentItems' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /retention_policies: + get: + operationId: get_retention_policies + summary: List retention policies + tags: + - Retention policies + x-box-tag: retention_policies + description: Retrieves all of the retention policies for an enterprise. + parameters: + - name: policy_name + description: Filters results by a case sensitive prefix of the name of retention policies. + in: query + required: false + example: Sales Policy + schema: + type: string + - name: policy_type + description: Filters results by the type of retention policy. + in: query + required: false + example: finite + schema: + type: string + enum: + - finite + - indefinite + - name: created_by_user_id + description: Filters results by the ID of the user who created policy. + example: '21312321' + in: query + required: false + schema: + type: string + responses: + '200': + description: Returns a list retention policies in the enterprise. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicies' + '400': + description: Returns a `bad_request` if a non existent `policy_type` was specified. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns a `not_found` error if the user specified in `created_by_user_id` does not exist. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_retention_policies + summary: Create retention policy + tags: + - Retention policies + x-box-tag: retention_policies + description: Creates a retention policy. + requestBody: + content: + application/json: + schema: + type: object + required: + - policy_name + - policy_type + - disposition_action + properties: + policy_name: + type: string + description: The name for the retention policy + example: Some Policy Name + policy_type: + type: string + example: finite + description: 'The type of the retention policy. A retention policy type can either be `finite`, where a specific amount of time to retain the content is known upfront, or `indefinite`, where the amount of time to retain the content is still unknown.' + enum: + - finite + - indefinite + disposition_action: + type: string + example: permanently_delete + description: 'The disposition action of the retention policy. This action can be `permanently_delete`, which will cause the content retained by the policy to be permanently deleted, or `remove_retention`, which will lift the retention policy from the content, allowing it to be deleted by users, once the retention policy has expired.' + enum: + - permanently_delete + - remove_retention + retention_length: + type: string + format: int32 + example: '365' + minimum: 1 + description: 'The length of the retention policy. This length specifies the duration in days that the retention policy will be active for after being assigned to content. If the policy has A `policy_type` of `indefinite`, the `retention_length` will also be `indefinite`.' + can_owner_extend_retention: + type: boolean + example: true + description: Whether the owner of a file will be allowed to extend the retention. + are_owners_notified: + type: boolean + example: true + description: Whether owner and co-owners of a file are notified when the policy nears expiration. + custom_notification_recipients: + type: array + items: + type: object + description: A user that is notified of an event. + properties: + type: + description: The type of item to notify + type: string + example: user + enum: + - user + id: + description: The id of the user to notify + type: string + example: '12312312' + name: + type: string + description: The name of the user to notify + example: Tim Apple + login: + type: string + description: The email address the user uses to notify + example: apple@example.com + responses: + '200': + description: Returns a new retention policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicy' + '400': + description: 'Returns a `bad_request` error with the `retention_length` was specified for a `infinite` retention policy, or an incorrect `disposition_action` was set.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: Returns an error if a retention policy with the given name already exists + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/retention_policies/{retention_policy_id}': + get: + operationId: get_retention_policies_id + summary: Get retention policy + tags: + - Retention policies + x-box-tag: retention_policies + description: Retrieves a retention policy. + parameters: + - name: retention_policy_id + description: The ID of the retention policy. + example: '982312' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns the retention policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicy' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_retention_policies_id + summary: Update retention policy + tags: + - Retention policies + x-box-tag: retention_policies + description: Updates a retention policy. + parameters: + - name: retention_policy_id + description: The ID of the retention policy. + example: '982312' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + policy_name: + type: string + description: The name for the retention policy + example: Some Policy Name + disposition_action: + type: string + example: permanently_delete + description: 'The disposition action of the retention policy. This action can be `permanently_delete`, which will cause the content retained by the policy to be permanently deleted, or `remove_retention`, which will lift the retention policy from the content, allowing it to be deleted by users, once the retention policy has expired.' + enum: + - permanently_delete + - remove_retention + status: + type: string + example: retired + description: 'Used to retire a retention policy. If not retiring a policy, do not include this parameter or set it to `null`.' + enum: + - retired + responses: + '200': + description: Returns the updated retention policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicy' + '400': + description: Returns a `bad_request` if an incorrect `disposition_action` was set. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: Returns an error if a retention policy with the given name already exists + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/retention_policies/{retention_policy_id}/assignments': + get: + operationId: get_retention_policies_id_assignments + summary: List retention policy assignments + tags: + - Retention policy assignments + x-box-tag: retention_policy_assignments + description: Returns a list of all retention policy assignments associated with a specified retention policy. + parameters: + - name: retention_policy_id + description: The ID of the retention policy. + example: '982312' + in: path + required: true + schema: + type: string + - name: type + description: The type of the retention policy assignment to retrieve. + in: query + required: false + example: folder + schema: + type: string + enum: + - folder + - enterprise + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a list of the retention policy assignments associated with the specified retention policy. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicyAssignments' + '400': + description: Returns an error if an unknown `type` is specified. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /retention_policy_assignments: + post: + operationId: post_retention_policy_assignments + summary: Assign retention policy + tags: + - Retention policy assignments + x-box-tag: retention_policy_assignments + description: Assigns a retention policy to an item. + requestBody: + content: + application/json: + schema: + type: object + required: + - policy_id + - assign_to + properties: + policy_id: + type: string + description: The ID of the retention policy to assign + example: '173463' + assign_to: + type: object + description: The item to assign the policy to + required: + - type + - id + properties: + type: + type: string + description: The type of item to assign the policy to. + example: folder + enum: + - enterprise + - folder + - metadata_template + id: + type: string + description: The ID of item to assign the policy to. Set to `null` or omit when `type` is set to `enterprise`. + example: '6564564' + responses: + '201': + description: Returns a new retention policy assignment object. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicyAssignment' + '400': + description: Returns an error if an `id` is specified while assigning a the retention policy to an enterprise. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: Returns an error if no retention policy with the given `policy_id` exists. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: Returns an error if a retention policy of equal or greater length has already been assigned to this item. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/retention_policy_assignments/{retention_policy_assignment_id}': + get: + operationId: get_retention_policy_assignments_id + summary: Get retention policy assignment + tags: + - Retention policy assignments + x-box-tag: retention_policy_assignments + description: Retrieves a retention policy assignment + parameters: + - name: retention_policy_assignment_id + description: The ID of the retention policy assignment. + example: '1233123' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns the retention policy assignment object. + content: + application/json: + schema: + $ref: '#/components/schemas/RetentionPolicyAssignment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /legal_hold_policies: + get: + operationId: get_legal_hold_policies + summary: List all legal hold policies + tags: + - Legal hold policies + x-box-tag: legal_hold_policies + description: Retrieves a list of legal hold policies that belong to an enterprise. + parameters: + - name: policy_name + description: Limits results to policies for which the names start with this search term. This is a case-insensitive prefix. + in: query + example: Sales Policy + required: false + schema: + type: string + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a list of legal hold policies. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicies' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_legal_hold_policies + summary: Create legal hold policy + tags: + - Legal hold policies + x-box-tag: legal_hold_policies + description: Create a new legal hold policy. + requestBody: + content: + application/json: + schema: + type: object + required: + - policy_name + properties: + policy_name: + description: The name of the policy. + example: Sales Policy + type: string + maxLength: 254 + description: + description: A description for the policy. + example: A custom policy for the sales team + type: string + maxLength: 500 + filter_started_at: + description: 'The filter start date. When this policy is applied using a `custodian` legal hold assignments, it will only apply to file versions created or uploaded inside of the date range. Other assignment types, such as folders and files, will ignore the date filter. Required if `is_ongoing` is set to `false`.' + example: '2012-12-12T10:53:43-08:00' + type: string + maxLength: 500 + format: date-time + filter_ended_at: + description: 'The filter end date. When this policy is applied using a `custodian` legal hold assignments, it will only apply to file versions created or uploaded inside of the date range. Other assignment types, such as folders and files, will ignore the date filter. Required if `is_ongoing` is set to `false`.' + example: '2012-12-18T10:53:43-08:00' + type: string + maxLength: 500 + format: date-time + is_ongoing: + description: 'Whether new assignments under this policy should continue applying to files even after initialization. When this policy is applied using a legal hold assignment, it will continue applying the policy to any new file versions even after it has been applied. For example, if a legal hold assignment is placed on a user today, and that user uploads a file tomorrow, that file will get held. This will continue until the policy is retired. Required if no filter dates are set.' + example: true + type: boolean + responses: + '201': + description: Returns a new legal hold policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicy' + '400': + description: 'Returns an error if required parameters are missing, or neither `is_ongoing` or filter dates are specified.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '409': + description: Returns an error if a policy with this name already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/legal_hold_policies/{legal_hold_policy_id}': + get: + operationId: get_legal_hold_policies_id + summary: Get legal hold policy + tags: + - Legal hold policies + x-box-tag: legal_hold_policies + description: Retrieve a legal hold policy. + parameters: + - name: legal_hold_policy_id + description: The ID of the legal hold policy + example: '324432' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a legal hold policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicy' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_legal_hold_policies_id + summary: Update legal hold policy + tags: + - Legal hold policies + x-box-tag: legal_hold_policies + description: Update legal hold policy. + parameters: + - name: legal_hold_policy_id + description: The ID of the legal hold policy + example: '324432' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + properties: + policy_name: + description: The name of the policy. + example: Sales Policy + type: string + maxLength: 254 + description: + description: A description for the policy. + example: A custom policy for the sales team + type: string + maxLength: 500 + release_notes: + description: Notes around why the policy was released. + example: Required for GDPR + type: string + maxLength: 500 + responses: + '200': + description: Returns a new legal hold policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicy' + '409': + description: Returns an error if a policy with this name already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_legal_hold_policies_id + x-box-tag: legal_hold_policies + tags: + - Legal hold policies + summary: Remove legal hold policy + description: Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. + parameters: + - name: legal_hold_policy_id + description: The ID of the legal hold policy + example: '324432' + in: path + required: true + schema: + type: string + responses: + '202': + content: {} + description: A blank response is returned if the policy was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /legal_hold_policy_assignments: + get: + operationId: get_legal_hold_policy_assignments + summary: List legal hold policy assignments + tags: + - Legal hold policy assignments + x-box-tag: legal_hold_policy_assignments + description: Retrieves a list of items a legal hold policy has been assigned to. + parameters: + - name: policy_id + description: The ID of the legal hold policy + example: '324432' + in: query + required: true + schema: + type: string + - name: assign_to_type + description: Filters the results by the type of item the policy was applied to. + example: file + in: query + schema: + type: string + enum: + - file + - file_version + - folder + - user + - name: assign_to_id + description: Filters the results by the ID of item the policy was applied to. + example: '1234323' + in: query + schema: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns a list of legal hold policy assignments. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicyAssignments' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_legal_hold_policy_assignments + summary: Assign legal hold policy + tags: + - Legal hold policy assignments + x-box-tag: legal_hold_policy_assignments + description: 'Assign a legal hold to a file, file version, folder, or user.' + requestBody: + content: + application/json: + schema: + type: object + required: + - policy_id + - assign_to + properties: + policy_id: + description: The ID of the policy to assign. + example: '123244' + type: string + assign_to: + type: object + description: The item to assign the policy to + required: + - type + - id + properties: + type: + type: string + description: The type of item to assign the policy to + example: folder + enum: + - file + - file_version + - folder + - user + id: + type: string + description: The ID of item to assign the policy to + example: '6564564' + responses: + '201': + description: Returns a new legal hold policy assignment. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicyAssignment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/legal_hold_policy_assignments/{legal_hold_policy_assignment_id}': + get: + operationId: get_legal_hold_policy_assignments_id + summary: Get legal hold policy assignment + tags: + - Legal hold policy assignments + x-box-tag: legal_hold_policy_assignments + description: Retrieve a legal hold policy assignment. + parameters: + - name: legal_hold_policy_assignment_id + description: The ID of the legal hold policy assignment + example: '753465' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a legal hold policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/LegalHoldPolicyAssignment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_legal_hold_policy_assignments_id + x-box-tag: legal_hold_policy_assignments + tags: + - Legal hold policy assignments + summary: Unassign legal hold policy + description: Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. + parameters: + - name: legal_hold_policy_assignment_id + description: The ID of the legal hold policy assignment + example: '753465' + in: path + required: true + schema: + type: string + responses: + '202': + content: {} + description: A blank response is returned if the assignment was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/legal_hold_policy_assignments/{legal_hold_policy_assignment_id}/files_on_hold': + get: + operationId: get_legal_hold_policy_assignments_id_files_on_hold + summary: List current file versions for legal hold policy assignment + tags: + - Legal hold policy assignments + x-box-tag: legal_hold_policy_assignments + description: 'Get a list of current file versions for a legal hold assignment. In some cases you may want to get previous file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API instead to return any previous versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all file versions held for this policy ID. Instead, this API will only return the latest file version held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID.' + parameters: + - name: legal_hold_policy_assignment_id + description: The ID of the legal hold policy assignment + example: '753465' + in: path + required: true + schema: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns the list of current file versions held under legal hold for a specific legal hold policy assignment. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersionLegalHolds' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/legal_hold_policy_assignments/{legal_hold_policy_assignment_id}/file_versions_on_hold': + get: + operationId: get_legal_hold_policy_assignments_id_file_versions_on_hold + summary: List previous file versions for legal hold policy assignment + tags: + - Legal hold policy assignments + x-box-tag: legal_hold_policy_assignments + description: 'Get a list of previous file versions for a legal hold assignment. In some cases you may only need the latest file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/files_on_hold` API instead to return any current (latest) versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all files held for this policy ID. Instead, this API will only return past file versions held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID.' + parameters: + - name: legal_hold_policy_assignment_id + description: The ID of the legal hold policy assignment + example: '753465' + in: path + required: true + schema: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: Returns the list of previous file versions held under legal hold for a specific legal hold policy assignment. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersionLegalHolds' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/file_version_retentions/{file_version_retention_id}': + get: + operationId: get_file_version_retentions_id + tags: + - File version retentions + x-box-tag: file_version_retentions + summary: Get retention on file + description: Returns information about a file version retention. + parameters: + - name: file_version_retention_id + description: The ID of the file version retention + in: path + required: true + example: '3424234' + schema: + type: string + responses: + '200': + description: Returns a file version retention object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersionRetention' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /file_version_retentions: + get: + operationId: get_file_version_retentions + tags: + - File version retentions + x-box-tag: file_version_retentions + summary: List file version retentions + description: Retrieves all file version retentions for the given enterprise. + parameters: + - name: file_id + description: Filters results by files with this ID. + in: query + example: '43123123' + required: false + schema: + type: string + - name: file_version_id + description: Filters results by file versions with this ID. + in: query + example: '1' + required: false + schema: + type: string + - name: policy_id + description: Filters results by the retention policy with this ID. + in: query + required: false + example: '982312' + schema: + type: string + - name: disposition_action + description: Filters results by the retention policy with this disposition action. + in: query + required: false + example: permanently_delete + schema: + type: string + enum: + - permanently_delete + - remove_retention + - name: disposition_before + description: Filters results by files that will have their disposition come into effect before this date. + in: query + required: false + example: '2012-12-12T10:53:43-08:00' + schema: + type: string + - name: disposition_after + description: Filters results by files that will have their disposition come into effect after this date. + in: query + required: false + example: '2012-12-19T10:34:23-08:00' + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + responses: + '200': + description: Returns a list of all file version retentions for the enterprise. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersionRetentions' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/file_version_legal_holds/{file_version_legal_hold_id}': + get: + operationId: get_file_version_legal_holds_id + summary: Get file version legal hold + tags: + - File version legal holds + x-box-tag: file_version_legal_holds + description: Retrieves information about the legal hold policies assigned to a file version. + parameters: + - name: file_version_legal_hold_id + description: The ID of the file version legal hold + in: path + required: true + example: '2348213' + schema: + type: string + responses: + '200': + description: Returns the legal hold policy assignments for the file version. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersionLegalHold' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /file_version_legal_holds: + get: + operationId: get_file_version_legal_holds + summary: List file version legal holds + tags: + - File version legal holds + x-box-tag: file_version_legal_holds + description: 'Get a list of file versions on legal hold for a legal hold assignment. Due to ongoing re-architecture efforts this API might not return all file versions for this policy ID. Instead, this API will only return file versions held in the legacy architecture. Two new endpoints will available to request any file versions held in the new architecture. For file versions held in the new architecture, the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to return all past file versions available for this policy assignment, and the `GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to return any current (latest) versions of a file under legal hold. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. Once the re-architecture is completed this API will be deprecated.' + parameters: + - name: policy_id + description: The ID of the legal hold policy to get the file version legal holds for. + in: query + example: '133870' + required: true + schema: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns the list of file version legal holds for a specific legal hold policy. + content: + application/json: + schema: + $ref: '#/components/schemas/FileVersionLegalHolds' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/device_pinners/{device_pinner_id}': + get: + operationId: get_device_pinners_id + summary: Get device pin + tags: + - Device pinners + x-box-tag: device_pinners + description: Retrieves information about an individual device pin. + parameters: + - name: device_pinner_id + description: The ID of the device pin + in: path + required: true + example: '2324234' + schema: + type: string + responses: + '200': + description: Returns information about a single device pin. + content: + application/json: + schema: + $ref: '#/components/schemas/DevicePinner' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_device_pinners_id + summary: Remove device pin + tags: + - Device pinners + x-box-tag: device_pinners + description: Deletes an individual device pin. + parameters: + - name: device_pinner_id + description: The ID of the device pin + in: path + required: true + example: '2324234' + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the pin has been deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/enterprises/{enterprise_id}/device_pinners': + get: + operationId: get_enterprises_id_device_pinners + summary: List enterprise device pins + tags: + - Device pinners + x-box-tag: device_pinners + description: 'Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call.' + parameters: + - name: enterprise_id + description: The ID of the enterprise + in: path + required: true + example: '3442311' + schema: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + - name: direction + description: The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. + in: query + required: false + example: ASC + schema: + type: string + enum: + - ASC + - DESC + responses: + '200': + description: Returns a list of device pins for a given enterprise. + content: + application/json: + schema: + $ref: '#/components/schemas/DevicePinners' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /terms_of_services: + get: + operationId: get_terms_of_services + x-box-tag: terms_of_services + summary: List terms of services + tags: + - Terms of service + description: Returns the current terms of service text and settings for the enterprise. + parameters: + - name: tos_type + description: Limits the results to the terms of service of the given type. + in: query + required: false + example: managed + schema: + type: string + enum: + - external + - managed + responses: + '200': + description: Returns a collection of terms of service text and settings for the enterprise. + content: + application/json: + schema: + $ref: '#/components/schemas/TermsOfServices' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_terms_of_services + tags: + - Terms of service + summary: Create terms of service + x-box-tag: terms_of_services + description: Creates a terms of service for a given enterprise and type of user. + requestBody: + content: + application/json: + schema: + type: object + required: + - status + - text + properties: + status: + description: Whether this terms of service is active. + example: enabled + type: string + enum: + - enabled + - disabled + tos_type: + description: The type of user to set the terms of service for. + example: managed + type: string + enum: + - external + - managed + text: + description: The terms of service text to display to users. The text can be set to empty if the `status` is set to `disabled`. + example: By collaborating on this file you are accepting... + type: string + responses: + '200': + description: Returns a new task object + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/terms_of_services/{terms_of_service_id}': + get: + operationId: get_terms_of_services_id + summary: Get terms of service + tags: + - Terms of service + x-box-tag: terms_of_services + description: Fetches a specific terms of service. + parameters: + - name: terms_of_service_id + description: The ID of the terms of service. + example: '324234' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a terms of service object. + content: + application/json: + schema: + $ref: '#/components/schemas/TermsOfService' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_terms_of_services_id + summary: Update terms of service + tags: + - Terms of service + x-box-tag: terms_of_services + description: Updates a specific terms of service. + parameters: + - name: terms_of_service_id + description: The ID of the terms of service. + example: '324234' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - status + - text + properties: + status: + description: Whether this terms of service is active. + example: enabled + type: string + enum: + - enabled + - disabled + text: + description: The terms of service text to display to users. The text can be set to empty if the `status` is set to `disabled`. + example: By collaborating on this file you are accepting... + type: string + responses: + '200': + description: Returns an updated terms of service object. + content: + application/json: + schema: + $ref: '#/components/schemas/TermsOfService' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /terms_of_service_user_statuses: + get: + operationId: get_terms_of_service_user_statuses + summary: List terms of service user statuses + tags: + - Terms of service user statuses + x-box-tag: terms_of_service_user_statuses + description: 'Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when.' + parameters: + - name: tos_id + description: The ID of the terms of service. + example: '324234' + in: query + required: true + schema: + type: string + - name: user_id + description: Limits results to the given user ID. + example: '123334' + in: query + required: false + schema: + type: string + responses: + '200': + description: Returns a list of terms of service statuses. + content: + application/json: + schema: + $ref: '#/components/schemas/TermsOfServiceUserStatuses' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_terms_of_service_user_statuses + summary: Create terms of service status for new user + tags: + - Terms of service user statuses + x-box-tag: terms_of_service_user_statuses + description: Sets the status for a terms of service for a user. + requestBody: + content: + application/json: + schema: + type: object + required: + - tos + - user + - is_accepted + properties: + tos: + type: object + description: The terms of service to set the status for. + required: + - id + - type + properties: + type: + type: string + description: The type of object. + example: terms_of_service + enum: + - terms_of_service + id: + type: string + description: The ID of terms of service + example: '1232132' + user: + type: object + description: The user to set the status for. + required: + - id + - type + properties: + type: + type: string + description: The type of object. + example: user + enum: + - user + id: + type: string + description: The ID of user + example: '3423423' + is_accepted: + type: boolean + example: true + description: Whether the user has accepted the terms. + responses: + '200': + description: Returns a terms of service status object. + content: + application/json: + schema: + $ref: '#/components/schemas/TermsOfServiceUserStatus' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/terms_of_service_user_statuses/{terms_of_service_user_status_id}': + put: + operationId: put_terms_of_service_user_statuses_id + summary: Update terms of service status for existing user + tags: + - Terms of service user statuses + x-box-tag: terms_of_service_user_statuses + description: Updates the status for a terms of service for a user. + parameters: + - name: terms_of_service_user_status_id + description: The ID of the terms of service status. + example: '324234' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - is_accepted + properties: + is_accepted: + type: boolean + example: true + description: Whether the user has accepted the terms. + responses: + '200': + description: Returns the updated terms of service status object. + content: + application/json: + schema: + $ref: '#/components/schemas/TermsOfServiceUserStatus' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /collaboration_whitelist_entries: + get: + operationId: get_collaboration_whitelist_entries + summary: List allowed collaboration domains + tags: + - Domain restrictions for collaborations + x-box-tag: collaboration_allowlist_entries + description: Returns the list domains that have been deemed safe to create collaborations for within the current enterprise. + parameters: + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a collection of domains that are allowed for collaboration. + content: + application/json: + schema: + $ref: '#/components/schemas/CollaborationAllowlistEntries' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_collaboration_whitelist_entries + summary: Add domain to list of allowed collaboration domains + tags: + - Domain restrictions for collaborations + x-box-tag: collaboration_allowlist_entries + description: Creates a new entry in the list of allowed domains to allow collaboration for. + requestBody: + content: + application/json: + schema: + type: object + required: + - domain + - direction + properties: + domain: + type: string + description: The domain to add to the list of allowed domains. + example: example.com + direction: + type: string + description: The direction in which to allow collaborations. + example: inbound + enum: + - inbound + - outbound + - both + responses: + '200': + description: Returns a new entry on the list of allowed domains. + content: + application/json: + schema: + $ref: '#/components/schemas/CollaborationAllowlistEntry' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/collaboration_whitelist_entries/{collaboration_whitelist_entry_id}': + get: + operationId: get_collaboration_whitelist_entries_id + summary: Get allowed collaboration domain + tags: + - Domain restrictions for collaborations + x-box-tag: collaboration_allowlist_entries + description: Returns a domain that has been deemed safe to create collaborations for within the current enterprise. + parameters: + - name: collaboration_whitelist_entry_id + description: The ID of the entry in the list. + in: path + required: true + example: '213123' + schema: + type: string + responses: + '200': + description: Returns an entry on the list of allowed domains. + content: + application/json: + schema: + $ref: '#/components/schemas/CollaborationAllowlistEntry' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_collaboration_whitelist_entries_id + summary: Remove domain from list of allowed collaboration domains + tags: + - Domain restrictions for collaborations + x-box-tag: collaboration_allowlist_entries + description: Removes a domain from the list of domains that have been deemed safe to create collaborations for within the current enterprise. + parameters: + - name: collaboration_whitelist_entry_id + description: The ID of the entry in the list. + in: path + required: true + example: '213123' + schema: + type: string + responses: + '204': + content: {} + description: A blank response is returned if the entry was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /collaboration_whitelist_exempt_targets: + get: + operationId: get_collaboration_whitelist_exempt_targets + summary: List users exempt from collaboration domain restrictions + tags: + - Domain restrictions (User exemptions) + x-box-tag: collaboration_allowlist_exempt_targets + description: Returns a list of users who have been exempt from the collaboration domain restrictions. + parameters: + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a collection of user exemptions. + content: + application/json: + schema: + $ref: '#/components/schemas/CollaborationAllowlistExemptTargets' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_collaboration_whitelist_exempt_targets + summary: Create user exemption from collaboration domain restrictions + tags: + - Domain restrictions (User exemptions) + x-box-tag: collaboration_allowlist_exempt_targets + description: Exempts a user from the restrictions set out by the allowed list of domains for collaborations. + requestBody: + content: + application/json: + schema: + type: object + required: + - user + properties: + user: + type: object + description: The user to exempt. + required: + - id + properties: + id: + type: string + description: The ID of the user to exempt. + example: '23522323' + responses: + '200': + description: Returns a new exemption entry. + content: + application/json: + schema: + $ref: '#/components/schemas/CollaborationAllowlistExemptTarget' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/collaboration_whitelist_exempt_targets/{collaboration_whitelist_exempt_target_id}': + get: + operationId: get_collaboration_whitelist_exempt_targets_id + summary: Get user exempt from collaboration domain restrictions + tags: + - Domain restrictions (User exemptions) + x-box-tag: collaboration_allowlist_exempt_targets + description: Returns a users who has been exempt from the collaboration domain restrictions. + parameters: + - name: collaboration_whitelist_exempt_target_id + description: The ID of the exemption to the list. + in: path + required: true + example: '984923' + schema: + type: string + responses: + '200': + description: Returns the user's exempted from the list of collaboration domains. + content: + application/json: + schema: + $ref: '#/components/schemas/CollaborationAllowlistExemptTarget' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_collaboration_whitelist_exempt_targets_id + summary: Remove user from list of users exempt from domain restrictions + tags: + - Domain restrictions (User exemptions) + x-box-tag: collaboration_allowlist_exempt_targets + description: Removes a user's exemption from the restrictions set out by the allowed list of domains for collaborations. + parameters: + - name: collaboration_whitelist_exempt_target_id + description: The ID of the exemption to the list. + in: path + required: true + example: '984923' + schema: + type: string + responses: + '204': + content: {} + description: A blank response is returned if the exemption was successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /storage_policies: + get: + operationId: get_storage_policies + summary: List storage policies + tags: + - Storage policies + x-box-tag: storage_policies + description: Fetches all the storage policies in the enterprise. + parameters: + - name: fields + description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested.' + in: query + example: + - id + - type + - name + required: false + explode: false + schema: + type: array + items: + type: string + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: limit + description: The maximum number of items to return per page. + in: query + required: false + example: 1000 + schema: + type: integer + format: int64 + maximum: 1000 + responses: + '200': + description: Returns a collection of storage policies. + content: + application/json: + schema: + $ref: '#/components/schemas/StoragePolicies' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/storage_policies/{storage_policy_id}': + get: + operationId: get_storage_policies_id + summary: Get storage policy + tags: + - Storage policies + x-box-tag: storage_policies + description: Fetches a specific storage policy. + parameters: + - name: storage_policy_id + description: The ID of the storage policy. + example: '34342' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a storage policy object. + content: + application/json: + schema: + $ref: '#/components/schemas/StoragePolicy' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /storage_policy_assignments: + get: + operationId: get_storage_policy_assignments + summary: List storage policy assignments + tags: + - Storage policy assignments + x-box-tag: storage_policy_assignments + description: Fetches all the storage policy assignment for an enterprise or user. + parameters: + - name: marker + description: Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. + in: query + required: false + example: JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii + schema: + type: string + - name: resolved_for_type + in: query + example: user + description: The target type to return assignments for + required: true + schema: + type: string + enum: + - user + - enterprise + - name: resolved_for_id + in: query + required: true + example: '984322' + description: The ID of the user or enterprise to return assignments for + schema: + type: string + responses: + '200': + description: Returns a collection of storage policies for the enterprise or user. + content: + application/json: + schema: + $ref: '#/components/schemas/StoragePolicyAssignments' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + post: + operationId: post_storage_policy_assignments + summary: Assign storage policy + tags: + - Storage policy assignments + x-box-tag: storage_policy_assignments + description: Creates a storage policy assignment for an enterprise or user. + requestBody: + content: + application/json: + schema: + type: object + required: + - storage_policy + - assigned_to + properties: + storage_policy: + type: object + description: The storage policy to assign to the user or enterprise + required: + - type + - id + properties: + type: + type: string + description: The type to assign. + example: storage_policy + enum: + - storage_policy + id: + type: string + description: The ID of the storage policy to assign. + example: '1434325' + assigned_to: + type: object + description: The user or enterprise to assign the storage policy to. + required: + - type + - id + properties: + type: + type: string + description: The type to assign the policy to. + example: user + enum: + - user + - enterprise + id: + type: string + description: The ID of the user or enterprise + example: '9987987' + responses: + '200': + description: Returns the new storage policy assignment created. + content: + application/json: + schema: + $ref: '#/components/schemas/StoragePolicyAssignment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/storage_policy_assignments/{storage_policy_assignment_id}': + get: + operationId: get_storage_policy_assignments_id + summary: Get storage policy assignment + tags: + - Storage policy assignments + x-box-tag: storage_policy_assignments + description: Fetches a specific storage policy assignment. + parameters: + - name: storage_policy_assignment_id + description: The ID of the storage policy assignment. + example: '932483' + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns a storage policy assignment object. + content: + application/json: + schema: + $ref: '#/components/schemas/StoragePolicyAssignment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + put: + operationId: put_storage_policy_assignments_id + summary: Update storage policy assignment + tags: + - Storage policy assignments + x-box-tag: storage_policy_assignments + description: Updates a specific storage policy assignment. + parameters: + - name: storage_policy_assignment_id + description: The ID of the storage policy assignment. + example: '932483' + in: path + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + type: object + required: + - storage_policy + properties: + storage_policy: + type: object + description: The storage policy to assign to the user or enterprise + required: + - type + - id + properties: + type: + type: string + description: The type to assign. + example: storage_policy + enum: + - storage_policy + id: + type: string + description: The ID of the storage policy to assign. + example: '1434325' + responses: + '200': + description: Returns an updated storage policy assignment object. + content: + application/json: + schema: + $ref: '#/components/schemas/StoragePolicyAssignment' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + delete: + operationId: delete_storage_policy_assignments_id + summary: Unassign storage policy + tags: + - Storage policy assignments + x-box-tag: storage_policy_assignments + description: Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour time frame. + parameters: + - name: storage_policy_assignment_id + description: The ID of the storage policy assignment. + example: '932483' + in: path + required: true + schema: + type: string + responses: + '204': + content: {} + description: Returns an empty response when the storage policy assignment is successfully deleted. + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + /zip_downloads: + post: + operationId: post_zip_downloads + summary: Create zip download + tags: + - Zip Downloads + x-box-tag: zip_downloads + x-box-reference-category: zip_downloads + description: 'Creates a request to download multiple files and folders as a single `zip` archive file. This API does not return the archive but instead performs all the checks to ensure that the user has access to all the items, and then returns a `download_url` and a `status_url` that can be used to download the archive. The limit for an archive is either 32GB or 10,000 files, whichever limitation is met first.' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ZipDownloadRequest' + responses: + '202': + description: 'If the `zip` archive is ready to be downloaded, the API will return a response that will include a `download_url`, a `status_url`, as well as any conflicts that might have occurred when creating the request.' + content: + application/json: + schema: + $ref: '#/components/schemas/ZipDownload' + examples: + default: + value: + download_url: 'https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content' + status_url: 'https://api.box.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status' + expires_at: '2020-07-22T11:26:08Z' + name_conflicts: + - - id: '12345' + type: file + original_name: Report.pdf + download_name: 3aa6a7.pdf + - id: '34325' + type: file + original_name: Report.pdf + download_name: 5d53f2.pdf + '400': + description: 'Returns an error if some of the parameters are missing or not valid. In most cases, this error might happen because the JSON request body is not valid JSON, any of the items has an incorrect or missing ID, any of the items is not a file or folder, or the root folder with ID `0` has been added to the list of folders to add to the archive. The following is a list of common error codes for this response. * `bad_request` - the request body is missing, invalid, or both the list of files and folders are empty. Additionally, it this error might be returned when attempting to add the root folder with ID `0` to an archive. * `zip_download_file_count_exceeded_limit` - the requested files and folders would result in an archive with more than 10,000 files. The request will have to be split into multiple requests to reduce the number of files per archive. * `zip_download_pre_compressed_bytes_exceeded_limit` - the requested files and folders would result in an archive with more than 32GB of content. The request will have to be split into multiple requests to reduce the size of the archive.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned when an authorization header is provided but the user does not have access to the items. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/zip_downloads/{zip_download_id}/content': + get: + operationId: get_zip_downloads_id_content + summary: Download zip archive + tags: + - Zip Downloads + x-box-tag: zip_downloads + x-box-reference-category: zip_downloads + description: 'Returns the contents of a `zip` archive in binary format. This URL does not require any form of authentication and could be used in a user''s browser to download the archive to a user''s device. By default, this URL is only valid for a few seconds from the creation of the request for this archive. Once a download has started it can not be stopped and resumed, instead a new request for a zip archive would need to be created. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `download_url` field in the response to this endpoint.' + security: [] + servers: + - url: 'https://dl.boxcloud.com/2.0' + description: An opaque server URL for downloading zip downloads. The format of this URL might change over time. + parameters: + - name: zip_download_id + description: The unique identifier that represent this `zip` archive. + example: Lu6fA9Ob-jyysp3AAvMF4AkLEwZwAYbL=tgj2zIC=eK9RvJnJbjJl9rNh2qBgHDpyOCAOhpM=vajg2mKq8Mdd + in: path + required: true + schema: + type: string + responses: + '200': + description: 'Returns the content of the items requested for this download, formatted as a stream of files and folders in a `zip` archive.' + headers: + Content-Disposition: + description: The name of the archive to be downloaded + schema: + type: string + example: attachment;filename="Avatars.zip";filename*=UTF-8''Avatars.zip + content: + application/octet-stream: + schema: + type: string + format: binary + description: 'The binary content of the archive, which will include the items requested for this download.' + '404': + description: 'Returns an error if the ID of this download request is not valid. This error can also be returned if this URL has been called before. To re-download this archive, please create a new request for a zip download.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '429': + description: Returns an error if the number of concurrent zip downloads has been reached for either the user or the enterprise. * `user_too_many_concurrent_downloads` - the maximum of 5 parallel downloads of zip archives per user has been met. * `enterprise_too_many_concurrent_downloads` - the maximum of 10 parallel downloads of zip archives per enterprise has been met. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '/zip_downloads/{zip_download_id}/status': + get: + operationId: get_zip_downloads_id_status + summary: Get zip download status + tags: + - Zip Downloads + x-box-tag: zip_downloads + x-box-reference-category: zip_downloads + description: 'Returns the download status of a `zip` archive, allowing an application to inspect the progress of the download as well as the number of items that might have been skipped. This endpoint can only be accessed once the download has started. Subsequently this endpoint is valid for 12 hours from the start of the download. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `status_url` field in the response to this endpoint.' + parameters: + - name: zip_download_id + description: The unique identifier that represent this `zip` archive. + example: Lu6fA9Ob-jyysp3AAvMF4AkLEwZwAYbL=tgj2zIC=eK9RvJnJbjJl9rNh2qBgHDpyOCAOhpM=vajg2mKq8Mdd + in: path + required: true + schema: + type: string + responses: + '200': + description: Returns the status of the `zip` archive that is being downloaded. + content: + application/json: + schema: + $ref: '#/components/schemas/ZipDownloadStatus' + '401': + description: Returned when the access token provided in the `Authorization` header is not recognized or not provided. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '403': + description: Returned when an authorization header is provided but the user does not have access to the items. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + '404': + description: 'Returns an error if the ID of this download request is not valid, or if the status of a download is requested before the download has been started.' + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' + default: + description: An unexpected client error. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientError' +components: + securitySchemes: + OAuth2Security: + type: oauth2 + flows: + authorizationCode: + authorizationUrl: 'https://account.box.com/api/oauth2/authorize' + tokenUrl: 'https://api.box.com/oauth2/token' + scopes: + root_readonly: Read all files and folders stored in Box + root_readwrite: Read and write all files and folders stored in Box + manage_app_users: Provision and manage app users + manage_managed_users: Provision and manage managed users + manage_groups: Manage an enterprise's groups + manage_webhook: Create webhooks programmatically through the API + manage_enterprise_properties: Manage enterprise properties + manage_data_retention: Manage data retention polices + manage_legal_hold: Manage Legal Holds + schemas: + PostOAuth2Token: + title: Token request + type: object + description: A request for a new OAuth 2.0 token + required: + - grant_type + properties: + grant_type: + type: string + format: urn + example: authorization_code + description: 'The type of request being made, either using a client-side obtained authorization code, a refresh token, a JWT assertion, client credentials grant or another access token for the purpose of downscoping a token.' + enum: + - authorization_code + - refresh_token + - client_credentials + - 'urn:ietf:params:oauth:grant-type:jwt-bearer' + - 'urn:ietf:params:oauth:grant-type:token-exchange' + client_id: + type: string + description: 'The Client ID of the application requesting an access token. Used in combination with `authorization_code`, `client_credentials`, or `urn:ietf:params:oauth:grant-type:jwt-bearer` as the `grant_type`.' + example: ly1nj6n11vionaie65emwzk575hnnmrk + client_secret: + type: string + description: 'The client secret of the application requesting an access token. Used in combination with `authorization_code`, `client_credentials`, or `urn:ietf:params:oauth:grant-type:jwt-bearer` as the `grant_type`.' + example: hOzsTeFlT6ko0dme22uGbQal04SBPYc1 + code: + type: string + format: token + description: The client-side authorization code passed to your application by Box in the browser redirect after the user has successfully granted your application permission to make API calls on their behalf. Used in combination with `authorization_code` as the `grant_type`. + example: n22JPxrh18m4Y0wIZPIqYZK7VRrsMTWW + refresh_token: + type: string + format: token + description: A refresh token used to get a new access token with. Used in combination with `refresh_token` as the `grant_type`. + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + assertion: + type: string + format: jwt + description: 'A JWT assertion for which to request a new access token. Used in combination with `urn:ietf:params:oauth:grant-type:jwt-bearer` as the `grant_type`.' + example: xxxxx.yyyyy.zzzzz + subject_token: + type: string + format: token + description: 'The token to exchange for a downscoped token. This can be a regular access token, a JWT assertion, or an app token. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`.' + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + subject_token_type: + type: string + example: 'urn:ietf:params:oauth:token-type:access_token' + description: 'The type of `subject_token` passed in. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`.' + enum: + - 'urn:ietf:params:oauth:token-type:access_token' + actor_token: + type: string + format: token + description: 'The token used to create an annotator token. This is a JWT assertion. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`.' + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + actor_token_type: + type: string + format: urn + example: 'urn:ietf:params:oauth:token-type:id_token' + description: 'The type of `actor_token` passed in. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`.' + enum: + - 'urn:ietf:params:oauth:token-type:id_token' + scope: + type: string + format: space_delimited_list + description: The space-delimited list of scopes that you want apply to the new access token. The `subject_token` will need to have all of these scopes or the call will error with **401 Unauthorized**. + example: item_upload item_preview base_explorer + resource: + type: string + format: url + description: Full URL for the file that the token should be generated for. + example: 'https://api.box.com/2.0/files/123456' + box_subject_type: + type: string + example: enterprise + description: Used in combination with `client_credentials` as the `grant_type`. + enum: + - enterprise + - user + box_subject_id: + type: string + example: '123456789' + description: Used in combination with `client_credentials` as the `grant_type`. Value is determined by `box_subject_type`. If `user` use user ID and if `enterprise` use enterprise ID. + box_shared_link: + type: string + format: url + description: Full URL of the shared link on the file or folder that the token should be generated for. + example: 'https://cloud.box.com/s/123456' + PostOAuth2Token--RefreshAccessToken: + title: Refresh access token + type: object + description: A request to refresh an Access Token. Use this API to refresh an expired Access Token using a valid Refresh Token. + required: + - grant_type + - client_id + - client_secret + - refresh_token + properties: + grant_type: + type: string + format: urn + example: refresh_token + description: 'The type of request being made, in this case a refresh request.' + enum: + - refresh_token + client_id: + type: string + description: The client ID of the application requesting to refresh the token. + example: ly1nj6n11vionaie65emwzk575hnnmrk + client_secret: + type: string + description: The client secret of the application requesting to refresh the token. + example: hOzsTeFlT6ko0dme22uGbQal04SBPYc1 + refresh_token: + type: string + format: token + description: The refresh token to refresh. + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + PostOAuth2Revoke: + title: Token revocation request + type: object + description: A request to revoke an OAuth 2.0 token + required: + - grant_type + properties: + client_id: + type: string + description: The Client ID of the application requesting to revoke the access token. + example: ly1nj6n11vionaie65emwzk575hnnmrk + client_secret: + type: string + description: The client secret of the application requesting to revoke an access token. + example: hOzsTeFlT6ko0dme22uGbQal04SBPYc1 + token: + type: string + format: token + description: The access token to revoke. + example: n22JPxrh18m4Y0wIZPIqYZK7VRrsMTWW + ZipDownloadRequest: + title: Create a `zip` archive + type: object + description: A request to create a `zip` archive to download + required: + - items + properties: + items: + type: array + description: A list of items to add to the `zip` archive. These can be folders or files. + items: + type: object + description: An item to add to the `zip` archive. This can be a file or a folder. + required: + - type + - id + properties: + type: + type: string + description: The type of the item to add to the archive. + example: file + enum: + - file + - folder. + id: + type: string + description: The identifier of the item to add to the archive. When this item is a folder then this can not be the root folder with ID `0`. + example: '12345' + download_file_name: + type: string + description: 'The optional name of the `zip` archive. This name will be appended by the `.zip` file extension, for example `January Financials.zip`.' + example: January Financials + FileRequestUpdateRequest: + title: File Request (Update) + type: object + description: The request body to update a file request. + properties: + title: + type: string + description: An optional new title for the file request. This can be used to change the title of the file request. This will default to the value on the existing file request. + example: Please upload required documents + description: + type: string + description: An optional new description for the file request. This can be used to change the description of the file request. This will default to the value on the existing file request. + example: Please upload required documents + status: + type: string + description: 'An optional new status of the file request. When the status is set to `inactive`, the file request will no longer accept new submissions, and any visitor to the file request URL will receive a `HTTP 404` status code. This will default to the value on the existing file request.' + example: active + enum: + - active + - inactive + is_email_required: + type: boolean + example: true + description: 'Whether a file request submitter is required to provide their email address. When this setting is set to true, the Box UI will show an email field on the file request form. This will default to the value on the existing file request.' + is_description_required: + type: boolean + example: true + description: 'Whether a file request submitter is required to provide a description of the files they are submitting. When this setting is set to true, the Box UI will show a description field on the file request form. This will default to the value on the existing file request.' + expires_at: + type: string + format: date-time + description: 'The date after which a file request will no longer accept new submissions. After this date, the `status` will automatically be set to `inactive`. This will default to the value on the existing file request.' + example: '2020-09-28T10:53:43-08:00' + FileRequestCopyRequest: + title: File Request (Copy) + type: object + description: The request body to copy a file request. + required: + - folder + allOf: + - $ref: '#/components/schemas/FileRequestUpdateRequest' + - properties: + folder: + type: object + description: The folder to associate the new file request to. + required: + - id + properties: + type: + type: string + example: folder + description: '`folder`' + enum: + - folder + id: + type: string + example: '42037322' + description: The ID of the folder to associate the new file request to. + ClientError: + title: Client error + type: object + x-box-resource-id: client_error + description: A generic error + properties: + type: + description: '`error`' + example: error + type: string + enum: + - error + nullable: false + status: + description: The HTTP status of the response. + example: 400 + type: integer + format: int32 + nullable: false + code: + description: A Box-specific error code + example: item_name_invalid + type: string + enum: + - created + - accepted + - no_content + - redirect + - not_modified + - bad_request + - unauthorized + - forbidden + - not_found + - method_not_allowed + - conflict + - precondition_failed + - too_many_requests + - internal_server_error + - unavailable + - item_name_invalid + message: + description: A short message describing the error. + example: Method Not Allowed + type: string + nullable: false + context_info: + description: A free-form object that contains additional context about the error. The possible fields are defined on a per-endpoint basis. + type: object + properties: + conflicts: + type: array + description: A list of the file conflicts that caused this error. + items: + $ref: '#/components/schemas/FileConflict' + help_url: + description: A URL that links to more information about why this error occurred. + example: 'http://developers.box.com/docs/#errors' + type: string + nullable: false + request_id: + description: 'A unique identifier for this response, which can be used when contacting Box support.' + type: string + example: abcdef123456 + nullable: false + ConflictError: + title: Conflict error + type: object + x-box-resource-id: conflict_error + x-box-tag: uploads + description: The error that occurs when a file can not be created due to a conflict. + allOf: + - $ref: '#/components/schemas/ClientError' + - properties: + context_info: + type: object + properties: + conflicts: + type: array + description: A list of the file conflicts that caused this error. + items: + $ref: '#/components/schemas/FileConflict' + OAuth2Error: + title: OAuth 2.0 error + type: object + x-box-resource-id: oauth2_error + x-box-tag: authorization + description: An OAuth 2.0 error + properties: + error: + type: string + example: invalid_client + description: The type of the error returned. + error_description: + type: string + example: The client credentials are not valid + description: The type of the error returned. + SkillInvocation: + title: Skill webhook payload + x-box-resource-id: skill_invocation + x-box-tag: skills + description: The payload of a Box skill as sent to a skill's `invocation_url`. + properties: + type: + type: string + description: '`skill_invocation`' + example: skill_invocation + enum: + - skill_invocation + id: + type: string + description: Unique identifier for the invocation request. + example: fd1d2e53-35f5-41fb-9c25-4ba326daf2f9_341016304 + skill: + title: Skill + description: An object representing a skill + properties: + id: + type: string + description: The unique identifier for this skill + example: '11446498' + type: + type: string + description: '`skill`' + example: skill + enum: + - skill + name: + type: string + description: The name of the skill + example: Hello World Skill + api_key: + type: string + description: The client ID of the application + example: hxel2s12wd2h9r8ne103c4gjbqefofih + token: + type: object + description: The read-only and read-write access tokens for this item + properties: + read: + type: object + description: The basics of an access token + properties: + access_token: + type: string + format: token + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + description: The requested access token. + expires_in: + type: integer + format: int64 + example: 3600 + description: The time in seconds in seconds by which this token will expire. + token_type: + type: string + enum: + - bearer + example: bearer + description: The type of access token returned. + restricted_to: + type: array + description: 'The permissions that this access token permits, providing a list of resources (files, folders, etc) and the scopes permitted for each of those resources.' + items: + $ref: '#/components/schemas/FileScope' + write: + type: object + description: The basics of an access token + properties: + access_token: + type: string + format: token + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + description: The requested access token. + expires_in: + type: integer + format: int64 + example: 3600 + description: The time in seconds in seconds by which this token will expire. + token_type: + type: string + enum: + - bearer + example: bearer + description: The type of access token returned. + restricted_to: + type: array + description: 'The permissions that this access token permits, providing a list of resources (files, folders, etc) and the scopes permitted for each of those resources.' + items: + $ref: '#/components/schemas/FileScope' + status: + type: object + description: The details status of this event. + properties: + state: + type: string + example: invoked + description: The state of this event. * `invoked` - Triggered the skill with event details to start applying skill on the file. * `processing` - Currently processing. * `success` - Completed processing with a success. * `transient_failure` - Encountered an issue which can be retried. * `permanent_failure` - Encountered a permanent issue and retry would not help. + enum: + - invoked + - processing + - success + - transient_failure + - permanent_failure + message: + type: string + example: Example + description: Status information + error_code: + type: string + example: '400' + description: 'Error code information, if error occurred.' + additional_info: + type: string + example: Example + description: Additional status information. + created_at: + type: string + format: date-time + description: The time this invocation was created. + example: '2012-12-12T10:53:43-08:00' + trigger: + type: string + example: FILE_CONTENT + description: Action that triggered the invocation + enterprise: + title: Enterprise + type: object + description: A representation of a Box enterprise + properties: + id: + type: string + description: The unique identifier for this enterprise. + example: '11446498' + type: + type: string + description: '`enterprise`' + example: enterprise + enum: + - enterprise + name: + description: The name of the enterprise + example: Acme Inc. + type: string + source: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + event: + description: The event that triggered this invocation + $ref: '#/components/schemas/Event' + WebhookInvocation: + title: Webhook (V2) payload + x-box-resource-id: webhook_invocation + x-box-tag: webhooks + description: The event that is sent to a webhook address when an event happens. + properties: + id: + type: string + description: The unique identifier for this webhook invocation + example: '11446498' + type: + type: string + description: '`webhook_event`' + example: webhook_event + enum: + - webhook_event + webhook: + description: The webhook object that triggered this event + $ref: '#/components/schemas/Webhook' + created_by: + description: The user that triggered this event + $ref: '#/components/schemas/User--Mini' + created_at: + type: string + format: date-time + description: A timestamp identifying the time that the webhook event was triggered. + example: '2012-12-12T10:53:43-08:00' + trigger: + title: Webhook Trigger + example: FILE.UPLOADED + type: string + description: The event name that triggered this webhook + enum: + - FILE.UPLOADED + - FILE.PREVIEWED + - FILE.DOWNLOADED + - FILE.TRASHED + - FILE.DELETED + - FILE.RESTORED + - FILE.COPIED + - FILE.MOVED + - FILE.LOCKED + - FILE.UNLOCKED + - FILE.RENAMED + - COMMENT.CREATED + - COMMENT.UPDATED + - COMMENT.DELETED + - TASK_ASSIGNMENT.CREATED + - TASK_ASSIGNMENT.UPDATED + - METADATA_INSTANCE.CREATED + - METADATA_INSTANCE.UPDATED + - METADATA_INSTANCE.DELETED + - FOLDER.CREATED + - FOLDER.RENAMED + - FOLDER.DOWNLOADED + - FOLDER.RESTORED + - FOLDER.DELETED + - FOLDER.COPIED + - FOLDER.MOVED + - FOLDER.TRASHED + - WEBHOOK.DELETED + - COLLABORATION.CREATED + - COLLABORATION.ACCEPTED + - COLLABORATION.REJECTED + - COLLABORATION.REMOVED + - COLLABORATION.UPDATED + - SHARED_LINK.DELETED + - SHARED_LINK.CREATED + - SHARED_LINK.UPDATED + source: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + AccessToken: + title: Access token + type: object + x-box-resource-id: access_token + x-box-tag: authorization + description: A token that can be used to make authenticated API calls. + properties: + access_token: + type: string + format: token + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + description: The requested access token. + expires_in: + type: integer + format: int64 + example: 3600 + description: The time in seconds in seconds by which this token will expire. + token_type: + type: string + enum: + - bearer + example: bearer + description: The type of access token returned. + restricted_to: + type: array + description: 'The permissions that this access token permits, providing a list of resources (files, folders, etc) and the scopes permitted for each of those resources.' + items: + $ref: '#/components/schemas/FileScope' + refresh_token: + type: string + format: token + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + description: 'The refresh token for this access token, which can be used to request a new access token when the current one expires.' + issued_token_type: + type: string + format: urn + example: 'urn:ietf:params:oauth:token-type:access_token' + enum: + - 'urn:ietf:params:oauth:token-type:access_token' + description: The type of downscoped access token returned. This is only returned if an access token has been downscoped. + ClassificationTemplate: + title: Classification Template + type: object + x-box-resource-id: classification_template + x-box-tag: classifications + description: A metadata template that holds the security classifications defined by an enterprise. + properties: + id: + type: string + example: 58063d82-4128-7b43-bba9-92f706befcdf + description: The ID of the classification template. + type: + type: string + description: '`metadata_template`' + example: metadata_template + enum: + - metadata_template + nullable: false + scope: + type: string + description: 'The scope of the classification template. This is in the format `enterprise_{id}` where the `id` is the enterprise ID.' + example: enterprise_123456 + templateKey: + type: string + example: securityClassification-6VMVochwUWo + description: '`securityClassification-6VMVochwUWo`' + enum: + - securityClassification-6VMVochwUWo + displayName: + type: string + example: Classification + description: The name of this template as shown in web and mobile interfaces. + enum: + - Classification + hidden: + type: boolean + example: false + description: This template is always available in web and mobile interfaces. + copyInstanceOnItemCopy: + type: boolean + example: true + description: Classifications are always copied along when the file or folder is copied. + fields: + type: array + maxItems: 1 + minItems: 1 + description: 'A list of fields for this classification template. This includes only one field, the `Box__Security__Classification__Key`, which defines the different classifications available in this enterprise.' + items: + type: object + description: The metadata template field that represents the available classifications. + properties: + id: + type: string + example: 822227e0-47a5-921b-88a8-494760b2e6d2 + description: The unique ID of the field. + type: + type: string + example: enum + description: '`enum`' + enum: + - enum + key: + type: string + example: Box__Security__Classification__Key + description: '`Box__Security__Classification__Key`' + enum: + - Box__Security__Classification__Key + displayName: + type: string + example: Classification + description: '`Classification`' + enum: + - Classification + hidden: + type: boolean + example: false + description: Classifications are always visible to web and mobile users. + options: + type: array + description: A list of classifications available in this enterprise. + minItems: 1 + items: + type: object + description: A single classification available in this enterprise. + properties: + id: + type: string + example: 46aea176-3483-4431-856c-6b5b13d1cc50 + description: The unique ID of this classification. + key: + type: string + example: Sensitive + description: The display name and key for this classification. + staticConfig: + type: object + description: Additional information about the classification. + properties: + classification: + type: object + description: 'Additional information about the classification. This is not an exclusive list of properties, and more object fields might be returned. These fields are used for internal Box Shield and Box Governance purposes and no additional value must be derived from these fields.' + properties: + classificationDefinition: + type: string + example: Sensitive information + description: A longer description of the classification. + colorID: + type: number + example: 4 + description: 'An internal Box identifier used to assign a color to a classification label. Mapping between a `colorID` and a color may change without notice. Currently, the color mappings are as follows. * `0`: Yellow * `1`: Orange * `2`: Watermelon red * `3`: Purple rain * `4`: Light blue * `5`: Dark blue * `6`: Light green * `7`: Gray' + Collaboration: + title: Collaboration + type: object + x-box-resource-id: collaboration + x-box-tag: user_collaborations + description: 'Collaborations define access permissions for users and groups to files and folders, similar to access control lists. A collaboration object grants a user or group access to a file or folder with permissions defined by a specific role.' + properties: + id: + type: string + description: The unique identifier for this collaboration. + example: '12345678' + type: + type: string + description: '`collaboration`' + example: collaboration + enum: + - collaboration + item: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + - $ref: '#/components/schemas/WebLink' + nullable: true + accessible_by: + description: The user or group that is granted access + $ref: '#/components/schemas/User--Mini' + invite_email: + type: string + nullable: true + example: john@example.com + description: 'The email address used to invite an unregistered collaborator, if they are not a registered user.' + role: + type: string + example: editor + enum: + - editor + - viewer + - previewer + - uploader + - previewer uploader + - viewer uploader + - co-owner + - owner + description: The level of access granted. + expires_at: + type: string + nullable: true + format: date-time + example: '2012-12-26T10:53:43-08:00' + description: 'When the collaboration will expire, or `null` if no expiration date is set.' + status: + type: string + example: accepted + enum: + - accepted + - pending + - rejected + description: The status of the collaboration invitation. + acknowledged_at: + type: string + format: date-time + example: '2012-12-12T10:55:20-08:00' + description: When the `status` of the collaboration object changed to `accepted` or `rejected` + created_by: + description: The user who created the collaboration object + $ref: '#/components/schemas/User--Mini' + created_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: When the collaboration object was created + modified_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: When the collaboration object was last modified + acceptance_requirements_status: + type: object + description: The terms of service that must be accepted before the collaboration can be accepted. + properties: + terms_of_service_requirement: + type: object + properties: + is_accepted: + type: boolean + nullable: true + example: true + description: Whether or not the terms of service have been accepted. The field is `null` when there is no terms of service required. + terms_of_service: + allOf: + - $ref: '#/components/schemas/TermsOfService--Mini' + - description: The terms of service that must be accepted before the collaboration can be accepted. The field is `null` when there is no terms of service required. + strong_password_requirement: + type: object + properties: + enterprise_has_strong_password_required_for_external_users: + type: boolean + example: true + description: Whether or not the enterprise that owns the content requires a strong password to collaborate on the content. + user_has_strong_password: + type: boolean + nullable: true + example: true + description: Whether or not the user has a strong password set for their account. The field is `null` when a strong password is not required. + two_factor_authentication_requirement: + type: object + properties: + enterprise_has_two_factor_auth_enabled: + type: boolean + example: true + description: Whether or not the enterprise that owns the content requires two-factor authentication to be enabled in order to collaborate on the content. + user_has_two_factor_authentication_enabled: + type: boolean + nullable: true + example: true + description: Whether or not the user has two-factor authentication enabled. The field is `null` when two-factor authentication is not required. + Collaborations: + title: Collaborations + type: object + x-box-resource-id: collaborations + x-box-tag: user_collaborations + description: A list of collaborations + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/Collaboration' + CollaborationAllowlistEntry: + title: Allowed collaboration domain + type: object + x-box-resource-id: collaboration_allowlist_entry + x-box-tag: collaboration_allowlist_entries + description: An entry that describes an approved domain for which users can collaborate with files and folders in your enterprise or vice versa. + properties: + id: + type: string + description: The unique identifier for this entry + example: '11446498' + type: + type: string + description: '`collaboration_whitelist_entry`' + example: collaboration_whitelist_entry + enum: + - collaboration_whitelist_entry + domain: + type: string + example: example.com + description: The whitelisted domain + direction: + type: string + example: both + description: The direction of the collaborations to allow. + enum: + - inbound + - outbound + - both + enterprise: + description: Collaboration allowlist enterprise. + $ref: '#/components/schemas/CollaborationAllowlistEnterprise' + created_at: + type: string + format: date-time + description: The time the entry was created at + example: '2012-12-12T10:53:43-08:00' + CollaborationAllowlistEntries: + title: Allowed collaboration domains + type: object + x-box-resource-id: collaboration_allowlist_entries + x-box-tag: collaboration_allowlist_entries + description: A list of allowed domains for collaboration. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/CollaborationAllowlistEntry' + CollaborationAllowlistExemptTarget: + title: Allowed collaboration domains user exemption + type: object + x-box-resource-id: collaboration_allowlist_exempt_target + x-box-tag: collaboration_allowlist_exempt_targets + description: The user that is exempt from any of the restrictions imposed by the list of allowed collaboration domains for this enterprise. + properties: + id: + type: string + description: The unique identifier for this exemption + example: '11446498' + type: + type: string + description: '`collaboration_whitelist`' + example: collaboration_whitelist + enum: + - collaboration_whitelist + enterprise: + description: The enterprise this entry belongs to + $ref: '#/components/schemas/CollaborationAllowlistEnterprise' + user: + description: The user that has been exempt + $ref: '#/components/schemas/CollaborationAllowlistUser' + created_at: + type: string + format: date-time + description: The time the entry was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: The time the entry was modified + example: '2012-12-12T10:53:43-08:00' + CollaborationAllowlistExemptTargets: + title: Allowed collaboration domains user exemptions + type: object + x-box-resource-id: collaboration_allowlist_exempt_targets + x-box-tag: collaboration_allowlist_exempt_targets + description: A list of users that is exempt from any of the restrictions imposed by the list of allowed collaboration domains for this enterprise. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/CollaborationAllowlistExemptTarget' + Collection: + title: Collection + type: object + x-box-resource-id: collection + x-box-tag: collections + description: 'A collection of items, including files and folders. Currently, the only collection available is the `favorites` collection. The contents of a collection can be explored in a similar way to which the contents of a folder is explored.' + properties: + id: + type: string + description: The unique identifier for this collection. + example: '11446498' + type: + type: string + description: '`collection`' + example: collection + enum: + - collection + name: + type: string + description: The name of the collection. + enum: + - Favorites + example: Favorites + collection_type: + type: string + description: The type of the collection. This is used to determine the proper visual treatment for collections. + enum: + - favorites + example: favorites + Collections: + title: Collections + type: object + x-box-resource-id: collections + x-box-tag: collections + description: A list of collections + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/Collection' + Comment: + title: Comment + type: object + description: Standard representation of a comment. + x-box-resource-id: comment + x-box-variant: standard + allOf: + - $ref: '#/components/schemas/Comment--Base' + - properties: + is_reply_comment: + type: boolean + description: Whether or not this comment is a reply to another comment + example: true + message: + type: string + example: '@Aaron Levie these tigers are cool!' + description: 'The text of the comment, as provided by the user' + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: A mini user object representing the author of the comment + created_at: + type: string + format: date-time + description: The time this comment was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: The time this comment was last modified + example: '2012-12-12T10:53:43-08:00' + item: + allOf: + - title: Reference + description: The bare basic reference for an object + type: object + properties: + id: + type: string + description: The unique identifier for this object + example: '11446498' + type: + type: string + description: The type for this object + example: file + - description: The file this comment was placed on + Comments: + title: Comments + type: object + x-box-resource-id: comments + x-box-tag: comments + description: A list of comments + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/Comment' + Comment--Base: + title: Comment (Base) + type: object + x-box-resource-id: comment--base + x-box-sanitized: true + x-box-tag: comments + x-box-variants: + - base + - standard + - full + x-box-variant: base + description: Base representation of a comment. + properties: + id: + type: string + description: The unique identifier for this comment. + example: '11446498' + type: + type: string + description: '`comment`' + example: comment + enum: + - comment + Comment--Full: + title: Comment (Full) + type: object + x-box-resource-id: comment--full + x-box-variant: full + description: Comments are messages created on files. Comments can be made independently or created as responses to other comments + allOf: + - $ref: '#/components/schemas/Comment' + - properties: + tagged_message: + type: string + example: '@[1234567:Aaron Levie] these tigers are cool!' + description: 'The string representing the comment text with @mentions included. @mention format is @[id:username] where `id` is user''s Box ID and `username` is their display name.' + DevicePinner: + title: Device pinner + type: object + x-box-resource-id: device_pinner + x-box-tag: device_pinners + description: Device pins allow enterprises to control what devices can use native Box applications. + properties: + id: + type: string + description: The unique identifier for this device pin. + example: '11446498' + type: + type: string + description: '`device_pinner`' + example: device_pinner + enum: + - device_pinner + owned_by: + description: The user that the device pin belongs to + $ref: '#/components/schemas/User--Mini' + product_name: + type: string + description: The type of device being pinned + example: iPad + created_at: + type: string + format: date-time + description: The time the device pin was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: The time the device pin was modified + example: '2012-12-12T10:53:43-08:00' + DevicePinners: + title: Device pinners + type: object + x-box-resource-id: device_pinners + x-box-tag: device_pinners + description: A list of device pins + properties: + entries: + type: array + description: A entries of device pins + items: + $ref: '#/components/schemas/DevicePinner' + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. + default: 100 + example: 200 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + order: + description: The order by which items are returned. + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field that is ordered by + example: id + enum: + - id + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: asc + enum: + - asc + - desc + EmailAlias: + title: Email alias + type: object + x-box-resource-id: email_alias + x-box-tag: email_aliases + description: An email alias for a user. + properties: + id: + type: string + description: The unique identifier for this object + example: '11446498' + type: + type: string + description: Email alias type + example: email_alias + enum: + - email_alias + email: + type: string + description: The email address + example: alias@example.com + is_confirmed: + type: boolean + description: Whether the email address has been confirmed + example: true + EmailAliases: + title: Email aliases + type: object + x-box-resource-id: email_aliases + x-box-tag: email_aliases + description: A list of email aliases + properties: + total_count: + description: The number of email aliases. + example: 5000 + type: integer + format: int64 + entries: + type: array + description: The entries of email alias. + items: + $ref: '#/components/schemas/EmailAlias' + Event: + title: Event + type: object + x-box-resource-id: event + x-box-tag: events + description: The description of an event that happened within Box + properties: + type: + description: '`event`' + type: string + example: event + event_id: + type: string + example: f82c3ba03e41f7e8a7608363cc6c0390183c3f83 + description: The ID of the event object. You can use this to detect duplicate events + created_by: + description: 'The user that performed the action represented by the event. Some events may be performed by users not logged into Box. In that case, not all attributes of the object are populated and the event is attributed to a unknown user (`user_id = 2`)' + $ref: '#/components/schemas/User--Mini' + event_type: + title: Event Type + example: FILE_MARKED_MALICIOUS + type: string + description: An event type that can trigger an event + enum: + - ACCESS_GRANTED + - ACCESS_REVOKED + - ADD_DEVICE_ASSOCIATION + - ADD_LOGIN_ACTIVITY_DEVICE + - ADMIN_LOGIN + - APPLICATION_CREATED + - APPLICATION_PUBLIC_KEY_ADDED + - APPLICATION_PUBLIC_KEY_DELETED + - CHANGE_ADMIN_ROLE + - CHANGE_FOLDER_PERMISSION + - COLLABORATION_ACCEPT + - COLLABORATION_EXPIRATION + - COLLABORATION_INVITE + - COLLABORATION_REMOVE + - COLLABORATION_ROLE_CHANGE + - COLLAB_ADD_COLLABORATOR + - COLLAB_INVITE_COLLABORATOR + - COLLAB_REMOVE_COLLABORATOR + - COLLAB_ROLE_CHANGE + - COMMENT_CREATE + - COMMENT_DELETE + - CONTENT_ACCESS + - CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY + - CONTENT_WORKFLOW_AUTOMATION_ADD + - CONTENT_WORKFLOW_AUTOMATION_DELETE + - CONTENT_WORKFLOW_POLICY_ADD + - CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION + - CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION + - COPY + - DATA_RETENTION_CREATE_RETENTION + - DATA_RETENTION_REMOVE_RETENTION + - DELETE + - DELETE_USER + - DEVICE_TRUST_CHECK_FAILED + - DOWNLOAD + - EDIT + - EDIT_USER + - EMAIL_ALIAS_CONFIRM + - EMAIL_ALIAS_REMOVE + - ENABLE_TWO_FACTOR_AUTH + - ENTERPRISE_APP_AUTHORIZATION_UPDATE + - FAILED_LOGIN + - FILE_MARKED_MALICIOUS + - FILE_WATERMARKED_DOWNLOAD + - GROUP_ADD_ITEM + - GROUP_ADD_USER + - GROUP_CREATION + - GROUP_DELETION + - GROUP_EDITED + - GROUP_REMOVE_ITEM + - GROUP_REMOVE_USER + - ITEM_COPY + - ITEM_CREATE + - ITEM_DOWNLOAD + - ITEM_MAKE_CURRENT_VERSION + - ITEM_MODIFY + - ITEM_MOVE + - ITEM_OPEN + - ITEM_PREVIEW + - ITEM_RENAME + - ITEM_SHARED + - ITEM_SHARED_CREATE + - ITEM_SHARED_UNSHARE + - ITEM_SHARED_UPDATE + - ITEM_SYNC + - ITEM_TRASH + - ITEM_UNDELETE_VIA_TRASH + - ITEM_UNSYNC + - ITEM_UPLOAD + - LEGAL_HOLD_ASSIGNMENT_CREATE + - LEGAL_HOLD_ASSIGNMENT_DELETE + - LEGAL_HOLD_POLICY_CREATE + - LEGAL_HOLD_POLICY_DELETE + - LEGAL_HOLD_POLICY_UPDATE + - LOCK + - LOCK_CREATE + - LOCK_DESTROY + - LOGIN + - MASTER_INVITE_ACCEPT + - MASTER_INVITE_REJECT + - METADATA_INSTANCE_CREATE + - METADATA_INSTANCE_DELETE + - METADATA_INSTANCE_UPDATE + - METADATA_TEMPLATE_CREATE + - METADATA_TEMPLATE_DELETE + - METADATA_TEMPLATE_UPDATE + - MOVE + - NEW_USER + - PREVIEW + - REMOVE_DEVICE_ASSOCIATION + - REMOVE_LOGIN_ACTIVITY_DEVICE + - RENAME + - RETENTION_POLICY_ASSIGNMENT_ADD + - SHARE + - SHARE_EXPIRATION + - SHIELD_ALERT + - SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED + - SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION + - SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED + - SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION + - SHIELD_JUSTIFICATION_APPROVAL + - STORAGE_EXPIRATION + - TAG_ITEM_CREATE + - TASK_ASSIGNMENT_CREATE + - TASK_ASSIGNMENT_DELETE + - TASK_ASSIGNMENT_UPDATE + - TASK_CREATE + - TASK_UPDATE + - TERMS_OF_SERVICE_ACCEPT + - TERMS_OF_SERVICE_REJECT + - UNDELETE + - UNLOCK + - UNSHARE + - UPDATE_COLLABORATION_EXPIRATION + - UPDATE_SHARE_EXPIRATION + - UPLOAD + - USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE + - WATERMARK_LABEL_CREATE + - WATERMARK_LABEL_DELETE + session_id: + type: string + example: 70090280850c8d2a1933c1 + description: The session of the user that performed the action. Not all events will populate this attribute. + source: + oneOf: + - $ref: '#/components/schemas/User' + - $ref: '#/components/schemas/EventSource' + additional_details: + type: object + example: + key: value + description: This object provides additional information about the event if available. This can include how a user performed an event as well as additional information to correlate an event to external KeySafe logs. Not all events have an `additional_details` object. This object is only available in the Enterprise Events. + Events: + title: Events + type: object + x-box-resource-id: events + x-box-tag: events + description: A list of event objects + properties: + chunk_size: + description: The number of events returned in this response. + example: 2 + type: integer + format: int64 + next_stream_position: + description: The stream position of the start of the next page (chunk) of events. + example: '1152922976252290886' + type: string + entries: + type: array + description: The description of an events that happened within Box. + items: + $ref: '#/components/schemas/Event' + File: + title: File + type: object + x-box-resource-id: file + x-box-variant: standard + description: 'A standard representation of a file, as returned from any file API endpoints by default' + allOf: + - $ref: '#/components/schemas/File--Mini' + - properties: + description: + type: string + nullable: false + description: The optional description of this file + maxLength: 256 + example: Contract for Q1 renewal + size: + type: integer + nullable: false + description: The file size in bytes. Be careful parsing this integer as it can get very large and cause an integer overflow. + example: 629644 + path_collection: + allOf: + - title: Path collection + description: A list of parent folders for an item. + type: object + properties: + total_count: + description: The number of folders in this list. + example: 1 + type: integer + format: int64 + nullable: false + entries: + type: array + description: The parent folders for this item + nullable: false + items: + $ref: '#/components/schemas/Folder--Mini' + - description: 'The tree of folders that this file is contained in, starting at the root.' + - nullable: false + created_at: + type: string + format: date-time + nullable: false + description: The date and time when the file was created on Box. + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + nullable: false + description: The date and time when the file was last updated on Box. + example: '2012-12-12T10:53:43-08:00' + trashed_at: + type: string + format: date-time + nullable: true + description: The time at which this file was put in the trash. + example: '2012-12-12T10:53:43-08:00' + purged_at: + type: string + format: date-time + nullable: true + description: The time at which this file is expected to be purged from the trash. + example: '2012-12-12T10:53:43-08:00' + content_created_at: + type: string + format: date-time + nullable: true + description: 'The date and time at which this file was originally created, which might be before it was uploaded to Box.' + example: '2012-12-12T10:53:43-08:00' + content_modified_at: + type: string + format: date-time + nullable: true + description: 'The date and time at which this file was last updated, which might be before it was uploaded to Box.' + example: '2012-12-12T10:53:43-08:00' + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who created this file + modified_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who last modified this file + - nullable: false + owned_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who owns this file + - nullable: false + shared_link: + allOf: + - title: Shared link + description: 'Shared links provide direct, read-only access to files or folder on Box. Shared links with open access level allow anyone with the URL to access the item, while shared links with company or collaborators access levels can only be accessed by appropriately authenticated Box users.' + type: object + properties: + url: + type: string + format: url + description: The URL that can be used to access the item on Box. This URL will display the item in Box's preview UI where the file can be downloaded if allowed. This URL will continue to work even when a custom `vanity_url` has been set for this shared link. + example: 'https://www.box.com/s/vspke7y05sb214wjokpk' + nullable: false + download_url: + type: string + format: url + x-box-premium-feature: true + description: A URL that can be used to download the file. This URL can be used in a browser to download the file. This URL includes the file extension so that the file will be saved with the right file type. This property will be `null` for folders. + example: 'https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg' + nullable: true + vanity_url: + type: string + format: url + description: The "Custom URL" that can also be used to preview the item on Box. Custom URLs can only be created or modified in the Box Web application. + example: 'https://acme.app.box.com/v/my_url/' + nullable: true + vanity_name: + type: string + description: 'The custom name of a shared link, as used in the `vanity_url` field.' + example: my_url + nullable: true + access: + type: string + description: 'The access level for this shared link. * `open` - provides access to this item to anyone with this link * `company` - only provides access to this item to people the same company * `collaborators` - only provides access to this item to people who are collaborators on this item If this field is omitted when creating the shared link, the access level will be set to the default access level specified by the enterprise admin.' + enum: + - open + - company + - collaborators + example: open + nullable: false + effective_access: + type: string + description: The effective access level for the shared link. This can be a more restrictive access level than the value in the `access` field when the enterprise settings restrict the allowed access levels. + enum: + - open + - company + - collaborators + example: company + nullable: false + effective_permission: + type: string + description: The effective permissions for this shared link. + enum: + - can_download + - can_preview + example: can_download + nullable: false + unshared_at: + type: string + format: date-time + description: The date and time when this link will be unshared. This field can only be set by users with paid accounts. + example: '2018-04-13T13:53:23-07:00' + nullable: true + is_password_enabled: + type: boolean + description: Defines if the shared link requires a password to access the item. + example: true + nullable: false + permissions: + type: object + description: Defines if this link allows a user to preview and download an item. + properties: + can_download: + type: boolean + example: true + nullable: false + description: 'Defines if the shared link allows for the item to be downloaded. For shared links on folders, this also applies to any items in the folder. This value can be set to `true` when the effective access level is set to `open` or `company`, not `collaborators`.' + can_preview: + type: boolean + example: true + nullable: false + description: Defines if the shared link allows for the item to be previewed. This value is always `true`. For shared links on folders this also applies to any items in the folder. + download_count: + type: integer + example: 3 + description: The number of times this item has been downloaded. + nullable: false + preview_count: + type: integer + example: 3 + description: The number of times this item has been previewed. + nullable: false + - description: The shared link for this file. This will be `null` if no shared link has been created for this file. + - nullable: true + parent: + allOf: + - $ref: '#/components/schemas/Folder--Mini' + - description: The folder that this file is located within. + nullable: true + item_status: + type: string + description: Defines if this item has been deleted or not. * `active` when the item has is not in the trash * `trashed` when the item has been moved to the trash but not deleted * `deleted` when the item has been permanently deleted. + enum: + - active + - trashed + - deleted + nullable: false + example: active + FileConflict: + title: File (Conflict) + type: object + x-box-sanitized: true + x-box-resource-id: file_conflict + x-box-tag: null + description: A representation of a file that is used to show + allOf: + - $ref: '#/components/schemas/File--Mini' + - properties: + sha1: + type: string + example: 85136C79CBF9FE36BB9D05D0639C70C265C18D37 + description: The SHA1 hash of the file. + file_version: + $ref: '#/components/schemas/FileVersion--Mini' + Files: + title: Files + type: object + x-box-resource-id: files + x-box-tag: files + description: A list of files + properties: + total_count: + description: The number of files. + example: 1 + type: integer + format: int64 + entries: + type: array + description: A list of files + items: + $ref: '#/components/schemas/File' + File--Full: + title: File (Full) + type: object + x-box-resource-id: file--full + x-box-variant: full + description: 'A full representation of a file, as can be returned from any file API endpoints by default' + allOf: + - $ref: '#/components/schemas/File' + - properties: + version_number: + type: string + example: '1' + description: The version number of this file + comment_count: + type: integer + example: 10 + description: The number of comments on this file + permissions: + allOf: + - type: object + description: The permissions that the authenticated user has for a file. + allOf: + - type: object + description: The permissions that the authenticated user has for an item. + properties: + can_delete: + type: boolean + description: Specifies if the current user can delete this item. + example: true + nullable: false + can_download: + type: boolean + description: Specifies if the current user can download this item. + example: true + nullable: false + can_invite_collaborator: + type: boolean + description: 'Specifies if the current user can invite new users to collaborate on this item, and if the user can update the role of a user already collaborated on this item.' + example: true + nullable: false + can_rename: + type: boolean + description: Specifies if the user can rename this item. + example: true + nullable: false + can_set_share_access: + type: boolean + description: Specifies if the user can change the access level of an existing shared link on this item. + example: true + nullable: false + can_share: + type: boolean + description: Specifies if the user can create a shared link for this item. + example: true + nullable: false + - properties: + can_annotate: + type: boolean + description: Specifies if the user can place annotations on this file. + example: true + nullable: false + can_comment: + type: boolean + description: Specifies if the user can place comments on this file. + example: true + nullable: false + can_preview: + type: boolean + description: Specifies if the user can preview this file. + example: true + nullable: false + can_upload: + type: boolean + description: Specifies if the user can upload a new version of this file. + example: true + nullable: false + can_view_annotations_all: + type: boolean + description: Specifies if the user view all annotations placed on this file + example: true + nullable: false + can_view_annotations_self: + type: boolean + description: Specifies if the user view annotations placed by themselves on this file + example: true + nullable: false + - description: Describes the permissions that the current user has for this file. + - nullable: false + tags: + allOf: + - type: array + example: + - approved + items: + type: string + minItems: 1 + maxItems: 100 + description: 'The tags for this item. These tags are shown in the Box web app and mobile apps next to an item. To add or remove a tag, retrieve the item''s current tags, modify them, and then update this field. There is a limit of 100 tags per item, and 10,000 unique tags per enterprise.' + - nullable: false + lock: + allOf: + - title: Lock + type: object + description: 'The lock held on a file. A lock prevents a file from being moved, renamed, or otherwise changed by anyone else than the user who created the lock.' + properties: + id: + type: string + description: The unique identifier for this lock + example: '11446498' + type: + type: string + description: '`lock`' + example: lock + enum: + - lock + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who created the lock. + created_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: The time this lock was created at. + expired_at: + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + description: 'The time this lock is to expire at, which might be in the past.' + is_download_prevented: + type: boolean + example: true + description: Whether or not the file can be downloaded while locked. + - description: 'The lock held on this file. If there is no lock, this can either be `null` or have a timestamp in the past.' + nullable: true + extension: + type: string + example: pdf + description: 'Indicates the (optional) file extension for this file. By default, this is set to an empty string.' + is_package: + type: boolean + example: true + description: Indicates if the file is a package. Packages are commonly used by Mac Applications and can include iWork files. + expiring_embed_link: + allOf: + - title: Expiring embed link + type: object + description: An expiring Box Embed Link. + allOf: + - type: object + description: The basics of an access token + properties: + access_token: + type: string + format: token + example: c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ + description: The requested access token. + expires_in: + type: integer + format: int64 + example: 3600 + description: The time in seconds in seconds by which this token will expire. + token_type: + type: string + enum: + - bearer + example: bearer + description: The type of access token returned. + restricted_to: + type: array + description: 'The permissions that this access token permits, providing a list of resources (files, folders, etc) and the scopes permitted for each of those resources.' + items: + $ref: '#/components/schemas/FileScope' + - properties: + url: + type: string + format: url + example: 'https://cloud.app.box.com/preview/expiring_embed/...' + description: 'The actual expiring embed URL for this file, constructed from the file ID and access tokens specified in this object.' + - description: 'Requesting this field creates an expiring Box Embed URL for an embedded preview session in an `iframe`. This URL will expire after 60 seconds and the session will expire after 60 minutes. Not all file types are supported for these embed URLs. Box Embed is not optimized for mobile browsers and should not be used in web experiences designed for mobile devices. Many UI elements, like the **download** and **print** options might not show in mobile browsers.' + watermark_info: + allOf: + - type: object + description: Details about the watermark applied to this item + properties: + is_watermarked: + type: boolean + description: Specifies if this item has a watermark applied. + example: true + nullable: false + - description: Details about the watermark applied to this file + allowed_invitee_roles: + type: array + example: + - editor + nullable: false + description: A list of the types of roles that user can be invited at when sharing this file. + items: + type: string + enum: + - editor + - viewer + - previewer + - uploader + - previewer uploader + - viewer uploader + - co-owner + is_externally_owned: + type: boolean + example: true + nullable: false + description: Specifies if this file is owned by a user outside of the authenticated enterprise. + has_collaborations: + type: boolean + example: true + nullable: false + description: Specifies if this file has any other collaborators. + metadata: + allOf: + - title: Item metadata instances + type: object + description: 'A list of metadata instances, nested within key-value pairs of their `scope` and `templateKey`. To access the metadata for a file or folder, first use the metadata endpoints to determine the metadata templates available to your enterprise. Then use the `GET /files/:id` or `GET /folder/:id` endpoint with the `fields` query parameter to get the metadata by ID. To request a metadata instance for a particular `scope` and `templateKey` use the following format for the `fields` parameter: `metadata..` For example, `?fields=metadata.enterprise_27335.marketingCollateral`.' + example: + enterprise_27335: + marketingCollateral: + $canEdit: true + $id: 01234500-12f1-1234-aa12-b1d234cb567e + $parent: folder_59449484661 + $scope: enterprise_27335 + $template: marketingCollateral + $type: properties-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0 + $typeVersion: 2 + $version: 1 + additionalProperties: + type: object + description: 'A list of metadata instances, nested within key-value pairs of their `scope` and `templateKey`.' + example: + marketingCollateral: + $canEdit: true + $id: 01234500-12f1-1234-aa12-b1d234cb567e + $parent: folder_59449484661 + $scope: enterprise_27335 + $template: marketingCollateral + $type: properties-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0 + $typeVersion: 2 + $version: 1 + additionalProperties: + $ref: '#/components/schemas/Metadata' + - description: 'An object containing the metadata instances that have been attached to this file. Each metadata instance is uniquely identified by its `scope` and `templateKey`. There can only be one instance of any metadata template attached to each file. Each metadata instance is nested within an object with the `templateKey` as the key, which again itself is nested in an object with the `scope` as the key.' + expires_at: + type: string + format: date-time + nullable: true + description: When the file will automatically be deleted + example: '2012-12-12T10:53:43-08:00' + representations: + allOf: + - title: Representations + description: A list of file representations + type: object + properties: + entries: + type: array + description: A list of files + items: + type: object + description: A file representation + properties: + content: + type: object + description: An object containing the URL that can be used to actually fetch the representation. + properties: + url_template: + type: string + example: 'https://dl.boxcloud.com/api/2.0/internal_files/123/versions/345/representations/png_paged_2048x2048/content/{+asset_path}?watermark_content=4567' + description: 'The download URL that can be used to fetch the representation. Make sure to make an authenticated API call to this endpoint. This URL is a template and will require the `{+asset_path}` to be replaced by a path. In general, for unpaged representations it can be replaced by an empty string. For paged representations, replace the `{+asset_path}` with the page to request plus the extension for the file, for example `1.pdf`. When requesting the download URL the following additional query params can be passed along. * `set_content_disposition_type` - Sets the `Content-Disposition` header in the API response with the specified disposition type of either `inline` or `attachment`. If not supplied, the `Content-Disposition` header is not included in the response. * `set_content_disposition_filename` - Allows the application to define the representation''s file name used in the `Content-Disposition` header. If not defined, the filename is derived from the source file name in Box combined with the extension of the representation.' + info: + type: object + description: An object containing the URL that can be used to fetch more info on this representation. + properties: + url: + type: string + example: 'https://api.box.com/2.0/internal_files/123/versions/345/representations/png_paged_2048x2048' + description: The API URL that can be used to get more info on this file representation. Make sure to make an authenticated API call to this endpoint. + properties: + type: object + description: An object containing the size and type of this presentation. + properties: + dimensions: + type: string + format: x + example: 2048x2048 + description: The width by height size of this representation in pixels. + paged: + type: boolean + example: true + description: Indicates if the representation is build up out of multiple pages. + thumb: + type: boolean + example: true + description: Indicates if the representation can be used as a thumbnail of the file. + representation: + type: string + example: png + description: Indicates the file type of the returned representation. + status: + type: object + description: An object containing the status of this representation. + properties: + state: + type: string + example: success + enum: + - success + - viewable + - pending + - none + description: The status of the representation. * `success` defines the representation as ready to be viewed. * `viewable` defines a video to be ready for viewing. * `pending` defines the representation as to be generated. Retry this endpoint to re-check the status. * `none` defines that the representation will be created when requested. Request the URL defined in the `info` object to trigger this generation. + - description: A list of representations for a file that can be used to display a placeholder of the file in your application. By default this returns all representations and we recommend using the `X-Rep-Hints` header to further customize the desired representations. + classification: + allOf: + - type: object + description: The classification applied to an item + properties: + name: + type: string + example: Top Secret + description: The name of the classification + definition: + type: string + example: Content that should not be shared outside the company. + description: An explanation of the meaning of this classification. + color: + type: string + example: '#FF0000' + description: The color that is used to display the classification label in a user-interface. Colors are defined by the admin or co-admin who created the classification in the Box web app. + - description: Details about the classification applied to this file. + - nullable: true + uploader_display_name: + allOf: + - title: Uploader display name + type: string + example: Ellis Wiggins + nullable: false + description: 'The display name of the user that uploaded the file. In most cases this is the name of the user logged in at the time of the upload. If the file was uploaded using a File Request form that requires the user to provide an email address, this field is populated with that email address. If an email address was not required in the File Request form, this field is set to return a value of `File Request`. In all other anonymous cases where no email was provided this field will default to a value of `Someone`.' + File--Mini: + title: File (Mini) + type: object + x-box-resource-id: file--mini + x-box-variant: mini + description: 'A mini representation of a file, used when nested under another resource.' + allOf: + - $ref: '#/components/schemas/File--Base' + - properties: + sequence_id: + allOf: + - type: string + example: '3' + nullable: false + description: 'A numeric identifier that represents the most recent user event that has been applied to this item. This can be used in combination with the `GET /events`-endpoint to filter out user events that would have occurred before this identifier was read. An example would be where a Box Drive-like application would fetch an item via the API, and then listen to incoming user events for changes to the item. The application would ignore any user events where the `sequence_id` in the event is smaller than or equal to the `sequence_id` in the originally fetched resource.' + - nullable: false + name: + type: string + description: The name of the file + example: Contract.pdf + sha1: + type: string + format: digest + nullable: false + example: 85136C79CBF9FE36BB9D05D0639C70C265C18D37 + description: The SHA1 hash of the file. This can be used to compare the contents of a file on Box with a local file. + file_version: + allOf: + - $ref: '#/components/schemas/FileVersion--Mini' + - description: The information about the current version of the file. + File--Base: + title: File (Base) + type: object + x-box-resource-id: file--base + x-box-sanitized: true + x-box-tag: files + x-box-variants: + - base + - mini + - standard + - full + x-box-variant: base + description: 'The bare basic representation of a file, the minimal amount of fields returned when using the `fields` query parameter.' + properties: + id: + type: string + nullable: false + description: 'The unique identifier that represent a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`.' + example: '12345' + etag: + type: string + example: '1' + nullable: true + description: The HTTP `etag` of this file. This can be used within some API endpoints in the `If-Match` and `If-None-Match` headers to only perform changes on the file if (no) changes have happened. + type: + type: string + description: '`file`' + example: file + enum: + - file + nullable: false + FileRequest: + title: File Request + type: object + x-box-resource-id: file_request + x-box-tag: file_requests + description: 'A standard representation of a file request, as returned from any file request API endpoints by default.' + properties: + id: + type: string + description: The unique identifier for this file request. + readOnly: true + example: '42037322' + type: + type: string + description: '`file-request`' + example: file-request + enum: + - file-request + readOnly: true + title: + type: string + description: The title of file request. This is shown in the Box UI to users uploading files. This defaults to title of the file request that was copied to create this file request. + example: Please upload documents + description: + type: string + nullable: true + description: The optional description of this file request. This is shown in the Box UI to users uploading files. This defaults to description of the file request that was copied to create this file request. + example: Following documents are requested for your process + status: + type: string + example: active + description: 'The status of the file request. This defaults to `active`. When the status is set to `inactive`, the file request will no longer accept new submissions, and any visitor to the file request URL will receive a `HTTP 404` status code. This defaults to status of file request that was copied to create this file request.' + enum: + - active + - inactive + is_email_required: + type: boolean + example: true + description: 'Whether a file request submitter is required to provide their email address. When this setting is set to true, the Box UI will show an email field on the file request form. This defaults to setting of file request that was copied to create this file request.' + is_description_required: + type: boolean + example: true + description: 'Whether a file request submitter is required to provide a description of the files they are submitting. When this setting is set to true, the Box UI will show a description field on the file request form. This defaults to setting of file request that was copied to create this file request.' + expires_at: + type: string + format: date-time + description: 'The date after which a file request will no longer accept new submissions. After this date, the `status` will automatically be set to `inactive`.' + example: '2020-09-28T10:53:43-08:00' + folder: + description: The folder that this file request is associated with. Files submitted through the file request form will be uploaded to this folder. + $ref: '#/components/schemas/Folder--Mini' + nullable: false + url: + type: string + description: The generated URL for this file request. This URL can be shared with users to let them upload files to the associated folder. + example: 'https://cloud.app.box.com/f/19e57f40ace247278a8e3d336678c64a' + readOnly: true + etag: + type: string + example: '1' + nullable: true + description: 'The HTTP `etag` of this file. This can be used in combination with the `If-Match` header when updating a file request. By providing that header, a change will only be performed on the file request if the `etag` on the file request still matches the `etag` provided in the `If-Match` header.' + created_by: + description: The user who created this file request. + $ref: '#/components/schemas/User--Mini' + created_at: + type: string + format: date-time + nullable: false + description: The date and time when the file request was created. + example: '2020-09-28T10:53:43-08:00' + updated_by: + description: The user who last modified this file request. + $ref: '#/components/schemas/User--Mini' + updated_at: + type: string + format: date-time + nullable: false + description: The date and time when the file request was last updated. + example: '2020-09-28T10:53:43-08:00' + FileVersion: + title: File version + type: object + x-box-resource-id: file_version + x-box-variant: standard + description: A standard representation of a file version + allOf: + - $ref: '#/components/schemas/FileVersion--Mini' + - properties: + name: + type: string + description: The name of the file version + example: tigers.jpeg + size: + type: integer + format: int64 + description: Size of the file version in bytes + example: 629644 + created_at: + type: string + format: date-time + description: When the file version object was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the file version object was last updated + example: '2012-12-12T10:53:43-08:00' + modified_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who last updated the file version + trashed_at: + type: string + description: When the file version object was trashed. + format: date-time + nullable: true + example: '2012-12-12T10:53:43-08:00' + trashed_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who trashed the file version + restored_at: + type: string + description: When the file version was restored from the trash. + format: date-time + nullable: true + example: '2012-12-12T10:53:43-08:00' + restored_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who restored the file version from the trash. + purged_at: + type: string + description: When the file version object will be permanently deleted. + format: date-time + nullable: true + example: '2012-12-12T10:53:43-08:00' + uploader_display_name: + allOf: + - title: Uploader display name + type: string + example: Ellis Wiggins + nullable: false + description: 'The display name of the user that uploaded the file. In most cases this is the name of the user logged in at the time of the upload. If the file was uploaded using a File Request form that requires the user to provide an email address, this field is populated with that email address. If an email address was not required in the File Request form, this field is set to return a value of `File Request`. In all other anonymous cases where no email was provided this field will default to a value of `Someone`.' + FileVersion--Mini: + title: File version (Mini) + type: object + x-box-resource-id: file_version--mini + x-box-variant: mini + description: 'A mini representation of a file version, used when nested within another resource.' + allOf: + - $ref: '#/components/schemas/FileVersion--Base' + - properties: + sha1: + type: string + description: The SHA1 hash of this version of the file. + example: 134b65991ed521fcfe4724b7d814ab8ded5185dc + FileVersion--Base: + title: File version (Base) + type: object + x-box-resource-id: file_version--base + x-box-sanitized: true + x-box-variants: + - base + - mini + - standard + x-box-variant: base + description: 'The bare basic representation of a file version, the minimal amount of fields returned when using the `fields` query parameter.' + properties: + id: + type: string + nullable: false + description: The unique identifier that represent a file version. + example: '12345' + type: + type: string + description: '`file_version`' + example: file_version + enum: + - file_version + nullable: false + FileVersions: + title: File versions + type: object + x-box-resource-id: file_versions + x-box-tag: file_versions + description: A list of file versions + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/FileVersion' + FileVersionLegalHold: + title: File version legal hold + type: object + x-box-resource-id: file_version_legal_hold + x-box-tag: file_version_legal_holds + description: File-Version-Legal-Hold is an entity representing all holds on a File Version. + properties: + id: + type: string + description: The unique identifier for this file version legal hold + example: '11446498' + type: + type: string + description: '`file_version_legal_hold`' + example: file_version_legal_hold + enum: + - file_version_legal_hold + file_version: + description: The file version this file version retention was applied to + $ref: '#/components/schemas/FileVersion--Mini' + file: + description: The file this file version retention was applied to + $ref: '#/components/schemas/File--Mini' + legal_hold_policy_assignments: + description: List of assignments contributing to this Hold. + type: array + items: + $ref: '#/components/schemas/LegalHoldPolicyAssignment' + deleted_at: + type: string + format: date-time + description: Time that this File-Version-Legal-Hold was deleted. + example: '2012-12-12T10:53:43-08:00' + FileVersionLegalHolds: + title: File version legal holds + type: object + x-box-resource-id: file_version_legal_holds + x-box-tag: file_version_legal_holds + description: A list of file version legal holds. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/FileVersionLegalHold' + FileVersionRetention: + title: File version retention + type: object + x-box-resource-id: file_version_retention + x-box-tag: file_version_retentions + description: 'A retention policy blocks permanent deletion of content for a specified amount of time. Admins can apply policies to specified folders, or an entire enterprise. A file version retention is a record for a retained file version. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. For more information about retention policies, please visit our help documentation' + properties: + id: + type: string + description: The unique identifier for this file version retention. + example: '11446498' + type: + type: string + description: '`file_version_retention`' + example: file_version_retention + enum: + - file_version_retention + file_version: + description: The file version this file version retention was applied to + $ref: '#/components/schemas/FileVersion--Mini' + file: + description: The file this file version retention was applied to + $ref: '#/components/schemas/File--Mini' + applied_at: + type: string + format: date-time + description: When this file version retention object was created + example: '2012-12-12T10:53:43-08:00' + disposition_at: + type: string + format: date-time + description: When the retention expires on this file version retention + example: '2012-12-12T10:53:43-08:00' + winning_retention_policy: + description: The winning retention policy applied to this file version retention. A file version can have multiple retention policies applied. + $ref: '#/components/schemas/RetentionPolicy--Mini' + FileVersionRetentions: + title: File version retentions + type: object + x-box-resource-id: file_version_retentions + x-box-tag: file_version_retentions + description: A list of file version retentions. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/FileVersionRetention' + Folder: + title: Folder + type: object + x-box-resource-id: folder + x-box-variant: standard + description: 'A standard representation of a folder, as returned from any folder API endpoints by default' + allOf: + - $ref: '#/components/schemas/Folder--Mini' + - properties: + created_at: + type: string + format: date-time + nullable: true + description: The date and time when the folder was created. This value may be `null` for some folders such as the root folder or the trash folder. + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: The date and time when the folder was last updated. This value may be `null` for some folders such as the root folder or the trash folder. + example: '2012-12-12T10:53:43-08:00' + nullable: true + description: + allOf: + - type: string + description: The optional description of this folder + maxLength: 256 + example: Legal contracts for the new ACME deal + nullable: false + - nullable: false + size: + type: integer + format: int64 + description: The folder size in bytes. Be careful parsing this integer as its value can get very large. + example: 629644 + nullable: false + path_collection: + allOf: + - title: Path collection + description: A list of parent folders for an item. + type: object + properties: + total_count: + description: The number of folders in this list. + example: 1 + type: integer + format: int64 + nullable: false + entries: + type: array + description: The parent folders for this item + nullable: false + items: + $ref: '#/components/schemas/Folder--Mini' + - description: 'The tree of folders that this folder is contained in, starting at the root.' + - nullable: false + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who created this folder + - nullable: false + modified_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who last modified this folder. + - nullable: false + trashed_at: + type: string + format: date-time + description: The time at which this folder was put in the trash. + example: '2012-12-12T10:53:43-08:00' + nullable: true + purged_at: + type: string + format: date-time + description: The time at which this folder is expected to be purged from the trash. + example: '2012-12-12T10:53:43-08:00' + nullable: true + content_created_at: + type: string + format: date-time + nullable: true + description: The date and time at which this folder was originally created. + example: '2012-12-12T10:53:43-08:00' + content_modified_at: + type: string + format: date-time + nullable: true + description: The date and time at which this folder was last updated. + example: '2012-12-12T10:53:43-08:00' + expires_at: + type: string + format: date-time + nullable: true + description: The time and which the folder will be automatically be deleted. + example: '2012-12-12T10:53:43-08:00' + owned_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who owns this folder. + - nullable: false + shared_link: + allOf: + - title: Shared link + description: 'Shared links provide direct, read-only access to files or folder on Box. Shared links with open access level allow anyone with the URL to access the item, while shared links with company or collaborators access levels can only be accessed by appropriately authenticated Box users.' + type: object + properties: + url: + type: string + format: url + description: The URL that can be used to access the item on Box. This URL will display the item in Box's preview UI where the file can be downloaded if allowed. This URL will continue to work even when a custom `vanity_url` has been set for this shared link. + example: 'https://www.box.com/s/vspke7y05sb214wjokpk' + nullable: false + download_url: + type: string + format: url + x-box-premium-feature: true + description: A URL that can be used to download the file. This URL can be used in a browser to download the file. This URL includes the file extension so that the file will be saved with the right file type. This property will be `null` for folders. + example: 'https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg' + nullable: true + vanity_url: + type: string + format: url + description: The "Custom URL" that can also be used to preview the item on Box. Custom URLs can only be created or modified in the Box Web application. + example: 'https://acme.app.box.com/v/my_url/' + nullable: true + vanity_name: + type: string + description: 'The custom name of a shared link, as used in the `vanity_url` field.' + example: my_url + nullable: true + access: + type: string + description: 'The access level for this shared link. * `open` - provides access to this item to anyone with this link * `company` - only provides access to this item to people the same company * `collaborators` - only provides access to this item to people who are collaborators on this item If this field is omitted when creating the shared link, the access level will be set to the default access level specified by the enterprise admin.' + enum: + - open + - company + - collaborators + example: open + nullable: false + effective_access: + type: string + description: The effective access level for the shared link. This can be a more restrictive access level than the value in the `access` field when the enterprise settings restrict the allowed access levels. + enum: + - open + - company + - collaborators + example: company + nullable: false + effective_permission: + type: string + description: The effective permissions for this shared link. + enum: + - can_download + - can_preview + example: can_download + nullable: false + unshared_at: + type: string + format: date-time + description: The date and time when this link will be unshared. This field can only be set by users with paid accounts. + example: '2018-04-13T13:53:23-07:00' + nullable: true + is_password_enabled: + type: boolean + description: Defines if the shared link requires a password to access the item. + example: true + nullable: false + permissions: + type: object + description: Defines if this link allows a user to preview and download an item. + properties: + can_download: + type: boolean + example: true + nullable: false + description: 'Defines if the shared link allows for the item to be downloaded. For shared links on folders, this also applies to any items in the folder. This value can be set to `true` when the effective access level is set to `open` or `company`, not `collaborators`.' + can_preview: + type: boolean + example: true + nullable: false + description: Defines if the shared link allows for the item to be previewed. This value is always `true`. For shared links on folders this also applies to any items in the folder. + download_count: + type: integer + example: 3 + description: The number of times this item has been downloaded. + nullable: false + preview_count: + type: integer + example: 3 + description: The number of times this item has been previewed. + nullable: false + - description: The shared link for this folder. This will be `null` if no shared link has been created for this folder. + nullable: true + folder_upload_email: + type: object + nullable: true + properties: + access: + type: string + example: open + nullable: false + enum: + - open + - collaborators + description: 'When this parameter has been set, users can email files to the email address that has been automatically created for this folder. To create an email address, set this property either when creating or updating the folder. When set to `collaborators`, only emails from registered email addresses for collaborators will be accepted. This includes any email aliases a user might have registered. When set to `open` it will accept emails from any email address.' + email: + description: The optional upload email address for this folder. + type: string + format: email + example: upload.Contracts.asd7asd@u.box.com + nullable: false + parent: + allOf: + - $ref: '#/components/schemas/Folder--Mini' + - description: The optional folder that this folder is located within. This value may be `null` for some folders such as the root folder or the trash folder. + nullable: true + item_status: + type: string + description: Defines if this item has been deleted or not. * `active` when the item has is not in the trash * `trashed` when the item has been moved to the trash but not deleted * `deleted` when the item has been permanently deleted. + enum: + - active + - trashed + - deleted + nullable: false + example: active + item_collection: + allOf: + - $ref: '#/components/schemas/Items' + - description: 'A page of the items that are in the folder. This field can only be requested when querying a folder''s information, not when querying a folder''s items.' + - nullable: false + Folder--Full: + title: Folder (Full) + type: object + x-box-resource-id: folder--full + x-box-variant: full + description: 'A full representation of a folder, as can be returned from any folder API endpoints by default' + allOf: + - $ref: '#/components/schemas/Folder' + - properties: + sync_state: + allOf: + - type: string + example: synced + nullable: false + description: Specifies whether a folder should be synced to a user's device or not. This is used by Box Sync (discontinued) and is not used by Box Drive. + enum: + - synced + - not_synced + - partially_synced + has_collaborations: + type: boolean + example: true + nullable: false + description: Specifies if this folder has any other collaborators. + permissions: + allOf: + - type: object + description: The permissions that the authenticated user has for a folder. + allOf: + - type: object + description: The permissions that the authenticated user has for an item. + properties: + can_delete: + type: boolean + description: Specifies if the current user can delete this item. + example: true + nullable: false + can_download: + type: boolean + description: Specifies if the current user can download this item. + example: true + nullable: false + can_invite_collaborator: + type: boolean + description: 'Specifies if the current user can invite new users to collaborate on this item, and if the user can update the role of a user already collaborated on this item.' + example: true + nullable: false + can_rename: + type: boolean + description: Specifies if the user can rename this item. + example: true + nullable: false + can_set_share_access: + type: boolean + description: Specifies if the user can change the access level of an existing shared link on this item. + example: true + nullable: false + can_share: + type: boolean + description: Specifies if the user can create a shared link for this item. + example: true + nullable: false + - properties: + can_upload: + type: boolean + description: Specifies if the user can upload into this folder. + example: true + nullable: false + - description: Describes the permissions that the current user has for this folder + - nullable: false + tags: + allOf: + - type: array + example: + - approved + items: + type: string + minItems: 1 + maxItems: 100 + description: 'The tags for this item. These tags are shown in the Box web app and mobile apps next to an item. To add or remove a tag, retrieve the item''s current tags, modify them, and then update this field. There is a limit of 100 tags per item, and 10,000 unique tags per enterprise.' + - nullable: false + can_non_owners_invite: + allOf: + - type: boolean + example: true + description: Specifies if users who are not the owner of the folder can invite new collaborators to the folder. + - nullable: false + is_externally_owned: + type: boolean + example: true + nullable: false + description: Specifies if this folder is owned by a user outside of the authenticated enterprise. + metadata: + allOf: + - title: Item metadata instances + type: object + description: 'A list of metadata instances, nested within key-value pairs of their `scope` and `templateKey`. To access the metadata for a file or folder, first use the metadata endpoints to determine the metadata templates available to your enterprise. Then use the `GET /files/:id` or `GET /folder/:id` endpoint with the `fields` query parameter to get the metadata by ID. To request a metadata instance for a particular `scope` and `templateKey` use the following format for the `fields` parameter: `metadata..` For example, `?fields=metadata.enterprise_27335.marketingCollateral`.' + example: + enterprise_27335: + marketingCollateral: + $canEdit: true + $id: 01234500-12f1-1234-aa12-b1d234cb567e + $parent: folder_59449484661 + $scope: enterprise_27335 + $template: marketingCollateral + $type: properties-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0 + $typeVersion: 2 + $version: 1 + additionalProperties: + type: object + description: 'A list of metadata instances, nested within key-value pairs of their `scope` and `templateKey`.' + example: + marketingCollateral: + $canEdit: true + $id: 01234500-12f1-1234-aa12-b1d234cb567e + $parent: folder_59449484661 + $scope: enterprise_27335 + $template: marketingCollateral + $type: properties-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0 + $typeVersion: 2 + $version: 1 + additionalProperties: + $ref: '#/components/schemas/Metadata' + - description: 'An object containing the metadata instances that have been attached to this folder. Each metadata instance is uniquely identified by its `scope` and `templateKey`. There can only be one instance of any metadata template attached to each folder. Each metadata instance is nested within an object with the `templateKey` as the key, which again itself is nested in an object with the `scope` as the key.' + is_collaboration_restricted_to_enterprise: + allOf: + - type: boolean + example: true + description: Specifies if new invites to this folder are restricted to users within the enterprise. This does not affect existing collaborations. + - nullable: false + allowed_shared_link_access_levels: + type: array + example: + - open + items: + type: string + enum: + - open + - company + - collaborators + nullable: false + description: 'A list of access levels that are available for this folder. For some folders, like the root folder, this will always be an empty list as sharing is not allowed at that level.' + allowed_invitee_roles: + type: array + example: + - editor + nullable: false + description: A list of the types of roles that user can be invited at when sharing this folder. + items: + type: string + enum: + - editor + - viewer + - previewer + - uploader + - previewer uploader + - viewer uploader + - co-owner + watermark_info: + allOf: + - type: object + description: Details about the watermark applied to this item + properties: + is_watermarked: + type: boolean + description: Specifies if this item has a watermark applied. + example: true + nullable: false + - description: Details about the watermark applied to this folder + - nullable: false + can_non_owners_view_collaborators: + type: boolean + example: true + description: Specifies if collaborators who are not owners of this folder are restricted from viewing other collaborations on this folder. It also restricts non-owners from inviting new collaborators. + classification: + allOf: + - type: object + description: The classification applied to an item + properties: + name: + type: string + example: Top Secret + description: The name of the classification + definition: + type: string + example: Content that should not be shared outside the company. + description: An explanation of the meaning of this classification. + color: + type: string + example: '#FF0000' + description: The color that is used to display the classification label in a user-interface. Colors are defined by the admin or co-admin who created the classification in the Box web app. + - description: Details about the classification applied to this folder. + - nullable: true + Folder--Mini: + title: Folder (Mini) + type: object + x-box-resource-id: folder--mini + x-box-variant: mini + description: 'A mini representation of a file version, used when nested under another resource.' + allOf: + - $ref: '#/components/schemas/Folder--Base' + - properties: + sequence_id: + allOf: + - type: string + example: '3' + nullable: false + description: 'A numeric identifier that represents the most recent user event that has been applied to this item. This can be used in combination with the `GET /events`-endpoint to filter out user events that would have occurred before this identifier was read. An example would be where a Box Drive-like application would fetch an item via the API, and then listen to incoming user events for changes to the item. The application would ignore any user events where the `sequence_id` in the event is smaller than or equal to the `sequence_id` in the originally fetched resource.' + - nullable: false + name: + type: string + description: The name of the folder. + example: Contracts + nullable: false + Folder--Base: + title: Folder (Base) + type: object + x-box-resource-id: folder--base + x-box-sanitized: true + x-box-tag: folders + x-box-variants: + - base + - mini + - standard + - full + x-box-variant: base + description: 'The bare basic representation of a folder, the minimal amount of fields returned when using the `fields` query parameter.' + properties: + id: + type: string + nullable: false + description: 'The unique identifier that represent a folder. The ID for any folder can be determined by visiting a folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folders/123` the `folder_id` is `123`.' + example: '12345' + etag: + type: string + nullable: true + example: '1' + description: The HTTP `etag` of this folder. This can be used within some API endpoints in the `If-Match` and `If-None-Match` headers to only perform changes on the folder if (no) changes have happened. + type: + type: string + description: '`folder`' + example: folder + enum: + - folder + nullable: false + FolderLock: + title: Folder Lock + type: object + x-box-resource-id: folder_lock + x-box-tag: folder_locks + description: Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. + properties: + folder: + description: The folder that the lock applies to. + $ref: '#/components/schemas/Folder--Mini' + id: + type: string + description: The unique identifier for this folder lock. + example: '12345678' + type: + type: string + description: 'The object type, always `folder_lock`.' + example: folder_lock + created_by: + description: The user or group that created the lock. + $ref: '#/components/schemas/User--Base' + created_at: + type: string + format: date-time + example: '2020-09-14T23:12:53Z' + description: When the folder lock object was created. + locked_operations: + type: object + description: 'The operations that have been locked. Currently the `move` and `delete` operations cannot be locked separately, and both need to be set to `true`. ' + properties: + move: + type: boolean + description: Whether moving the folder is restricted. + nullable: false + example: true + delete: + type: boolean + description: Whether deleting the folder is restricted. + nullable: false + example: true + lock_type: + type: string + description: 'The lock type, always `freeze`.' + example: freeze + FolderLocks: + title: Folder Locks + type: object + x-box-resource-id: folder_locks + x-box-tag: folder_locks + description: A list of folder locks + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/FolderLock' + Group: + title: Group + type: object + x-box-resource-id: group + x-box-variant: standard + description: 'A standard representation of a group, as returned from any group API endpoints by default' + allOf: + - $ref: '#/components/schemas/Group--Mini' + - properties: + created_at: + type: string + format: date-time + description: When the group object was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the group object was last modified + example: '2012-12-12T10:53:43-08:00' + Groups: + title: Groups + type: object + x-box-resource-id: groups + x-box-tag: groups + description: A list of groups. + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/Group--Mini' + Group--Base: + title: Group (Base) + type: object + x-box-resource-id: group--base + x-box-sanitized: true + x-box-tag: groups + x-box-variants: + - base + - mini + - standard + - full + x-box-variant: base + description: A base representation of a group. + properties: + id: + type: string + description: The unique identifier for this object + example: '11446498' + type: + type: string + description: '`group`' + example: group + enum: + - group + Group--Full: + title: Group (Full) + type: object + x-box-resource-id: group--full + x-box-variant: full + description: 'Groups contain a set of users, and can be used in place of users in some operations, such as collaborations.' + allOf: + - $ref: '#/components/schemas/Group' + - properties: + provenance: + type: string + description: 'Keeps track of which external source this group is coming from (e.g. "Active Directory", "Google Groups", "Facebook Groups"). Setting this will also prevent Box users from editing the group name and its members directly via the Box web application. This is desirable for one-way syncing of groups.' + maxLength: 255 + example: Active Directory + external_sync_identifier: + type: string + description: An arbitrary identifier that can be used by external group sync tools to link this Box Group to an external group. Example values of this field could be an Active Directory Object ID or a Google Group ID. We recommend you use of this field in order to avoid issues when group names are updated in either Box or external systems. + example: 'AD:123456' + description: + type: string + description: Human readable description of the group. + maxLength: 255 + example: Support Group - as imported from Active Directory + invitability_level: + type: string + example: admins_only + description: 'Specifies who can invite the group to collaborate on items. When set to `admins_only` the enterprise admin, co-admins, and the group''s admin can invite the group. When set to `admins_and_members` all the admins listed above and group members can invite the group. When set to `all_managed_users` all managed users in the enterprise can invite the group.' + enum: + - admins_only + - admins_and_members + - all_managed_users + member_viewability_level: + type: string + example: admins_only + description: 'Specifies who can view the members of the group (Get Memberships for Group). * `admins_only` - the enterprise admin, co-admins, group''s group admin * `admins_and_members` - all admins and group members * `all_managed_users` - all managed users in the enterprise' + enum: + - admins_only + - admins_and_members + - all_managed_users + permissions: + allOf: + - type: object + description: The permissions that the authenticated user has for a group. + properties: + can_invite_as_collaborator: + type: boolean + description: Specifies if the user can invite the group to collaborate on any items. + example: true + - description: Describes the permissions that the current user has for this group. + Group--Mini: + title: Group (Mini) + type: object + x-box-resource-id: group--mini + x-box-variant: mini + description: 'Mini representation of a group, including id and name of group.' + allOf: + - $ref: '#/components/schemas/Group--Base' + - properties: + name: + type: string + description: The name of the group + example: Support + group_type: + type: string + description: The type of the group. + example: managed_group + enum: + - managed_group + - all_users_group + GroupMembership: + title: Group membership + type: object + x-box-resource-id: group_membership + x-box-tag: memberships + description: Membership is used to signify that a user is part of a group. + properties: + id: + type: string + description: The unique identifier for this group membership + example: '11446498' + type: + type: string + description: '`group_membership`' + example: group_membership + enum: + - group_membership + user: + description: The user that the membership applies to + $ref: '#/components/schemas/User--Mini' + group: + description: The group that the membership applies to + $ref: '#/components/schemas/Group--Mini' + role: + type: string + example: member + description: The role of the user in the group. + enum: + - member + - admin + created_at: + type: string + format: date-time + description: The time this membership was created. + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: The time this membership was last modified. + example: '2012-12-12T10:53:43-08:00' + GroupMemberships: + title: Group memberships + type: object + x-box-resource-id: group_memberships + x-box-tag: memberships + description: A list of group memberships. + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/GroupMembership' + Invite: + title: Invite + type: object + x-box-resource-id: invite + x-box-tag: invites + description: An invite for a user to an enterprise. + properties: + id: + type: string + description: The unique identifier for this invite + example: '11446498' + type: + type: string + description: '`invite`' + example: invite + enum: + - invite + invited_to: + title: Enterprise + type: object + description: A representation of a Box enterprise + properties: + id: + type: string + description: The unique identifier for this enterprise. + example: '11446498' + type: + type: string + description: '`enterprise`' + example: enterprise + enum: + - enterprise + name: + description: The name of the enterprise + example: Acme Inc. + type: string + actionable_by: + $ref: '#/components/schemas/User--Mini' + invited_by: + $ref: '#/components/schemas/User--Mini' + status: + description: The status of the invite + type: string + example: pending + created_at: + type: string + format: date-time + description: When the invite was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the invite was modified. + example: '2012-12-12T10:53:43-08:00' + Items: + title: Items + type: object + x-box-resource-id: items + x-box-tag: folders + description: 'A list of files, folders, and web links in their mini representation.' + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + description: The items in this collection. + type: array + items: + oneOf: + - $ref: '#/components/schemas/File--Mini' + - $ref: '#/components/schemas/Folder--Mini' + - $ref: '#/components/schemas/WebLink--Mini' + LegalHoldPolicy: + title: Legal hold policy + type: object + x-box-resource-id: legal_hold_policy + x-box-variant: standard + description: 'Legal Hold Policy information describes the basic characteristics of the Policy, such as name, description, and filter dates.' + allOf: + - $ref: '#/components/schemas/LegalHoldPolicy--Mini' + - properties: + policy_name: + type: string + example: Policy 4 + description: Name of the legal hold policy. + maxLength: 254 + description: + type: string + description: Description of the legal hold policy. Optional property with a 500 character limit. + maxLength: 500 + example: Postman created policy + status: + type: string + example: active + enum: + - active + - applying + - releasing + - released + description: '* ''active'' - the policy is not in a transition state * ''applying'' - that the policy is in the process of being applied * ''releasing'' - that the process is in the process of being released * ''released'' - the policy is no longer active' + assignment_counts: + type: object + description: Counts of assignments within this a legal hold policy by item type + properties: + user: + type: integer + format: int64 + description: The number of users this policy is applied to + example: 1 + folder: + type: integer + format: int64 + description: The number of folders this policy is applied to + example: 2 + file: + type: integer + format: int64 + description: The number of files this policy is applied to + example: 3 + file_version: + type: integer + format: int64 + description: The number of file versions this policy is applied to + example: 4 + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who created the legal hold policy object + created_at: + type: string + format: date-time + description: When the legal hold policy object was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the legal hold policy object was modified. Does not update when assignments are added or removed. + example: '2012-12-12T10:53:43-08:00' + deleted_at: + type: string + format: date-time + description: 'When the policy release request was sent. (Because it can take time for a policy to fully delete, this isn''t quite the same time that the policy is fully deleted). If `null`, the policy was not deleted.' + example: '2012-12-12T10:53:43-08:00' + filter_started_at: + type: string + format: date-time + description: 'User-specified, optional date filter applies to Custodian assignments only' + example: '2012-12-12T10:53:43-08:00' + filter_ended_at: + type: string + format: date-time + description: 'User-specified, optional date filter applies to Custodian assignments only' + example: '2012-12-12T10:53:43-08:00' + release_notes: + type: string + example: Example + description: Optional notes about why the policy was created. + maxLength: 500 + LegalHoldPolicies: + title: Legal hold policies + type: object + x-box-resource-id: legal_hold_policies + x-box-tag: legal_hold_policies + description: A list of legal hold policies. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/LegalHoldPolicy' + LegalHoldPolicy--Mini: + title: Legal hold policy (Mini) + type: object + x-box-resource-id: legal_hold_policy--mini + x-box-tag: legal_hold_policies + x-box-variants: + - mini + - standard + x-box-variant: mini + description: A mini legal hold policy + properties: + id: + type: string + description: The unique identifier for this legal hold policy + example: '11446498' + type: + type: string + description: '`legal_hold_policy`' + example: legal_hold_policy + enum: + - legal_hold_policy + LegalHoldPolicyAssignment: + title: Legal hold policy assignment + type: object + x-box-resource-id: legal_hold_policy_assignment + x-box-tag: legal_hold_policy_assignments + description: 'Legal Hold Assignments are used to assign Legal Hold Policies to Users, Folders, Files, or File Versions. Creating a Legal Hold Assignment puts a hold on the File-Versions that belong to the Assignment''s ''apply-to'' entity.' + allOf: + - $ref: '#/components/schemas/LegalHoldPolicyAssignment--Base' + - properties: + legal_hold_policy: + allOf: + - $ref: '#/components/schemas/LegalHoldPolicy--Mini' + - description: The policy that the legal hold policy assignment is part of + assigned_to: + # allOf: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + - $ref: '#/components/schemas/WebLink' + description: The item that the the legal hold policy is assigned to. Includes type and ID. + assigned_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who created the legal hold policy assignment + assigned_at: + type: string + format: date-time + description: When the legal hold policy assignment object was created + example: '2012-12-12T10:53:43-08:00' + deleted_at: + type: string + format: date-time + description: 'When the assignment release request was sent. (Because it can take time for an assignment to fully delete, this isn''t quite the same time that the assignment is fully deleted). If null, Assignment was not deleted.' + example: '2012-12-12T10:53:43-08:00' + LegalHoldPolicyAssignment--Base: + title: Legal hold policy assignment (Base) + type: object + x-box-resource-id: legal_hold_policy_assignment--base + x-box-sanitized: true + x-box-tag: legal_hold_policy_assignments + x-box-variants: + - base + - standard + x-box-variant: base + description: 'Legal Hold Assignments are used to assign Legal Hold Policies to Users, Folders, Files, or File Versions. Creating a Legal Hold Assignment puts a hold on the File-Versions that belong to the Assignment''s ''apply-to'' entity.' + properties: + id: + type: string + description: The unique identifier for this legal hold assignment + example: '11446498' + type: + type: string + description: '`legal_hold_policy_assignment`' + example: legal_hold_policy_assignment + enum: + - legal_hold_policy_assignment + LegalHoldPolicyAssignments: + title: Legal hold policy assignments + type: object + x-box-resource-id: legal_hold_policy_assignments + x-box-tag: legal_hold_policy_assignments + description: A list of legal hold policies assignments. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/LegalHoldPolicyAssignment--Base' + RealtimeServer: + title: Real-time server + type: object + x-box-resource-id: realtime_server + description: A real-time server that can be used for long polling user events + properties: + type: + description: '`realtime_server`' + type: string + example: realtime_server + url: + type: string + example: 'http://2.realtime.services.box.net/subscribe?channel=cc807c9c4869ffb1c81a&stream_type=all' + description: The URL for the server. + ttl: + description: The time in minutes for which this server is available + type: integer + example: 10 + max_retries: + description: 'The maximum number of retries this server will allow before a new long poll should be started by getting a [new list of server](#options-events).' + type: integer + example: 10 + retry_timeout: + description: The maximum number of seconds without a response after which you should retry the long poll connection. This helps to overcome network issues where the long poll looks to be working but no packages are coming through. + type: integer + example: 610 + RealtimeServers: + title: Real-time servers + type: object + x-box-resource-id: realtime_servers + description: A list of real-time servers that can be used for long-polling. + x-box-tag: events + properties: + chunk_size: + description: The number of items in this response. + example: 1 + type: integer + format: int64 + entries: + type: array + description: The entries of realtime servers. + items: + $ref: '#/components/schemas/RealtimeServer' + RecentItem: + title: Recent item + type: object + x-box-resource-id: recent_item + description: A recent item accessed by a user. + x-box-tag: recent_items + properties: + type: + type: string + description: '`recent_item`' + example: recent_item + item: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + - $ref: '#/components/schemas/WebLink' + interaction_type: + type: string + example: item_preview + description: The most recent type of access the user performed on the item. + enum: + - item_preview + - item_upload + - item_comment + - item_open + - item_modify + interacted_at: + type: string + format: date-time + description: The time of the most recent interaction. + example: '2018-04-13T13:53:23-07:00' + interaction_shared_link: + type: string + example: 'https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg' + description: 'If the item was accessed through a shared link it will appear here, otherwise this will be null.' + RecentItems: + title: Recent items + type: object + x-box-resource-id: recent_items + description: A list of recent items. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/RecentItem' + RetentionPolicies: + title: Retention policies + type: object + x-box-resource-id: retention_policies + x-box-tag: retention_policies + description: A list of retention policies + properties: + total_count: + description: The number of retention policies. + example: 156 + type: integer + format: int64 + entries: + type: array + description: The entries of retention policies. + items: + $ref: '#/components/schemas/RetentionPolicy' + RetentionPolicy: + title: Retention policy + type: object + x-box-resource-id: retention_policy + x-box-tag: retention_policies + x-box-variant: standard + description: 'A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console.' + allOf: + - $ref: '#/components/schemas/RetentionPolicy--Mini' + - properties: + policy_type: + type: string + example: finite + description: 'The type of the retention policy. A retention policy type can either be `finite`, where a specific amount of time to retain the content is known upfront, or `indefinite`, where the amount of time to retain the content is still unknown.' + enum: + - finite + - indefinite + status: + type: string + example: active + description: 'The status of the retention policy. The status of a policy will be `active`, unless explicitly retired by an administrator, in which case the status will be `retired`. Once a policy has been retired, it cannot become active again.' + enum: + - active + - retired + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: A mini user object representing the user that created the retention policy + created_at: + type: string + format: date-time + description: When the retention policy object was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the retention policy object was last modified + example: '2012-12-12T10:53:43-08:00' + RetentionPolicy--Mini: + title: Retention policy (Mini) + type: object + x-box-resource-id: retention_policy--mini + x-box-variant: mini + description: 'A mini representation of a retention policy, used when nested within another resource.' + allOf: + - $ref: '#/components/schemas/RetentionPolicy--Base' + - properties: + policy_name: + type: string + description: The name given to the retention policy + example: Some Policy Name + retention_length: + type: string + format: int32 + example: '365' + minimum: 1 + description: 'The length of the retention policy. This length specifies the duration in days that the retention policy will be active for after being assigned to content. If the policy has A `policy_type` of `indefinite`, the `retention_length` will also be `indefinite`.' + disposition_action: + type: string + example: permanently_delete + description: 'The disposition action of the retention policy. This action can be `permanently_delete`, which will cause the content retained by the policy to be permanently deleted, or `remove_retention`, which will lift the retention policy from the content, allowing it to be deleted by users, once the retention policy has expired.' + enum: + - permanently_delete + - remove_retention + RetentionPolicy--Base: + title: Retention policy (Base) + type: object + x-box-resource-id: retention_policy--base + x-box-tag: retention_policies + x-box-variants: + - base + - mini + - standard + x-box-variant: base + description: 'The bare basic representation of a file version, the minimal amount of fields returned when using the `fields` query parameter.' + properties: + id: + type: string + nullable: false + description: The unique identifier that represent a file version. + example: '12345' + type: + type: string + description: '`retention_policy`' + example: retention_policy + enum: + - retention_policy + nullable: false + RetentionPolicyAssignment: + title: Retention policy assignment + type: object + x-box-resource-id: retention_policy_assignment + x-box-tag: retention_policy_assignments + description: 'The retention policy assignment endpoint provides a way for admins to apply a retention policy on a per-folder basis, or place a blanket policy over the entire enterprise.' + properties: + id: + type: string + description: The unique identifier for this retention policy assignment + example: '11446498' + type: + type: string + description: '`retention_policy_assignment`' + example: retention_policy_assignment + enum: + - retention_policy_assignment + retention_policy: + description: A mini retention policy object representing the retention policy that has been assigned to this content + $ref: '#/components/schemas/RetentionPolicy--Mini' + assigned_to: + title: Reference + description: The bare basic reference for an object + type: object + properties: + id: + type: string + description: The unique identifier for this object + example: '11446498' + type: + type: string + description: The type for this object + example: file + assigned_by: + description: A mini user object representing the user that created the retention policy assignment object + $ref: '#/components/schemas/User--Mini' + assigned_at: + type: string + format: date-time + description: When the retention policy assignment object was created + example: '2012-12-12T10:53:43-08:00' + RetentionPolicyAssignments: + title: Retention policy assignments + type: object + x-box-resource-id: retention_policy_assignments + x-box-tag: retention_policy_assignments + description: A list of retention policy assignments + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/RetentionPolicyAssignment' + SearchResults: + title: Search Results + type: object + x-box-resource-id: search_results + x-box-tag: search + description: 'A list of files, folders and web links that matched the search query.' + allOf: + - type: object + properties: + total_count: + description: One greater than the offset of the last entry in the search results. The total number of entries in the collection may be less than `total_count`. + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for this search. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. + example: 1000 + type: integer + format: int64 + offset: + description: The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter used. + example: 2000 + type: integer + format: int64 + - properties: + entries: + description: The search results for the query provided. + type: array + items: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + - $ref: '#/components/schemas/WebLink' + SearchResultsWithSharedLinks: + title: Search Results (including Shared Links) + type: object + x-box-resource-id: search_results_with_shared_links + x-box-tag: search + description: 'A list of files, folders and web links that matched the search query, including the additional information about any shared links through which the item has been shared with the user. This response format is only returned when the `include_recent_shared_links` query parameter has been set to `true`.' + allOf: + - type: object + properties: + total_count: + description: One greater than the offset of the last entry in the search results. The total number of entries in the collection may be less than `total_count`. + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for this search. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. + example: 1000 + type: integer + format: int64 + offset: + description: The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter used. + example: 2000 + type: integer + format: int64 + - properties: + entries: + description: 'The search results for the query provided, including the additional information about any shared links through which the item has been shared with the user.' + type: array + items: + $ref: '#/components/schemas/SearchResultWithSharedLink' + SearchResultWithSharedLink: + title: Search Result (including Shared Link) + type: object + x-box-resource-id: search_result_with_shared_link + x-box-tag: search + description: 'A single of files, folder or web link that matched the search query, including the additional information about the shared link through which the item has been shared with the user. This response format is only returned when the `include_recent_shared_links` query parameter has been set to `true`.' + properties: + accessible_via_shared_link: + description: The optional shared link through which the user has access to this item. This value is only returned for items for which the user has recently accessed the file through a shared link. For all other items this value will return `null`. + example: 'https://www.box.com/s/vspke7y05sb214wjokpk' + type: string + item: + oneOf: + - $ref: '#/components/schemas/File' + - $ref: '#/components/schemas/Folder' + - $ref: '#/components/schemas/WebLink' + type: + description: The result type. The value is always `search_result`. + example: search_result + type: string + StoragePolicy: + title: Storage policy + type: object + x-box-resource-id: storage_policy + x-box-variant: standard + description: The Storage Policy object describes the storage zone. + allOf: + - $ref: '#/components/schemas/StoragePolicy--Mini' + - properties: + name: + description: A descriptive name of the region + type: string + example: Montreal / Dublin + StoragePolicies: + title: Storage policies + type: object + x-box-resource-id: storage_policies + x-box-tag: storage_policies + description: A list of storage policies. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/StoragePolicy' + StoragePolicy--Mini: + title: Storage policy (Mini) + type: object + x-box-resource-id: storage_policy--mini + x-box-tag: storage_policies + x-box-variants: + - standard + - mini + x-box-variant: mini + description: A mini description of a Storage Policy object + properties: + id: + type: string + description: The unique identifier for this storage policy + example: '11446498' + type: + type: string + description: '`storage_policy`' + example: storage_policy + enum: + - storage_policy + StoragePolicyAssignment: + title: Storage policy assignment + type: object + x-box-resource-id: storage_policy_assignment + x-box-tag: storage_policy_assignments + description: The assignment of a storage policy to a user or enterprise + properties: + storage_policy: + description: The assigned storage policy + $ref: '#/components/schemas/StoragePolicy--Mini' + assigned_to: + description: The enterprise or use the policy is assigned to + $ref: '#/components/schemas/AssignedTo' + StoragePolicyAssignments: + title: Storage policy assignments + type: object + x-box-resource-id: storage_policy_assignments + x-box-tag: storage_policy_assignments + description: A list of storage policy assignments. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/StoragePolicyAssignment' + Task: + title: Task + type: object + x-box-resource-id: task + x-box-tag: tasks + description: A task allows for file-centric workflows within Box. Users can create tasks on files and assign them to other users for them to complete the tasks. + properties: + id: + type: string + description: The unique identifier for this task + example: '11446498' + type: + type: string + description: '`task`' + example: task + enum: + - task + item: + description: The file associated with the task + $ref: '#/components/schemas/File--Mini' + due_at: + type: string + format: date-time + description: When the task is due + example: '2012-12-12T10:53:43-08:00' + action: + type: string + example: review + description: The type of task the task assignee will be prompted to perform. + enum: + - review + - complete + message: + type: string + description: A message that will be included with the task + example: Legal review + task_assignment_collection: + description: A collection of task assignment objects associated with the task + $ref: '#/components/schemas/TaskAssignments' + is_completed: + type: boolean + description: Whether the task has been completed + example: true + created_by: + description: The user who created the task + $ref: '#/components/schemas/User--Mini' + created_at: + type: string + format: date-time + description: When the task object was created + example: '2012-12-12T10:53:43-08:00' + completion_rule: + type: string + description: Defines which assignees need to complete this task before the task is considered completed. * `all_assignees` requires all assignees to review or approve the the task in order for it to be considered completed. * `any_assignee` accepts any one assignee to review or approve the the task in order for it to be considered completed. + example: all_assignees + enum: + - all_assignees + - any_assignee + Tasks: + title: Tasks + type: object + x-box-resource-id: tasks + x-box-tag: tasks + description: A list of tasks + properties: + total_count: + description: One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. + example: 5000 + type: integer + format: int64 + entries: + type: array + description: Tasks on files which other users can to complete for a user. + items: + $ref: '#/components/schemas/Task' + TaskAssignment: + title: Task assignment + type: object + x-box-resource-id: task_assignment + x-box-tag: task_assignments + description: A task assignment defines which task is assigned to which user to complete. + properties: + id: + type: string + description: The unique identifier for this task assignment + example: '11446498' + type: + type: string + description: '`task_assignment`' + example: task_assignment + enum: + - task_assignment + item: + description: The file that the task has been assigned to. + $ref: '#/components/schemas/File--Mini' + assigned_to: + description: The user that the task has been assigned to. + $ref: '#/components/schemas/User--Mini' + message: + type: string + example: Please review + description: A message that will is included with the task assignment. This is visible to the assigned user in the web and mobile UI. + completed_at: + type: string + format: date-time + description: The date at which this task assignment was completed. This will be `null` if the task is not completed yet. + example: '2012-12-12T10:53:43-08:00' + assigned_at: + type: string + format: date-time + description: The date at which this task was assigned to the user. + example: '2012-12-12T10:53:43-08:00' + reminded_at: + type: string + format: date-time + description: The date at which the assigned user was reminded of this task assignment. + example: '2012-12-12T10:53:43-08:00' + resolution_state: + type: string + description: The current state of the assignment. The available states depend on the `action` value of the task object. + example: incomplete + enum: + - completed + - incomplete + - approved + - rejected + assigned_by: + description: The user who assigned this task. + $ref: '#/components/schemas/User--Mini' + TaskAssignments: + title: Task assignments + type: object + x-box-resource-id: task_assignments + x-box-tag: task_assignments + description: A list of task assignments + properties: + total_count: + description: The total number of items in this collection. + example: 100 + type: integer + format: int64 + entries: + type: array + description: The entries of task assignments. + items: + $ref: '#/components/schemas/TaskAssignment' + TermsOfService: + title: Terms of service + type: object + x-box-resource-id: terms_of_service + x-box-variant: standard + description: The root-level record that is supposed to represent a single Terms of Service. + allOf: + - $ref: '#/components/schemas/TermsOfService--Mini' + - properties: + status: + description: Whether these terms are enabled or not + type: string + example: enabled + enum: + - enabled + - disabled + enterprise: + allOf: + - title: Enterprise + type: object + description: A representation of a Box enterprise + properties: + id: + type: string + description: The unique identifier for this enterprise. + example: '11446498' + type: + type: string + description: '`enterprise`' + example: enterprise + enum: + - enterprise + name: + description: The name of the enterprise + example: Acme Inc. + type: string + - description: The enterprise these terms apply to + tos_type: + description: Whether to apply these terms to managed users or external users + type: string + example: managed + enum: + - managed + - external + text: + description: The text for your terms and conditions. This text could be empty if the `status` is set to `disabled`. + type: string + example: 'By using this service, you agree to ...' + created_at: + type: string + format: date-time + description: When the legal item was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the legal item was modified. + example: '2012-12-12T10:53:43-08:00' + TermsOfServices: + title: Terms of services + type: object + x-box-resource-id: terms_of_services + x-box-tag: terms_of_services + description: A list of terms of services + properties: + total_count: + description: The total number of objects. + example: 2 + type: integer + format: int64 + entries: + type: array + description: The entries of terms of service. + items: + $ref: '#/components/schemas/TermsOfService' + TermsOfService--Mini: + title: Terms of service (Mini) + type: object + x-box-resource-id: terms_of_service--mini + x-box-tag: terms_of_services + x-box-variants: + - mini + - standard + x-box-variant: mini + description: The root-level record that is supposed to represent a single Terms of Service. + properties: + id: + type: string + description: The unique identifier for this terms of service. + example: '11446498' + type: + type: string + description: '`terms_of_service`' + example: terms_of_service + enum: + - terms_of_service + TermsOfServiceUserStatus: + title: Terms of service user status + type: object + x-box-resource-id: terms_of_service_user_status + x-box-tag: terms_of_service_user_statuses + description: The association between a Terms of Service and a user + properties: + id: + type: string + description: The unique identifier for this terms of service user status + example: '11446498' + type: + type: string + description: '`terms_of_service_user_status`' + example: terms_of_service_user_status + enum: + - terms_of_service_user_status + tos: + description: The terms of service + $ref: '#/components/schemas/TermsOfService--Mini' + user: + description: The user + $ref: '#/components/schemas/User--Mini' + is_accepted: + type: boolean + example: true + description: If the user has accepted the terms of services + created_at: + type: string + format: date-time + description: When the legal item was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the legal item was modified. + example: '2012-12-12T10:53:43-08:00' + TermsOfServiceUserStatuses: + title: Terms of service user statuses + type: object + x-box-resource-id: terms_of_services_user_statuses + x-box-tag: terms_of_service_user_statuses + description: A list of terms of service user statuses + properties: + total_count: + description: The total number of objects. + example: 2 + type: integer + format: int64 + entries: + type: array + description: The associations between a Terms of Service and a user. + items: + $ref: '#/components/schemas/TermsOfServiceUserStatus' + UploadPart: + title: Upload part + type: object + x-box-resource-id: upload_part + x-box-variant: standard + description: The representation of an upload session chunk. + allOf: + - $ref: '#/components/schemas/UploadPart--Mini' + - properties: + sha1: + description: The SHA1 hash of the chunk. + type: string + example: 134b65991ed521fcfe4724b7d814ab8ded5185dc + UploadPart--Mini: + title: Upload part (Mini) + type: object + x-box-resource-id: upload_part--mini + x-box-tag: chunked_uploads + x-box-variants: + - mini + - standard + x-box-variant: mini + description: The basic representation of an upload session chunk. + properties: + part_id: + description: The unique ID of the chunk. + type: string + example: 6F2D3486 + offset: + description: The offset of the chunk within the file in bytes. The lower bound of the position of the chunk within the file. + type: integer + format: int64 + example: 16777216 + size: + description: The size of the chunk in bytes. + type: integer + format: int64 + example: 3222784 + UploadedPart: + title: Uploaded part + type: object + x-box-resource-id: uploaded_part + description: 'A chunk of a file uploaded as part of an upload session, as returned by some endpoints.' + x-box-tag: chunked_uploads + properties: + part: + $ref: '#/components/schemas/UploadPart' + UploadParts: + title: Upload parts + type: object + x-box-resource-id: upload_parts + x-box-tag: chunked_uploads + description: A list of uploaded chunks for an upload session. + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/UploadPart' + UploadSession: + title: Upload session + type: object + x-box-resource-id: upload_session + description: An upload session for chunk uploading a file. + x-box-tag: chunked_uploads + properties: + id: + type: string + description: The unique identifier for this session + example: F971964745A5CD0C001BBE4E58196BFD + type: + type: string + description: '`upload_session`' + example: upload_session + enum: + - upload_session + session_expires_at: + description: The date and time when this session expires. + type: string + format: date-time + example: '2012-12-12T10:53:43-08:00' + part_size: + type: integer + format: int64 + example: 1024 + description: The size in bytes that must be used for all parts of of the upload. Only the last part is allowed to be of a smaller size. + total_parts: + type: integer + format: int32 + example: 1000 + description: 'The total number of parts expected in this upload session, as determined by the file size and part size.' + num_parts_processed: + type: integer + format: int32 + example: 455 + description: 'The number of parts that have been uploaded and processed by the server. This starts at `0`. When committing a file files, inspecting this property can provide insight if all parts have been uploaded correctly.' + session_endpoints: + description: A list of endpoints for a chunked upload session. + $ref: '#/components/schemas/SessionEndpoint' + UploadUrl: + title: Upload URL + type: object + x-box-resource-id: upload_url + x-box-tag: uploads + description: The details for the upload session for the file. + properties: + upload_url: + type: string + example: 'https://upload-las.app.box.com/api/2.0/files/content?upload_session_id=1234' + description: A URL for an upload session that can be used to upload the file. + upload_token: + type: string + example: Pc3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQP + description: An optional access token to use to upload the file + User: + title: User + type: object + x-box-resource-id: user + x-box-variant: standard + description: 'A standard representation of a user, as returned from any user API endpoints by default' + allOf: + - $ref: '#/components/schemas/User--Mini' + - properties: + created_at: + type: string + format: date-time + description: When the user object was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When the user object was last modified + example: '2012-12-12T10:53:43-08:00' + language: + type: string + description: 'The language of the user, formatted in modified version of the [ISO 639-1](/guides/api-calls/language-codes) format.' + example: en + timezone: + type: string + format: timezone + description: The user's timezone + example: Africa/Bujumbura + space_amount: + type: integer + format: int64 + description: The user’s total available space amount in bytes + example: 11345156112 + space_used: + type: integer + format: int64 + description: The amount of space in use by the user + example: 1237009912 + max_upload_size: + type: integer + format: int64 + description: The maximum individual file size in bytes the user can have + example: 2147483648 + status: + type: string + enum: + - active + - inactive + - cannot_delete_edit + - cannot_delete_edit_upload + description: The user's account status + example: active + job_title: + type: string + description: The user’s job title + maxLength: 100 + example: CEO + phone: + type: string + description: The user’s phone number + maxLength: 100 + example: '6509241374' + address: + type: string + description: The user’s address + maxLength: 255 + example: '900 Jefferson Ave, Redwood City, CA 94063' + avatar_url: + type: string + description: URL of the user’s avatar image + example: 'https://www.box.com/api/avatar/large/181216415' + notification_email: + type: object + description: 'An alternate notification email address to which email notifications are sent. When it''s confirmed, this will be the email address to which notifications are sent instead of to the primary email address.' + nullable: true + properties: + email: + type: string + example: notifications@example.com + description: The email address to send the notifications to. + is_confirmed: + type: boolean + example: true + description: Specifies if this email address has been confirmed. + Users: + title: Users + type: object + x-box-resource-id: users + x-box-tag: users + description: A list of users. + allOf: + - type: object + description: The part of an API response that describes pagination + properties: + total_count: + description: 'One greater than the offset of the last entry in the entire collection. The total number of entries in the collection may be less than `total_count`. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 5000 + type: integer + format: int64 + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + offset: + description: 'The 0-based offset of the first entry in this set. This will be the same as the `offset` query parameter. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + example: 2000 + type: integer + format: int64 + order: + description: 'The order by which items are returned. This field is only returned for calls that use offset-based pagination. For marker-based paginated APIs, this field will be omitted.' + type: array + items: + type: object + description: The order in which a pagination is ordered + properties: + by: + description: The field to order by + example: type + type: string + direction: + type: string + description: 'The direction to order by, either ascending or descending' + example: ASC + enum: + - ASC + - DESC + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/User' + User--Full: + title: User (Full) + type: object + x-box-resource-id: user--full + x-box-variant: full + description: 'A full representation of a user, as can be returned from any user API endpoint.' + allOf: + - $ref: '#/components/schemas/User' + - properties: + role: + type: string + enum: + - admin + - coadmin + - user + description: The user’s enterprise role + example: admin + tracking_codes: + type: array + description: Tracking codes allow an admin to generate reports from the admin console and assign an attribute to a specific group of users. This setting must be enabled for an enterprise before it can be used. + items: + type: object + description: Custom tracking code for a user. + properties: + type: + type: string + description: '`tracking_code`' + example: tracking_code + enum: + - tracking_code + name: + type: string + description: 'The name of the tracking code, which must be preconfigured in the Admin Console' + example: department + value: + type: string + description: The value of the tracking code + example: Sales + can_see_managed_users: + type: boolean + example: true + description: Whether the user can see other enterprise users in their contact list + is_sync_enabled: + type: boolean + description: Whether the user can use Box Sync + example: true + is_external_collab_restricted: + type: boolean + example: true + description: Whether the user is allowed to collaborate with users outside their enterprise + is_exempt_from_device_limits: + type: boolean + example: true + description: Whether to exempt the user from Enterprise device limits + is_exempt_from_login_verification: + type: boolean + example: true + description: Whether the user must use two-factor authentication + enterprise: + allOf: + - title: Enterprise + type: object + description: A representation of a Box enterprise + properties: + id: + type: string + description: The unique identifier for this enterprise. + example: '11446498' + type: + type: string + description: '`enterprise`' + example: enterprise + enum: + - enterprise + name: + description: The name of the enterprise + example: Acme Inc. + type: string + - description: Representation of the user’s enterprise + my_tags: + type: array + items: + type: string + example: + - important + description: Tags for all files and folders owned by the user. Values returned will only contain tags that were set by the requester. + hostname: + type: string + example: 'https://example.app.box.com/' + description: 'The root (protocol, subdomain, domain) of any links that need to be generated for the user' + is_platform_access_only: + type: boolean + example: true + description: Whether the user is an App User + external_app_user_id: + type: string + example: my-user-1234 + description: 'An external identifier for an app user, which can be used to look up the user. This can be used to tie user IDs from external identity providers to Box users.' + User--Mini: + title: User (Mini) + type: object + x-box-resource-id: user--mini + x-box-variant: mini + description: 'A mini representation of a user, as can be returned when nested within other resources.' + allOf: + - $ref: '#/components/schemas/User--Base' + - properties: + name: + type: string + description: The display name of this user + example: Aaron Levie + maxLength: 50 + nullable: false + login: + type: string + format: email + description: The primary email address of this user + example: ceo@example.com + nullable: false + User--Base: + title: User (Base) + type: object + x-box-resource-id: user--base + x-box-tag: users + x-box-variants: + - base + - mini + - standard + - full + x-box-variant: base + description: 'A mini representation of a user, used when nested within another resource.' + properties: + id: + type: string + description: The unique identifier for this user + example: '11446498' + type: + type: string + description: '`user`' + example: user + nullable: false + enum: + - user + Watermark: + title: Watermark + type: object + x-box-resource-id: watermark + x-box-tag: file_watermarks + description: A watermark is a semi-transparent overlay on an embedded file preview that displays a viewer's email address or user ID and the time of access over a file's content + properties: + watermark: + type: object + description: Watermark details + properties: + created_at: + type: string + format: date-time + description: When this watermark was created + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When this task was modified + example: '2012-12-12T10:53:43-08:00' + Webhook: + title: Webhook + type: object + x-box-resource-id: webhook + x-box-tag: webhooks + description: Represents a configured webhook. + properties: + id: + type: string + description: The unique identifier for this webhook. + example: '11446498' + type: + type: string + description: '`webhook`' + example: webhook + enum: + - webhook + target: + type: object + description: The item that will trigger the webhook + properties: + id: + description: The ID of the item to trigger a webhook + type: string + example: '1231232' + type: + description: The type of item to trigger a webhook + type: string + example: file + enum: + - file + - folder + created_by: + description: The user who created the webhook + $ref: '#/components/schemas/User--Mini' + created_at: + type: string + format: date-time + description: A timestamp identifying the time that the webhook was created. + example: '2012-12-12T10:53:43-08:00' + address: + type: string + example: 'https://example.com/webhooks' + description: The URL that is notified by this webhook + triggers: + type: array + example: + - FILE.UPLOADED + description: An array of event names that this webhook is to be triggered for + items: + title: Webhook Trigger + example: FILE.UPLOADED + type: string + description: The event name that triggered this webhook + enum: + - FILE.UPLOADED + - FILE.PREVIEWED + - FILE.DOWNLOADED + - FILE.TRASHED + - FILE.DELETED + - FILE.RESTORED + - FILE.COPIED + - FILE.MOVED + - FILE.LOCKED + - FILE.UNLOCKED + - FILE.RENAMED + - COMMENT.CREATED + - COMMENT.UPDATED + - COMMENT.DELETED + - TASK_ASSIGNMENT.CREATED + - TASK_ASSIGNMENT.UPDATED + - METADATA_INSTANCE.CREATED + - METADATA_INSTANCE.UPDATED + - METADATA_INSTANCE.DELETED + - FOLDER.CREATED + - FOLDER.RENAMED + - FOLDER.DOWNLOADED + - FOLDER.RESTORED + - FOLDER.DELETED + - FOLDER.COPIED + - FOLDER.MOVED + - FOLDER.TRASHED + - WEBHOOK.DELETED + - COLLABORATION.CREATED + - COLLABORATION.ACCEPTED + - COLLABORATION.REJECTED + - COLLABORATION.REMOVED + - COLLABORATION.UPDATED + - SHARED_LINK.DELETED + - SHARED_LINK.CREATED + - SHARED_LINK.UPDATED + Webhooks: + title: Webhooks + type: object + x-box-resource-id: webhooks + x-box-tag: webhooks + description: A list of webhooks. + allOf: + - type: object + description: The part of an API response that describes marker based pagination + properties: + limit: + description: The limit that was used for these entries. This will be the same as the `limit` query parameter unless that value exceeded the maximum value allowed. The maximum value varies by API. + example: 1000 + type: integer + format: int64 + next_marker: + description: The marker for the start of the next page of results. + example: 3000 + type: integer + format: int64 + prev_marker: + description: The marker for the start of the previous page of results. + example: 1000 + type: integer + format: int64 + - properties: + entries: + type: array + items: + $ref: '#/components/schemas/Webhook' + WebLink: + title: Web link + type: object + x-box-resource-id: web_link + x-box-variant: standard + description: 'Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files.' + allOf: + - $ref: '#/components/schemas/WebLink--Mini' + - properties: + parent: + allOf: + - $ref: '#/components/schemas/Folder--Mini' + - description: The parent object the web link belongs to + description: + type: string + example: Example page + description: The description accompanying the web link. This is visible within the Box web application. + path_collection: + allOf: + - title: Path collection + description: A list of parent folders for an item. + type: object + properties: + total_count: + description: The number of folders in this list. + example: 1 + type: integer + format: int64 + nullable: false + entries: + type: array + description: The parent folders for this item + nullable: false + items: + $ref: '#/components/schemas/Folder--Mini' + - description: 'The tree of folders that this web link is contained in, starting at the root.' + - nullable: false + created_at: + type: string + format: date-time + description: When this file was created on Box’s servers. + example: '2012-12-12T10:53:43-08:00' + modified_at: + type: string + format: date-time + description: When this file was last updated on the Box servers. + example: '2012-12-12T10:53:43-08:00' + trashed_at: + type: string + format: date-time + nullable: true + description: When this file was last moved to the trash. + example: '2012-12-12T10:53:43-08:00' + purged_at: + type: string + format: date-time + nullable: true + description: When this file will be permanently deleted. + example: '2012-12-12T10:53:43-08:00' + created_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who created this web link + modified_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who last modified this web link + owned_by: + allOf: + - $ref: '#/components/schemas/User--Mini' + - description: The user who owns this web link + shared_link: + allOf: + - title: Shared link + description: 'Shared links provide direct, read-only access to files or folder on Box. Shared links with open access level allow anyone with the URL to access the item, while shared links with company or collaborators access levels can only be accessed by appropriately authenticated Box users.' + type: object + properties: + url: + type: string + format: url + description: The URL that can be used to access the item on Box. This URL will display the item in Box's preview UI where the file can be downloaded if allowed. This URL will continue to work even when a custom `vanity_url` has been set for this shared link. + example: 'https://www.box.com/s/vspke7y05sb214wjokpk' + nullable: false + download_url: + type: string + format: url + x-box-premium-feature: true + description: A URL that can be used to download the file. This URL can be used in a browser to download the file. This URL includes the file extension so that the file will be saved with the right file type. This property will be `null` for folders. + example: 'https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg' + nullable: true + vanity_url: + type: string + format: url + description: The "Custom URL" that can also be used to preview the item on Box. Custom URLs can only be created or modified in the Box Web application. + example: 'https://acme.app.box.com/v/my_url/' + nullable: true + vanity_name: + type: string + description: 'The custom name of a shared link, as used in the `vanity_url` field.' + example: my_url + nullable: true + access: + type: string + description: 'The access level for this shared link. * `open` - provides access to this item to anyone with this link * `company` - only provides access to this item to people the same company * `collaborators` - only provides access to this item to people who are collaborators on this item If this field is omitted when creating the shared link, the access level will be set to the default access level specified by the enterprise admin.' + enum: + - open + - company + - collaborators + example: open + nullable: false + effective_access: + type: string + description: The effective access level for the shared link. This can be a more restrictive access level than the value in the `access` field when the enterprise settings restrict the allowed access levels. + enum: + - open + - company + - collaborators + example: company + nullable: false + effective_permission: + type: string + description: The effective permissions for this shared link. + enum: + - can_download + - can_preview + example: can_download + nullable: false + unshared_at: + type: string + format: date-time + description: The date and time when this link will be unshared. This field can only be set by users with paid accounts. + example: '2018-04-13T13:53:23-07:00' + nullable: true + is_password_enabled: + type: boolean + description: Defines if the shared link requires a password to access the item. + example: true + nullable: false + permissions: + type: object + description: Defines if this link allows a user to preview and download an item. + properties: + can_download: + type: boolean + example: true + nullable: false + description: 'Defines if the shared link allows for the item to be downloaded. For shared links on folders, this also applies to any items in the folder. This value can be set to `true` when the effective access level is set to `open` or `company`, not `collaborators`.' + can_preview: + type: boolean + example: true + nullable: false + description: Defines if the shared link allows for the item to be previewed. This value is always `true`. For shared links on folders this also applies to any items in the folder. + download_count: + type: integer + example: 3 + description: The number of times this item has been downloaded. + nullable: false + preview_count: + type: integer + example: 3 + description: The number of times this item has been previewed. + nullable: false + - description: The shared link object for this item. Will be `null` if no shared link has been created. + - nullable: true + item_status: + type: string + example: active + enum: + - active + - trashed + - deleted + description: 'Whether this item is deleted or not. Values include `active`, `trashed` if the file has been moved to the trash, and `deleted` if the file has been permanently deleted' + WebLink--Base: + title: Web link (Base) + type: object + x-box-resource-id: web_link--base + x-box-tag: web_links + x-box-variants: + - base + - mini + - standard + x-box-variant: base + description: 'Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files.' + properties: + id: + type: string + description: The unique identifier for this web link + example: '11446498' + type: + type: string + description: '`web_link`' + example: web_link + enum: + - web_link + etag: + type: string + example: '1' + description: The entity tag of this web link. Used with `If-Match` headers. + WebLink--Mini: + title: Web link (Mini) + type: object + x-box-resource-id: web_link--mini + x-box-variant: mini + description: 'Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files.' + allOf: + - $ref: '#/components/schemas/WebLink--Base' + - properties: + url: + type: string + example: 'https://www.example.com/example/1234' + description: The URL this web link points to + sequence_id: + allOf: + - type: string + example: '3' + nullable: false + description: 'A numeric identifier that represents the most recent user event that has been applied to this item. This can be used in combination with the `GET /events`-endpoint to filter out user events that would have occurred before this identifier was read. An example would be where a Box Drive-like application would fetch an item via the API, and then listen to incoming user events for changes to the item. The application would ignore any user events where the `sequence_id` in the event is smaller than or equal to the `sequence_id` in the originally fetched resource.' + - nullable: false + name: + type: string + description: The name of the web link + example: My Bookmark + ZipDownload: + title: Zip download + type: object + x-box-resource-id: zip_download + x-box-tag: zip_downloads + x-box-reference-category: zip_downloads + description: Represents a successful request to create a `zip` archive of a list of files and folders. + example: + download_url: 'https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content' + status_url: 'https://api.box.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status' + expires_at: '2020-07-22T11:26:08Z' + name_conflicts: + - - id: '12345' + type: file + original_name: Report.pdf + download_name: 3aa6a7.pdf + - id: '34325' + type: file + original_name: Report.pdf + download_name: 5d53f2.pdf + properties: + download_url: + type: string + description: 'The URL that can be used to download the `zip` archive. A `Get` request to this URL will start streaming the items requested. By default, this URL is only valid for a few seconds, until the `exires_at` time, unless a download is started after which it is valid for the duration of the download. It is important to note that the domain and path of this URL might change between API calls, and therefore it''s important to use this URL as-is.' + example: 'https://dl.boxcloud.com/2.0/zip_downloads/Lu6fA9Ob-jyysp3AAvMF4AkLEwZwAYbL=tgj2zIC=eK9RvJnJbjJl9rNh2qBgHDpyOCAOhpM=vajg2mKq8Mdd/content' + status_url: + type: string + description: 'The URL that can be used to get the status of the `zip` archive being downloaded. A `Get` request to this URL will return the number of files in the archive as well as the number of items already downloaded or skipped. By default, this URL is only valid for a few seconds, until the `exires_at` time, unless a download is started after which the URL is valid for 12 hours from the start of the download. It is important to note that the domain and path of this URL might change between API calls, and therefore it''s important to use this URL as-is.' + example: 'https://api.box.com/2.0/zip_downloads/Lu6fA9Ob-jyysp3AAvMF4AkLEwZwAYbL=tgj2zIC=eK9RvJnJbjJl9rNh2qBgHDpyOCAOhpM=vajg2mKq8Mdd/status' + expires_at: + type: string + format: date-time + description: 'The time and date when this archive will expire. After this time the `status_url` and `download_url` will return an error. By default, these URLs are only valid for a few seconds, unless a download is started after which the `download_url` is valid for the duration of the download, and the `status_url` is valid for 12 hours from the start of the download.' + example: '2019-08-29T23:59:00-07:00' + name_conflicts: + type: array + description: 'A list of conflicts that occurred when trying to create the archive. This would occur when multiple items have been requested with the same name. To solve these conflicts, the API will automatically rename an item and return a mapping between the original item''s name and its new name. For every conflict, both files will be renamed and therefore this list will always be a multiple of 2.' + items: + $ref: '#/components/schemas/NameConflict' + ZipDownloadStatus: + title: Zip download status + type: object + x-box-resource-id: zip_download_status + x-box-tag: zip_downloads + x-box-reference-category: zip_downloads + description: The status of a `zip` archive being downloaded. + properties: + total_file_count: + type: integer + description: The total number of files in the archive. + example: 20 + minimum: 0 + maximum: 10000 + downloaded_file_count: + type: integer + description: The number of files that have already been downloaded. + example: 10 + minimum: 0 + skipped_file_count: + type: integer + description: The number of files that have been skipped as they could not be downloaded. In many cases this is due to permission issues that have surfaced between the creation of the request for the archive and the archive being downloaded. + example: 5 + minimum: 0 + skipped_folder_count: + type: integer + description: The number of folders that have been skipped as they could not be downloaded. In many cases this is due to permission issues that have surfaced between the creation of the request for the archive and the archive being downloaded. + example: 5 + minimum: 0 + state: + type: string + description: The state of the archive being downloaded. + default: in_progeress + example: success + enum: + - in_progress + - failed + - success + FileScope: + title: File scope + type: object + description: A relation between a file and the scopes for which the file can be accessed + properties: + scope: + type: string + description: The file scopes for the file access + example: item_download + enum: + - annotation_edit + - annotation_view_all + - annotation_view_self + - base_explorer + - base_picker + - base_preview + - base_upload + - item_delete + - item_download + - item_preview + - item_rename + - item_share + object: + description: The file for which the file can be accessed + $ref: '#/components/schemas/File--Mini' + EventSource: + title: Event source + type: object + x-box-resource-id: event_source + description: The source file or folder that triggered an event in the event stream. + properties: + item_type: + type: string + nullable: false + enum: + - file + - folder + description: 'The type of the item that the event represents. Can be `file` or `folder`. ' + example: file + item_id: + type: string + nullable: false + description: 'The unique identifier that represents the item. ' + example: '560284318361' + item_name: + type: string + nullable: false + description: 'The name of the item. ' + example: report.pdf + parent: + description: The optional folder that this folder is located within. This value may be `null` for some folders such as the root folder or the trash folder. + $ref: '#/components/schemas/Folder--Mini' + nullable: true + owned_by: + description: The user who owns this item. + $ref: '#/components/schemas/User--Mini' + nullable: false + SkillCard: + type: object + x-box-resource-id: skill_card + x-box-tag: skills + title: Skill Card + description: A generic Box Skill metadata card. + required: + - type + - skill_card_type + - skill + - invocation + properties: + created_at: + type: string + format: date-time + example: '2018-04-13T13:53:23-07:00' + description: The optional date and time this card was created at. + type: + type: string + description: '`skill_card`' + example: skill_card + enum: + - skill_card + skill_card_type: + type: string + description: The type of card to add to the file. + example: status + enum: + - transcript + - keyword + - timeline + - status + skill_card_title: + type: object + description: The title of the card. + required: + - message + properties: + code: + type: string + example: my_transcripts + description: An optional identifier for the title. + message: + type: string + example: My Transcripts + description: The actual title to show in the UI. + status: + type: object + description: Used with a card of type `status` to set the status of the skill. This can be used to show a message to the user while the Skill is processing the data. + required: + - code + properties: + code: + type: string + description: A code for the status of this Skill invocation. By default each of these will have their own accompanied messages. These can be adjusted by setting the `message` value on this object. + example: success + enum: + - invoked + - processing + - success + - transient_failure + - permanent_failure + message: + type: string + description: A custom message that can be provided with this status. This will be shown in the web app to the end user. + example: We're preparing to process your file. Please hold on! + skill: + type: object + description: The service that applied this metadata. + required: + - type + - id + properties: + type: + type: string + example: service + description: '`service`' + enum: + - service + id: + type: string + example: image-recognition-service + description: A custom identifier that represent the service that applied this metadata. + invocation: + type: object + description: 'The invocation of this service, used to track which instance of a service applied the metadata.' + required: + - type + - id + properties: + type: + type: string + example: skill_invocation + description: '`skill_invocation`' + enum: + - skill_invocation + id: + type: string + example: image-recognition-service-123 + description: 'A custom identifier that represent the instance of the service that applied this metadata. For example, if your `image-recognition-service` runs on multiple nodes, this field can be used to identify the ID of the node that was used to apply the metadata.' + duration: + type: integer + example: 1000 + description: An optional total duration in seconds. Used with a `skill_card_type` of `transcript` or `timeline`. + entries: + type: array + description: 'An optional list of entries in the metadata card. This field is used with a `skill_card_type` of `transcript`, `keyword` or `timeline`.' + items: + type: object + description: An entry in the `entries` attribute of a metadata card + properties: + text: + type: string + example: keyword1 + description: 'The text of the entry. This would be the actual keyword in a `keyword` card, the line of a transcript in a `transcript` card, or the display name for an item when using the `timeline` entry.' + appears: + type: array + description: 'Defines a list of timestamps for an entry. This is used with a `skill_card_type` of `transcript` as well as `timeline` to place items on a timeline. For a `skill_card_type` of `transcript` there can only be one entry in this list for each item, and only the `start` time is used to place the transcript on the timeline.' + required: + - start + - end + items: + type: object + description: The timestamp for an entry. + properties: + start: + type: integer + example: 1 + description: The time in seconds when an entry should start appearing on a timeline. + end: + type: integer + example: 20 + description: The time in seconds when an entry should stop appearing on a timeline. For a `skill_card_type` of `transcript` this value is ignored. + image_url: + type: string + description: 'The image to show on a for an entry that appears on a timeline. This image URL is required for any `timeline` cards. The image will be shown in a list of items (for example faces), and clicking the image will show the user where that entry appears during the duration of this entry.' + example: 'https://example.com/image1.jpg' + KeywordSkillCard: + type: object + x-box-resource-id: keyword_skill_card + x-box-tag: skills + title: Keyword Skill Card + description: A skill card that contains a set of keywords + required: + - type + - skill_card_type + - skill + - invocation + - entries + properties: + created_at: + type: string + format: date-time + example: '2018-04-13T13:53:23-07:00' + description: The optional date and time this card was created at. + type: + type: string + description: '`skill_card`' + example: skill_card + enum: + - skill_card + skill_card_type: + type: string + description: '`keyword`' + example: keyword + enum: + - keyword + skill_card_title: + type: object + description: The title of the card. + required: + - message + properties: + code: + type: string + example: labels + description: An optional identifier for the title. + message: + type: string + example: Labels + description: The actual title to show in the UI. + skill: + type: object + description: The service that applied this metadata. + required: + - type + - id + properties: + type: + type: string + example: service + description: '`service`' + enum: + - service + id: + type: string + example: image-recognition-service + description: A custom identifier that represent the service that applied this metadata. + invocation: + type: object + description: 'The invocation of this service, used to track which instance of a service applied the metadata.' + required: + - type + - id + properties: + type: + type: string + example: skill_invocation + description: '`skill_invocation`' + enum: + - skill_invocation + id: + type: string + example: image-recognition-service-123 + description: 'A custom identifier that represent the instance of the service that applied this metadata. For example, if your `image-recognition-service` runs on multiple nodes, this field can be used to identify the ID of the node that was used to apply the metadata.' + entries: + type: array + description: An list of entries in the metadata card. + items: + type: object + description: An entry in the `entries` attribute of a metadata card + properties: + text: + type: string + example: keyword1 + description: The text of the keyword. + TimelineSkillCard: + type: object + x-box-resource-id: timeline_skill_card + x-box-tag: skills + title: Timeline Skill Card + description: A Box Skill metadata card that places a list of images on a timeline. + required: + - type + - skill_card_type + - skill + - invocation + - entries + properties: + created_at: + type: string + format: date-time + example: '2018-04-13T13:53:23-07:00' + description: The optional date and time this card was created at. + type: + type: string + description: '`skill_card`' + example: skill_card + enum: + - skill_card + skill_card_type: + type: string + description: '`timeline`' + example: timeline + enum: + - timeline + skill_card_title: + type: object + description: The title of the card. + required: + - message + properties: + code: + type: string + example: Faces + description: An optional identifier for the title. + message: + type: string + example: Faces + description: The actual title to show in the UI. + skill: + type: object + description: The service that applied this metadata. + required: + - type + - id + properties: + type: + type: string + example: service + description: '`service`' + enum: + - service + id: + type: string + example: image-recognition-service + description: A custom identifier that represent the service that applied this metadata. + invocation: + type: object + description: 'The invocation of this service, used to track which instance of a service applied the metadata.' + required: + - type + - id + properties: + type: + type: string + example: skill_invocation + description: '`skill_invocation`' + enum: + - skill_invocation + id: + type: string + example: image-recognition-service-123 + description: 'A custom identifier that represent the instance of the service that applied this metadata. For example, if your `image-recognition-service` runs on multiple nodes, this field can be used to identify the ID of the node that was used to apply the metadata.' + duration: + type: integer + example: 1000 + description: An total duration in seconds of the timeline. + entries: + type: array + description: A list of entries on the timeline. + items: + type: object + description: An single item that's placed on multiple items on the timeline. + properties: + text: + type: string + example: John + description: 'The text of the entry. This would be the display name for an item being placed on the timeline, for example the name of the person who was detected in a video.' + appears: + type: array + description: Defines a list of timestamps for when this item should appear on the timeline. + required: + - start + - end + items: + type: object + description: The timestamp for an entry. + properties: + start: + type: integer + example: 1 + description: The time in seconds when an entry should start appearing on a timeline. + end: + type: integer + example: 20 + description: The time in seconds when an entry should stop appearing on a timeline. + image_url: + type: string + description: 'The image to show on a for an entry that appears on a timeline. This image URL is required for every entry. The image will be shown in a list of items (for example faces), and clicking the image will show the user where that entry appears during the duration of this entry.' + example: 'https://example.com/image1.jpg' + TranscriptSkillCard: + type: object + x-box-resource-id: transcript_skill_card + x-box-tag: skills + title: Transcript Skill Card + description: A Box Skill metadata card that adds a transcript to a file. + required: + - type + - skill_card_type + - skill + - invocation + - entries + properties: + created_at: + type: string + format: date-time + example: '2018-04-13T13:53:23-07:00' + description: The optional date and time this card was created at. + type: + type: string + description: '`skill_card`' + example: skill_card + enum: + - skill_card + skill_card_type: + type: string + description: '`transcript`' + example: transcript + enum: + - transcript + skill_card_title: + type: object + description: The title of the card. + required: + - message + properties: + code: + type: string + example: my_transcripts + description: An optional identifier for the title. + message: + type: string + example: My Transcripts + description: The actual title to show in the UI. + skill: + type: object + description: The service that applied this metadata. + required: + - type + - id + properties: + type: + type: string + example: service + description: '`service`' + enum: + - service + id: + type: string + example: transciption-service + description: A custom identifier that represent the service that applied this metadata. + invocation: + type: object + description: 'The invocation of this service, used to track which instance of a service applied the metadata.' + required: + - type + - id + properties: + type: + type: string + example: skill_invocation + description: '`skill_invocation`' + enum: + - skill_invocation + id: + type: string + example: transciption-service-123 + description: 'A custom identifier that represent the instance of the service that applied this metadata. For example, if your `image-recognition-service` runs on multiple nodes, this field can be used to identify the ID of the node that was used to apply the metadata.' + duration: + type: integer + example: 1000 + description: An optional total duration in seconds. Used with a `skill_card_type` of `transcript` or `timeline`. + entries: + type: array + description: An list of entries for the card. This represents the individual entries of the transcription. + items: + type: object + description: An entry in the `entries` attribute of a metadata card + properties: + text: + type: string + example: 'Hi, and welcome to this video...' + description: The text of the entry. This would be the transcribed text assigned to the entry on the timeline. + appears: + type: array + description: Defines when a transcribed bit of text appears. This only includes a start time and no end time. + required: + - start + items: + type: object + description: The timestamp for an entry. + properties: + start: + type: integer + example: 1 + description: The time in seconds when an entry should start appearing on a timeline. + StatusSkillCard: + type: object + x-box-resource-id: status_skill_card + x-box-tag: skills + title: Status Skill Card + description: A Box Skill metadata card that puts a status message in the metadata sidebar. + required: + - type + - skill_card_type + - skill + - invocation + - status + properties: + created_at: + type: string + format: date-time + example: '2018-04-13T13:53:23-07:00' + description: The optional date and time this card was created at. + type: + type: string + description: '`skill_card`' + example: skill_card + enum: + - skill_card + skill_card_type: + type: string + description: '`status`' + example: status + enum: + - status + skill_card_title: + type: object + description: The title of the card. + required: + - message + properties: + code: + type: string + example: status + description: An optional identifier for the title. + message: + type: string + example: Status + description: The actual title to show in the UI. + status: + type: object + description: 'Sets the status of the skill. This can be used to show a message to the user while the Skill is processing the data, or if it was not able to process the file.' + required: + - code + properties: + code: + type: string + description: A code for the status of this Skill invocation. By default each of these will have their own accompanied messages. These can be adjusted by setting the `message` value on this object. + example: success + enum: + - invoked + - processing + - success + - transient_failure + - permanent_failure + message: + type: string + description: A custom message that can be provided with this status. This will be shown in the web app to the end user. + example: We're preparing to process your file. Please hold on! + skill: + type: object + description: The service that applied this metadata. + required: + - type + - id + properties: + type: + type: string + example: service + description: '`service`' + enum: + - service + id: + type: string + example: image-recognition-service + description: A custom identifier that represent the service that applied this metadata. + invocation: + type: object + description: 'The invocation of this service, used to track which instance of a service applied the metadata.' + required: + - type + - id + properties: + type: + type: string + example: skill_invocation + description: '`skill_invocation`' + enum: + - skill_invocation + id: + type: string + example: image-recognition-service-123 + description: 'A custom identifier that represent the instance of the service that applied this metadata. For example, if your `image-recognition-service` runs on multiple nodes, this field can be used to identify the ID of the node that was used to apply the metadata.' + SessionEndpoint: + description: Session endpoints. + type: object + properties: + upload_part: + type: string + description: The URL to upload parts to + example: 'https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD' + commit: + type: string + description: The URL used to commit the file + example: 'https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/commit' + abort: + type: string + description: The URL for used to abort the session. + example: 'https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD' + list_parts: + type: string + description: The URL users to list all parts. + example: 'https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/parts' + status: + type: string + description: The URL used to get the status of the upload. + example: 'https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD' + log_event: + type: string + description: The URL used to get the upload log from. + example: 'https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/log' + CollaborationAllowlistEnterprise: + title: CollaborationAllowlistEnterprise + description: A representation of a Box enterprise + type: object + properties: + id: + type: string + description: The unique identifier for this enterprise. + example: '11446498' + type: + type: string + description: '`enterprise`' + example: enterprise + enum: + - enterprise + name: + description: The name of the enterprise + example: Acme Inc. + type: string + CollaborationAllowlistUser: + title: CollaborationAllowlistUser + type: object + description: A representation of a Box enterprise + properties: + id: + type: string + description: The unique identifier for this enterprise. + example: '11446498' + type: + type: string + description: '`enterprise`' + example: enterprise + enum: + - enterprise + name: + description: The name of the enterprise + example: Acme Inc. + type: string + AssignedTo: + title: Reference + description: The bare basic reference for an object + type: object + properties: + id: + type: string + description: The unique identifier for this object + example: '11446498' + type: + type: string + description: The type for this object + example: file + NameConflict: + type: array + description: 'An individual conflict that occurred when trying to create the archive. This includes an array of 2 objects, each containing the original name and the renamed filename of a file or folder for which the names conflicted.' + items: + type: object + description: 'A file or folder for which a conflict was encountered, This object provides the type and identifier of the original item, as well as a mapping between its original name and it''s new name as it will appear in the archive.' + properties: + id: + type: string + description: The identifier of the item + example: '12345' + type: + type: string + description: The type of this item + example: file + enum: + - file + - folder + original_name: + type: string + description: The original name of this item + example: Report.pdf + download_name: + type: string + description: The new name of this item as it will appear in the downloaded `zip` archive. + example: 3aa6a7.pdf +security: + - OAuth2Security: [] +tags: + - name: Authorization + x-box-tag: authorization + x-box-priority: true + - name: Classifications + x-box-tag: classifications + - name: Classifications on files + x-box-tag: file_classifications + - name: Classifications on folders + x-box-tag: folder_classifications + - name: Collaborations + x-box-tag: user_collaborations + - name: Collaborations (List) + x-box-tag: list_collaborations + - name: Collections + x-box-tag: collections + - name: Comments + x-box-tag: comments + - name: Device pinners + x-box-tag: device_pinners + - name: Domain restrictions (User exemptions) + x-box-tag: collaboration_allowlist_exempt_targets + - name: Domain restrictions for collaborations + x-box-tag: collaboration_allowlist_entries + - name: Downloads + x-box-tag: downloads + - name: Email aliases + x-box-tag: email_aliases + - name: Events + x-box-tag: events + - name: File requests + x-box-tag: file_requests + - name: File version legal holds + x-box-tag: file_version_legal_holds + - name: File version retentions + x-box-tag: file_version_retentions + - name: File versions + x-box-tag: file_versions + - name: Files + x-box-tag: files + - name: Folder Locks + x-box-tag: folder_locks + - name: Folders + x-box-tag: folders + - name: Group memberships + x-box-tag: memberships + - name: Groups + x-box-tag: groups + - name: Invites + x-box-tag: invites + - name: Legal hold policies + x-box-tag: legal_hold_policies + - name: Legal hold policy assignments + x-box-tag: legal_hold_policy_assignments + - name: Metadata cascade policies + x-box-tag: metadata_cascade_policies + - name: Metadata instances (Files) + x-box-tag: file_metadata + - name: Metadata instances (Folders) + x-box-tag: folder_metadata + - name: Metadata templates + x-box-tag: metadata_templates + - name: Recent items + x-box-tag: recent_items + - name: Retention policies + x-box-tag: retention_policies + - name: Retention policy assignments + x-box-tag: retention_policy_assignments + - name: Search + x-box-tag: search + - name: Shared links (Files) + x-box-tag: shared_links_files + - name: Shared links (Folders) + x-box-tag: shared_links_folders + - name: Skills + x-box-tag: skills + - name: Storage policies + x-box-tag: storage_policies + - name: Storage policy assignments + x-box-tag: storage_policy_assignments + - name: Task assignments + x-box-tag: task_assignments + - name: Tasks + x-box-tag: tasks + - name: Terms of service + x-box-tag: terms_of_services + - name: Terms of service user statuses + x-box-tag: terms_of_service_user_statuses + - name: Transfer folders + x-box-tag: transfer + - name: Trashed files + x-box-tag: trashed_files + - name: Trashed folders + x-box-tag: trashed_folders + - name: Trashed items + x-box-tag: trashed_items + - name: Trashed web links + x-box-tag: trashed_web_links + - name: Uploads + x-box-tag: uploads + - name: Uploads (Chunked) + x-box-tag: chunked_uploads + - name: User avatars + x-box-tag: avatars + - name: Users + x-box-tag: users + - name: Watermarks (Files) + x-box-tag: file_watermarks + - name: Watermarks (Folders) + x-box-tag: folder_watermarks + - name: Web links + x-box-tag: web_links + - name: Webhooks + x-box-tag: webhooks + - name: Zip Downloads + x-box-tag: zip_downloads +externalDocs: + description: Box Developer Documentation + url: 'https://developer.box.com' diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/files.com.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/files.com.yaml new file mode 100644 index 000000000..3ebadedab --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/files.com.yaml @@ -0,0 +1,34967 @@ +# There is a problem in responses of type double. From the API responses it sometimes maps to type string. +openapi: 3.0.1 +info: + x-ballerina-display: + label: files.com + iconPath: "icon.png" + title: Files.com API + contact: + name: Files.com Customer Success Team + email: support@files.com + version: 0.0.1 + description: > + This is a generated connector from [Files.com API v1.0](https://www.files.com/) OpenAPI specification. + + Welcome to the Files.com API. Our REST API are designed for people who require the highest level of integration between Files.com and their own application, website, or database. + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Obtain API keys following [this guide](https://developers.files.com/#authentication-with-api-key). +servers: + - url: / +tags: + - name: action_notification_exports + description: Operations about action_notification_exports + - name: action_notification_export_results + description: Operations about action_notification_export_results + - name: action_webhook_failures + description: Operations about action_webhook_failures + - name: api_key + description: Operations about api_keys + - name: api_keys + description: Operations about api_keys + - name: site + description: Operations about sites + - name: user + description: Operations about users + - name: users + description: Operations about users + - name: apps + description: Operations about apps + - name: as2_keys + description: Operations about as2_keys + - name: automations + description: Operations about automations + - name: bandwidth_snapshots + description: Operations about bandwidth_snapshots + - name: behaviors + description: Operations about behaviors + - name: bundles + description: Operations about bundles + - name: bundle_downloads + description: Operations about bundle_downloads + - name: bundle_recipients + description: Operations about bundle_recipients + - name: bundle_registrations + description: Operations about bundle_registrations + - name: clickwraps + description: Operations about clickwraps + - name: dns_records + description: Operations about dns_records + - name: external_events + description: Operations about external_events + - name: files + description: Operations about files + - name: file_actions + description: Operations about file_actions + - name: file_comments + description: Operations about file_comments + - name: file_comment_reactions + description: Operations about file_comment_reactions + - name: file_migrations + description: Operations about file_migrations + - name: folders + description: Operations about folders + - name: form_field_sets + description: Operations about form_field_sets + - name: groups + description: Operations about groups + - name: group_users + description: Operations about group_users + - name: history + description: Operations about histories + - name: history_exports + description: Operations about history_exports + - name: history_export_results + description: Operations about history_export_results + - name: inbox_recipients + description: Operations about inbox_recipients + - name: inbox_registrations + description: Operations about inbox_registrations + - name: inbox_uploads + description: Operations about inbox_uploads + - name: invoices + description: Operations about invoices + - name: ip_addresses + description: Operations about ip_addresses + - name: locks + description: Operations about locks + - name: messages + description: Operations about messages + - name: message_comments + description: Operations about message_comments + - name: message_comment_reactions + description: Operations about message_comment_reactions + - name: message_reactions + description: Operations about message_reactions + - name: notifications + description: Operations about notifications + - name: payments + description: Operations about payments + - name: permissions + description: Operations about permissions + - name: projects + description: Operations about projects + - name: public_keys + description: Operations about public_keys + - name: remote_servers + description: Operations about remote_servers + - name: requests + description: Operations about requests + - name: sessions + description: Operations about sessions + - name: settings_changes + description: Operations about settings_changes + - name: sso_strategies + description: Operations about sso_strategies + - name: styles + description: Operations about styles + - name: sync_jobs + description: Operations about sync_jobs + - name: usage_snapshots + description: Operations about usage_snapshots + - name: usage_daily_snapshots + description: Operations about usage_daily_snapshots + - name: user_cipher_uses + description: Operations about user_cipher_uses + - name: user_requests + description: Operations about user_requests + - name: webhook_tests + description: Operations about webhook_tests +security: + - api_key: [] + +paths: + /action_notification_exports: + post: + tags: + - action_notification_exports + summary: Create Action Notification Export + description: Create Action Notification Export + operationId: PostActionNotificationExports + requestBody: + content: + application/json: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Start date/time of export range. + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: End date/time of export range. + query_message: + type: string + description: Error message associated with the request, if any. + example: Connection Refused + x-ms-summary: Error message associated with the request, if any. + query_request_method: + type: string + description: The HTTP request method used by the webhook. + example: GET + x-ms-summary: The HTTP request method used by the webhook. + query_request_url: + type: string + description: The target webhook URL. + example: http://example.com/webhook + x-ms-summary: The target webhook URL. + query_status: + type: string + description: The HTTP status returned from the server in response + to the webhook request. + example: "200" + x-ms-summary: The HTTP status returned from the server in response + to the webhook request. + query_success: + type: boolean + description: true if the webhook request succeeded (i.e. returned + a 200 or 204 response status). false otherwise. + example: true + x-ms-summary: true if the webhook request succeeded (i.e. returned + a 200 or 204 response status). false otherwise. + query_path: + type: string + description: Return notifications that were triggered by actions + on this specific path. + example: MyFile.txt + x-ms-summary: Return notifications that were triggered by actions + on this specific path. + query_folder: + type: string + description: Return notifications that were triggered by actions + in this folder. + example: MyFolder + x-ms-summary: Return notifications that were triggered by actions + in this folder. + application/x-www-form-urlencoded: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Start date/time of export range. + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: End date/time of export range. + query_message: + type: string + description: Error message associated with the request, if any. + example: Connection Refused + x-ms-summary: Error message associated with the request, if any. + query_request_method: + type: string + description: The HTTP request method used by the webhook. + example: GET + x-ms-summary: The HTTP request method used by the webhook. + query_request_url: + type: string + description: The target webhook URL. + example: http://example.com/webhook + x-ms-summary: The target webhook URL. + query_status: + type: string + description: The HTTP status returned from the server in response + to the webhook request. + example: "200" + x-ms-summary: The HTTP status returned from the server in response + to the webhook request. + query_success: + type: boolean + description: true if the webhook request succeeded (i.e. returned + a 200 or 204 response status). false otherwise. + example: true + x-ms-summary: true if the webhook request succeeded (i.e. returned + a 200 or 204 response status). false otherwise. + query_path: + type: string + description: Return notifications that were triggered by actions + on this specific path. + example: MyFile.txt + x-ms-summary: Return notifications that were triggered by actions + on this specific path. + query_folder: + type: string + description: Return notifications that were triggered by actions + in this folder. + example: MyFolder + x-ms-summary: Return notifications that were triggered by actions + in this folder. + multipart/form-data: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Start date/time of export range. + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: End date/time of export range. + query_message: + type: string + description: Error message associated with the request, if any. + example: Connection Refused + x-ms-summary: Error message associated with the request, if any. + query_request_method: + type: string + description: The HTTP request method used by the webhook. + example: GET + x-ms-summary: The HTTP request method used by the webhook. + query_request_url: + type: string + description: The target webhook URL. + example: http://example.com/webhook + x-ms-summary: The target webhook URL. + query_status: + type: string + description: The HTTP status returned from the server in response + to the webhook request. + example: "200" + x-ms-summary: The HTTP status returned from the server in response + to the webhook request. + query_success: + type: boolean + description: true if the webhook request succeeded (i.e. returned + a 200 or 204 response status). false otherwise. + example: true + x-ms-summary: true if the webhook request succeeded (i.e. returned + a 200 or 204 response status). false otherwise. + query_path: + type: string + description: Return notifications that were triggered by actions + on this specific path. + example: MyFile.txt + x-ms-summary: Return notifications that were triggered by actions + on this specific path. + query_folder: + type: string + description: Return notifications that were triggered by actions + in this folder. + example: MyFolder + x-ms-summary: Return notifications that were triggered by actions + in this folder. + responses: + 201: + description: The ActionNotificationExports object. + content: + application/json: + schema: + $ref: '#/components/schemas/ActionNotificationExportEntity' + x-ms-summary: The ActionNotificationExports object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + - path_params: + - query_path + - query_folder + /action_notification_exports/{id}: + get: + tags: + - action_notification_exports + summary: Show Action Notification Export + description: Show Action Notification Export + operationId: GetActionNotificationExportsId + parameters: + - name: id + in: path + description: Action Notification Export ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Action Notification Export ID. + x-ms-summary: Action Notification Export ID. + responses: + 200: + description: The ActionNotificationExports object. + content: + application/json: + schema: + $ref: '#/components/schemas/ActionNotificationExportEntity' + x-ms-summary: The ActionNotificationExports object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + /action_notification_export_results: + get: + tags: + - action_notification_export_results + summary: List Action Notification Export Results + description: List Action Notification Export Results + operationId: GetActionNotificationExportResults + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: action_notification_export_id + in: query + description: ID of the associated action notification export. + required: true + schema: + type: integer + format: int32 + x-ms-summary: ID of the associated action notification export. + x-ms-summary: ID of the associated action notification export. + responses: + 200: + description: A list of ActionNotificationExportResults objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ActionNotificationExportResultEntity' + x-ms-summary: A list of ActionNotificationExportResults objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + /action_webhook_failures/{id}/retry: + post: + tags: + - action_webhook_failures + summary: retry Action Webhook Failure + description: retry Action Webhook Failure + operationId: PostActionWebhookFailuresIdRetry + parameters: + - name: id + in: path + description: Action Webhook Failure ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Action Webhook Failure ID. + x-ms-summary: Action Webhook Failure ID. + responses: + 201: + description: The ActionWebhookFailures object. + content: {} + x-ms-summary: The ActionWebhookFailures object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /api_key: + get: + tags: + - api_key + summary: Show information about current API key. (Requires current API connection + to be using an API key.) + description: Show information about current API key. (Requires current API + connection to be using an API key.) + operationId: ApiKeyFindCurrent + responses: + 200: + description: The ApiKey object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKey object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + delete: + tags: + - api_key + summary: Delete current API key. (Requires current API connection to be using + an API key.) + description: Delete current API key. (Requires current API connection to be + using an API key.) + operationId: ApiKeyDeleteCurrent + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + patch: + tags: + - api_key + summary: Update current API key. (Requires current API connection to be using + an API key.) + description: Update current API key. (Requires current API connection to be + using an API key.) + operationId: ApiKeyUpdateCurrent + requestBody: + content: + application/json: + schema: + properties: + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + application/x-www-form-urlencoded: + schema: + properties: + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + multipart/form-data: + schema: + properties: + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + responses: + 200: + description: The ApiKey object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKey object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + /api_keys/{id}: + get: + tags: + - api_keys + summary: Show Api Key + description: Show Api Key + operationId: GetApiKeysId + parameters: + - name: id + in: path + description: Api Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Api Key ID. + x-ms-summary: Api Key ID. + responses: + 200: + description: The ApiKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + delete: + tags: + - api_keys + summary: Delete Api Key + description: Delete Api Key + operationId: DeleteApiKeysId + parameters: + - name: id + in: path + description: Api Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Api Key ID. + x-ms-summary: Api Key ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + patch: + tags: + - api_keys + summary: Update Api Key + description: Update Api Key + operationId: PatchApiKeysId + parameters: + - name: id + in: path + description: Api Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Api Key ID. + x-ms-summary: Api Key ID. + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + multipart/form-data: + schema: + properties: + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + responses: + 200: + description: The ApiKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + /api_keys: + get: + tags: + - api_keys + summary: List Api Keys + description: List Api Keys + operationId: GetApiKeys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + responses: + 200: + description: A list of ApiKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: A list of ApiKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + post: + tags: + - api_keys + summary: Create Api Key + description: Create Api Key + operationId: PostApiKeys + requestBody: + content: + application/json: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + application/x-www-form-urlencoded: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + multipart/form-data: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + responses: + 201: + description: The ApiKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + /site/usage: + get: + tags: + - site + summary: Get the most recent usage snapshot (usage data for billing purposes) + for a Site. + description: Get the most recent usage snapshot (usage data for billing purposes) + for a Site. + operationId: GetSiteUsage + responses: + 200: + description: The Site object. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageSnapshotEntity' + x-ms-summary: The Site object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + - billing + /site: + get: + tags: + - site + summary: Show site settings + description: Show site settings + operationId: GetSite + responses: + 200: + description: The Site object. + content: + application/json: + schema: + $ref: '#/components/schemas/SiteEntity' + x-ms-summary: The Site object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + patch: + tags: + - site + summary: Update site settings. + description: Update site settings. + operationId: PatchSite + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Site name + x-ms-summary: Site name + subdomain: + type: string + description: Site subdomain + x-ms-summary: Site subdomain + domain: + type: string + description: Custom domain + x-ms-summary: Custom domain + email: + type: string + description: Main email for this site + x-ms-summary: Main email for this site + reply_to_email: + type: string + description: Reply-to email for this site + x-ms-summary: Reply-to email for this site + allow_bundle_names: + type: boolean + description: Are manual Bundle names allowed? + x-ms-summary: Are manual Bundle names allowed? + bundle_expiration: + type: integer + description: Site-wide Bundle expiration in days + format: int32 + x-ms-summary: Site-wide Bundle expiration in days + overage_notify: + type: boolean + description: Notify site email of overages? + x-ms-summary: Notify site email of overages? + welcome_email_enabled: + type: boolean + description: Will the welcome email be sent to new users? + x-ms-summary: Will the welcome email be sent to new users? + ask_about_overwrites: + type: boolean + description: If false, rename conflicting files instead of asking + for overwrite confirmation. Only applies to web interface. + x-ms-summary: If false, rename conflicting files instead of asking + for overwrite confirmation. Only applies to web interface. + show_request_access_link: + type: boolean + description: Show request access link for users without access? Currently + unused. + x-ms-summary: Show request access link for users without access? Currently + unused. + welcome_email_cc: + type: string + description: Include this email in welcome emails if enabled + x-ms-summary: Include this email in welcome emails if enabled + welcome_custom_text: + type: string + description: Custom text send in user welcome email + x-ms-summary: Custom text send in user welcome email + language: + type: string + description: Site default language + x-ms-summary: Site default language + windows_mode_ftp: + type: boolean + description: Does FTP user Windows emulation mode? + x-ms-summary: Does FTP user Windows emulation mode? + default_time_zone: + type: string + description: Site default time zone + x-ms-summary: Site default time zone + desktop_app: + type: boolean + description: Is the desktop app enabled? + x-ms-summary: Is the desktop app enabled? + desktop_app_session_ip_pinning: + type: boolean + description: Is desktop app session IP pinning enabled? + x-ms-summary: Is desktop app session IP pinning enabled? + desktop_app_session_lifetime: + type: integer + description: Desktop app session lifetime (in hours) + format: int32 + x-ms-summary: Desktop app session lifetime (in hours) + mobile_app: + type: boolean + description: Is the mobile app enabled? + x-ms-summary: Is the mobile app enabled? + mobile_app_session_ip_pinning: + type: boolean + description: Is mobile app session IP pinning enabled? + x-ms-summary: Is mobile app session IP pinning enabled? + mobile_app_session_lifetime: + type: integer + description: Mobile app session lifetime (in hours) + format: int32 + x-ms-summary: Mobile app session lifetime (in hours) + folder_permissions_groups_only: + type: boolean + description: If true, permissions for this site must be bound to + a group (not a user). Otherwise, permissions must be bound to + a user. + x-ms-summary: If true, permissions for this site must be bound to + a group (not a user). Otherwise, permissions must be bound to + a user. + welcome_screen: + type: string + description: Does the welcome screen appear? + x-ms-summary: Does the welcome screen appear? + office_integration_available: + type: boolean + description: Allow users to use Office for the web? + x-ms-summary: Allow users to use Office for the web? + session_expiry: + type: number + description: Session expiry in hours + format: double + x-ms-summary: Session expiry in hours + ssl_required: + type: boolean + description: Is SSL required? Disabling this is insecure. + x-ms-summary: Is SSL required? Disabling this is insecure. + tls_disabled: + type: boolean + description: Is TLS disabled(site setting)? + x-ms-summary: Is TLS disabled(site setting)? + user_lockout: + type: boolean + description: Will users be locked out after incorrect login attempts? + x-ms-summary: Will users be locked out after incorrect login attempts? + user_lockout_tries: + type: integer + description: Number of login tries within `user_lockout_within` + hours before users are locked out + format: int32 + x-ms-summary: Number of login tries within `user_lockout_within` + hours before users are locked out + user_lockout_within: + type: integer + description: Number of hours for user lockout window + format: int32 + x-ms-summary: Number of hours for user lockout window + user_lockout_lock_period: + type: integer + description: How many hours to lock user out for failed password? + format: int32 + x-ms-summary: How many hours to lock user out for failed password? + include_password_in_welcome_email: + type: boolean + description: Include password in emails to new users? + x-ms-summary: Include password in emails to new users? + allowed_countries: + type: string + description: Comma seperated list of allowed Country codes + x-ms-summary: Comma seperated list of allowed Country codes + allowed_ips: + type: string + description: List of allowed IP addresses + x-ms-summary: List of allowed IP addresses + disallowed_countries: + type: string + description: Comma seperated list of disallowed Country codes + x-ms-summary: Comma seperated list of disallowed Country codes + days_to_retain_backups: + type: integer + description: Number of days to keep deleted files + format: int32 + x-ms-summary: Number of days to keep deleted files + max_prior_passwords: + type: integer + description: Number of prior passwords to disallow + format: int32 + x-ms-summary: Number of prior passwords to disallow + password_validity_days: + type: integer + description: Number of days password is valid + format: int32 + x-ms-summary: Number of days password is valid + password_min_length: + type: integer + description: Shortest password length for users + format: int32 + x-ms-summary: Shortest password length for users + password_require_letter: + type: boolean + description: Require a letter in passwords? + x-ms-summary: Require a letter in passwords? + password_require_mixed: + type: boolean + description: Require lower and upper case letters in passwords? + x-ms-summary: Require lower and upper case letters in passwords? + password_require_special: + type: boolean + description: Require special characters in password? + x-ms-summary: Require special characters in password? + password_require_number: + type: boolean + description: Require a number in passwords? + x-ms-summary: Require a number in passwords? + password_require_unbreached: + type: boolean + description: Require passwords that have not been previously breached? + (see https://haveibeenpwned.com/) + x-ms-summary: Require passwords that have not been previously breached? + (see https://haveibeenpwned.com/) + sftp_user_root_enabled: + type: boolean + description: Use user FTP roots also for SFTP? + x-ms-summary: Use user FTP roots also for SFTP? + disable_password_reset: + type: boolean + description: Is password reset disabled? + x-ms-summary: Is password reset disabled? + immutable_files: + type: boolean + description: Are files protected from modification? + x-ms-summary: Are files protected from modification? + session_pinned_by_ip: + type: boolean + description: Are sessions locked to the same IP? (i.e. do users + need to log in again if they change IPs?) + x-ms-summary: Are sessions locked to the same IP? (i.e. do users + need to log in again if they change IPs?) + bundle_password_required: + type: boolean + description: Do Bundles require password protection? + x-ms-summary: Do Bundles require password protection? + bundle_require_share_recipient: + type: boolean + description: Do Bundles require recipients for sharing? + x-ms-summary: Do Bundles require recipients for sharing? + password_requirements_apply_to_bundles: + type: boolean + description: Require bundles' passwords, and passwords for other + items (inboxes, public shares, etc.) to conform to the same requirements + as users' passwords? + x-ms-summary: Require bundles' passwords, and passwords for other + items (inboxes, public shares, etc.) to conform to the same requirements + as users' passwords? + opt_out_global: + type: boolean + description: Use servers in the USA only? + x-ms-summary: Use servers in the USA only? + use_provided_modified_at: + type: boolean + description: Allow uploaders to set `provided_modified_at` for uploaded + files? + x-ms-summary: Allow uploaders to set `provided_modified_at` for + uploaded files? + custom_namespace: + type: boolean + description: Is this site using a custom namespace for users? + x-ms-summary: Is this site using a custom namespace for users? + disable_users_from_inactivity_period_days: + type: integer + description: If greater than zero, users will unable to login if + they do not show activity within this number of days. + format: int32 + x-ms-summary: If greater than zero, users will unable to login if + they do not show activity within this number of days. + non_sso_groups_allowed: + type: boolean + description: If true, groups can be manually created / modified + / deleted by Site Admins. Otherwise, groups can only be managed + via your SSO provider. + x-ms-summary: If true, groups can be manually created / modified + / deleted by Site Admins. Otherwise, groups can only be managed + via your SSO provider. + non_sso_users_allowed: + type: boolean + description: If true, users can be manually created / modified / + deleted by Site Admins. Otherwise, users can only be managed via + your SSO provider. + x-ms-summary: If true, users can be manually created / modified + / deleted by Site Admins. Otherwise, users can only be managed + via your SSO provider. + sharing_enabled: + type: boolean + description: Allow bundle creation + x-ms-summary: Allow bundle creation + user_requests_enabled: + type: boolean + description: Enable User Requests feature + x-ms-summary: Enable User Requests feature + allowed_2fa_method_sms: + type: boolean + description: Is SMS two factor authentication allowed? + x-ms-summary: Is SMS two factor authentication allowed? + allowed_2fa_method_u2f: + type: boolean + description: Is U2F two factor authentication allowed? + x-ms-summary: Is U2F two factor authentication allowed? + allowed_2fa_method_totp: + type: boolean + description: Is TOTP two factor authentication allowed? + x-ms-summary: Is TOTP two factor authentication allowed? + allowed_2fa_method_yubi: + type: boolean + description: Is yubikey two factor authentication allowed? + x-ms-summary: Is yubikey two factor authentication allowed? + require_2fa: + type: boolean + description: Require two-factor authentication for all users? + x-ms-summary: Require two-factor authentication for all users? + require_2fa_user_type: + type: string + description: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + x-ms-summary: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + color2_top: + type: string + description: Top bar background color + x-ms-summary: Top bar background color + color2_left: + type: string + description: Page link and button color + x-ms-summary: Page link and button color + color2_link: + type: string + description: Top bar link color + x-ms-summary: Top bar link color + color2_text: + type: string + description: Page link and button color + x-ms-summary: Page link and button color + color2_top_text: + type: string + description: Top bar text color + x-ms-summary: Top bar text color + site_header: + type: string + description: Custom site header text + x-ms-summary: Custom site header text + site_footer: + type: string + description: Custom site footer text + x-ms-summary: Custom site footer text + login_help_text: + type: string + description: Login help text + x-ms-summary: Login help text + smtp_address: + type: string + description: SMTP server hostname or IP + x-ms-summary: SMTP server hostname or IP + smtp_authentication: + type: string + description: SMTP server authentication type + x-ms-summary: SMTP server authentication type + smtp_from: + type: string + description: From address to use when mailing through custom SMTP + x-ms-summary: From address to use when mailing through custom SMTP + smtp_username: + type: string + description: SMTP server username + x-ms-summary: SMTP server username + smtp_port: + type: integer + description: SMTP server port + format: int32 + x-ms-summary: SMTP server port + ldap_enabled: + type: boolean + description: 'Main LDAP setting: is LDAP enabled?' + x-ms-summary: 'Main LDAP setting: is LDAP enabled?' + ldap_type: + type: string + description: LDAP type + x-ms-summary: LDAP type + ldap_host: + type: string + description: LDAP host + x-ms-summary: LDAP host + ldap_host_2: + type: string + description: LDAP backup host + x-ms-summary: LDAP backup host + ldap_host_3: + type: string + description: LDAP backup host + x-ms-summary: LDAP backup host + ldap_port: + type: integer + description: LDAP port + format: int32 + x-ms-summary: LDAP port + ldap_secure: + type: boolean + description: Use secure LDAP? + x-ms-summary: Use secure LDAP? + ldap_username: + type: string + description: Username for signing in to LDAP server. + x-ms-summary: Username for signing in to LDAP server. + ldap_username_field: + type: string + description: LDAP username field + x-ms-summary: LDAP username field + ldap_domain: + type: string + description: Domain name that will be appended to usernames + x-ms-summary: Domain name that will be appended to usernames + ldap_user_action: + type: string + description: Should we sync users from LDAP server? + x-ms-summary: Should we sync users from LDAP server? + ldap_group_action: + type: string + description: Should we sync groups from LDAP server? + x-ms-summary: Should we sync groups from LDAP server? + ldap_user_include_groups: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) - if provided, only users in these groups + will be added or synced. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) - if provided, only users in these groups + will be added or synced. + ldap_group_exclusion: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) to exclude when syncing. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) to exclude when syncing. + ldap_group_inclusion: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) to include when syncing. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) to include when syncing. + ldap_base_dn: + type: string + description: Base DN for looking up users in LDAP server + x-ms-summary: Base DN for looking up users in LDAP server + icon16_file: + type: string + format: binary + x-ms-summary: null + icon16_delete: + type: boolean + description: If true, will delete the file stored in icon16 + x-ms-summary: If true, will delete the file stored in icon16 + icon32_file: + type: string + format: binary + x-ms-summary: null + icon32_delete: + type: boolean + description: If true, will delete the file stored in icon32 + x-ms-summary: If true, will delete the file stored in icon32 + icon48_file: + type: string + format: binary + x-ms-summary: null + icon48_delete: + type: boolean + description: If true, will delete the file stored in icon48 + x-ms-summary: If true, will delete the file stored in icon48 + icon128_file: + type: string + format: binary + x-ms-summary: null + icon128_delete: + type: boolean + description: If true, will delete the file stored in icon128 + x-ms-summary: If true, will delete the file stored in icon128 + logo_file: + type: string + format: binary + x-ms-summary: null + logo_delete: + type: boolean + description: If true, will delete the file stored in logo + x-ms-summary: If true, will delete the file stored in logo + disable_2fa_with_delay: + type: boolean + description: If set to true, we will begin the process of disabling + 2FA on this site. + x-ms-summary: If set to true, we will begin the process of disabling + 2FA on this site. + ldap_password_change: + type: string + description: New LDAP password. + x-ms-summary: New LDAP password. + ldap_password_change_confirmation: + type: string + description: Confirm new LDAP password. + x-ms-summary: Confirm new LDAP password. + smtp_password: + type: string + description: Password for SMTP server. + x-ms-summary: Password for SMTP server. + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Site name + x-ms-summary: Site name + subdomain: + type: string + description: Site subdomain + x-ms-summary: Site subdomain + domain: + type: string + description: Custom domain + x-ms-summary: Custom domain + email: + type: string + description: Main email for this site + x-ms-summary: Main email for this site + reply_to_email: + type: string + description: Reply-to email for this site + x-ms-summary: Reply-to email for this site + allow_bundle_names: + type: boolean + description: Are manual Bundle names allowed? + x-ms-summary: Are manual Bundle names allowed? + bundle_expiration: + type: integer + description: Site-wide Bundle expiration in days + format: int32 + x-ms-summary: Site-wide Bundle expiration in days + overage_notify: + type: boolean + description: Notify site email of overages? + x-ms-summary: Notify site email of overages? + welcome_email_enabled: + type: boolean + description: Will the welcome email be sent to new users? + x-ms-summary: Will the welcome email be sent to new users? + ask_about_overwrites: + type: boolean + description: If false, rename conflicting files instead of asking + for overwrite confirmation. Only applies to web interface. + x-ms-summary: If false, rename conflicting files instead of asking + for overwrite confirmation. Only applies to web interface. + show_request_access_link: + type: boolean + description: Show request access link for users without access? Currently + unused. + x-ms-summary: Show request access link for users without access? Currently + unused. + welcome_email_cc: + type: string + description: Include this email in welcome emails if enabled + x-ms-summary: Include this email in welcome emails if enabled + welcome_custom_text: + type: string + description: Custom text send in user welcome email + x-ms-summary: Custom text send in user welcome email + language: + type: string + description: Site default language + x-ms-summary: Site default language + windows_mode_ftp: + type: boolean + description: Does FTP user Windows emulation mode? + x-ms-summary: Does FTP user Windows emulation mode? + default_time_zone: + type: string + description: Site default time zone + x-ms-summary: Site default time zone + desktop_app: + type: boolean + description: Is the desktop app enabled? + x-ms-summary: Is the desktop app enabled? + desktop_app_session_ip_pinning: + type: boolean + description: Is desktop app session IP pinning enabled? + x-ms-summary: Is desktop app session IP pinning enabled? + desktop_app_session_lifetime: + type: integer + description: Desktop app session lifetime (in hours) + format: int32 + x-ms-summary: Desktop app session lifetime (in hours) + mobile_app: + type: boolean + description: Is the mobile app enabled? + x-ms-summary: Is the mobile app enabled? + mobile_app_session_ip_pinning: + type: boolean + description: Is mobile app session IP pinning enabled? + x-ms-summary: Is mobile app session IP pinning enabled? + mobile_app_session_lifetime: + type: integer + description: Mobile app session lifetime (in hours) + format: int32 + x-ms-summary: Mobile app session lifetime (in hours) + folder_permissions_groups_only: + type: boolean + description: If true, permissions for this site must be bound to + a group (not a user). Otherwise, permissions must be bound to + a user. + x-ms-summary: If true, permissions for this site must be bound to + a group (not a user). Otherwise, permissions must be bound to + a user. + welcome_screen: + type: string + description: Does the welcome screen appear? + x-ms-summary: Does the welcome screen appear? + office_integration_available: + type: boolean + description: Allow users to use Office for the web? + x-ms-summary: Allow users to use Office for the web? + session_expiry: + type: number + description: Session expiry in hours + format: double + x-ms-summary: Session expiry in hours + ssl_required: + type: boolean + description: Is SSL required? Disabling this is insecure. + x-ms-summary: Is SSL required? Disabling this is insecure. + tls_disabled: + type: boolean + description: Is TLS disabled(site setting)? + x-ms-summary: Is TLS disabled(site setting)? + user_lockout: + type: boolean + description: Will users be locked out after incorrect login attempts? + x-ms-summary: Will users be locked out after incorrect login attempts? + user_lockout_tries: + type: integer + description: Number of login tries within `user_lockout_within` + hours before users are locked out + format: int32 + x-ms-summary: Number of login tries within `user_lockout_within` + hours before users are locked out + user_lockout_within: + type: integer + description: Number of hours for user lockout window + format: int32 + x-ms-summary: Number of hours for user lockout window + user_lockout_lock_period: + type: integer + description: How many hours to lock user out for failed password? + format: int32 + x-ms-summary: How many hours to lock user out for failed password? + include_password_in_welcome_email: + type: boolean + description: Include password in emails to new users? + x-ms-summary: Include password in emails to new users? + allowed_countries: + type: string + description: Comma seperated list of allowed Country codes + x-ms-summary: Comma seperated list of allowed Country codes + allowed_ips: + type: string + description: List of allowed IP addresses + x-ms-summary: List of allowed IP addresses + disallowed_countries: + type: string + description: Comma seperated list of disallowed Country codes + x-ms-summary: Comma seperated list of disallowed Country codes + days_to_retain_backups: + type: integer + description: Number of days to keep deleted files + format: int32 + x-ms-summary: Number of days to keep deleted files + max_prior_passwords: + type: integer + description: Number of prior passwords to disallow + format: int32 + x-ms-summary: Number of prior passwords to disallow + password_validity_days: + type: integer + description: Number of days password is valid + format: int32 + x-ms-summary: Number of days password is valid + password_min_length: + type: integer + description: Shortest password length for users + format: int32 + x-ms-summary: Shortest password length for users + password_require_letter: + type: boolean + description: Require a letter in passwords? + x-ms-summary: Require a letter in passwords? + password_require_mixed: + type: boolean + description: Require lower and upper case letters in passwords? + x-ms-summary: Require lower and upper case letters in passwords? + password_require_special: + type: boolean + description: Require special characters in password? + x-ms-summary: Require special characters in password? + password_require_number: + type: boolean + description: Require a number in passwords? + x-ms-summary: Require a number in passwords? + password_require_unbreached: + type: boolean + description: Require passwords that have not been previously breached? + (see https://haveibeenpwned.com/) + x-ms-summary: Require passwords that have not been previously breached? + (see https://haveibeenpwned.com/) + sftp_user_root_enabled: + type: boolean + description: Use user FTP roots also for SFTP? + x-ms-summary: Use user FTP roots also for SFTP? + disable_password_reset: + type: boolean + description: Is password reset disabled? + x-ms-summary: Is password reset disabled? + immutable_files: + type: boolean + description: Are files protected from modification? + x-ms-summary: Are files protected from modification? + session_pinned_by_ip: + type: boolean + description: Are sessions locked to the same IP? (i.e. do users + need to log in again if they change IPs?) + x-ms-summary: Are sessions locked to the same IP? (i.e. do users + need to log in again if they change IPs?) + bundle_password_required: + type: boolean + description: Do Bundles require password protection? + x-ms-summary: Do Bundles require password protection? + bundle_require_share_recipient: + type: boolean + description: Do Bundles require recipients for sharing? + x-ms-summary: Do Bundles require recipients for sharing? + password_requirements_apply_to_bundles: + type: boolean + description: Require bundles' passwords, and passwords for other + items (inboxes, public shares, etc.) to conform to the same requirements + as users' passwords? + x-ms-summary: Require bundles' passwords, and passwords for other + items (inboxes, public shares, etc.) to conform to the same requirements + as users' passwords? + opt_out_global: + type: boolean + description: Use servers in the USA only? + x-ms-summary: Use servers in the USA only? + use_provided_modified_at: + type: boolean + description: Allow uploaders to set `provided_modified_at` for uploaded + files? + x-ms-summary: Allow uploaders to set `provided_modified_at` for + uploaded files? + custom_namespace: + type: boolean + description: Is this site using a custom namespace for users? + x-ms-summary: Is this site using a custom namespace for users? + disable_users_from_inactivity_period_days: + type: integer + description: If greater than zero, users will unable to login if + they do not show activity within this number of days. + format: int32 + x-ms-summary: If greater than zero, users will unable to login if + they do not show activity within this number of days. + non_sso_groups_allowed: + type: boolean + description: If true, groups can be manually created / modified + / deleted by Site Admins. Otherwise, groups can only be managed + via your SSO provider. + x-ms-summary: If true, groups can be manually created / modified + / deleted by Site Admins. Otherwise, groups can only be managed + via your SSO provider. + non_sso_users_allowed: + type: boolean + description: If true, users can be manually created / modified / + deleted by Site Admins. Otherwise, users can only be managed via + your SSO provider. + x-ms-summary: If true, users can be manually created / modified + / deleted by Site Admins. Otherwise, users can only be managed + via your SSO provider. + sharing_enabled: + type: boolean + description: Allow bundle creation + x-ms-summary: Allow bundle creation + user_requests_enabled: + type: boolean + description: Enable User Requests feature + x-ms-summary: Enable User Requests feature + allowed_2fa_method_sms: + type: boolean + description: Is SMS two factor authentication allowed? + x-ms-summary: Is SMS two factor authentication allowed? + allowed_2fa_method_u2f: + type: boolean + description: Is U2F two factor authentication allowed? + x-ms-summary: Is U2F two factor authentication allowed? + allowed_2fa_method_totp: + type: boolean + description: Is TOTP two factor authentication allowed? + x-ms-summary: Is TOTP two factor authentication allowed? + allowed_2fa_method_yubi: + type: boolean + description: Is yubikey two factor authentication allowed? + x-ms-summary: Is yubikey two factor authentication allowed? + require_2fa: + type: boolean + description: Require two-factor authentication for all users? + x-ms-summary: Require two-factor authentication for all users? + require_2fa_user_type: + type: string + description: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + x-ms-summary: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + color2_top: + type: string + description: Top bar background color + x-ms-summary: Top bar background color + color2_left: + type: string + description: Page link and button color + x-ms-summary: Page link and button color + color2_link: + type: string + description: Top bar link color + x-ms-summary: Top bar link color + color2_text: + type: string + description: Page link and button color + x-ms-summary: Page link and button color + color2_top_text: + type: string + description: Top bar text color + x-ms-summary: Top bar text color + site_header: + type: string + description: Custom site header text + x-ms-summary: Custom site header text + site_footer: + type: string + description: Custom site footer text + x-ms-summary: Custom site footer text + login_help_text: + type: string + description: Login help text + x-ms-summary: Login help text + smtp_address: + type: string + description: SMTP server hostname or IP + x-ms-summary: SMTP server hostname or IP + smtp_authentication: + type: string + description: SMTP server authentication type + x-ms-summary: SMTP server authentication type + smtp_from: + type: string + description: From address to use when mailing through custom SMTP + x-ms-summary: From address to use when mailing through custom SMTP + smtp_username: + type: string + description: SMTP server username + x-ms-summary: SMTP server username + smtp_port: + type: integer + description: SMTP server port + format: int32 + x-ms-summary: SMTP server port + ldap_enabled: + type: boolean + description: 'Main LDAP setting: is LDAP enabled?' + x-ms-summary: 'Main LDAP setting: is LDAP enabled?' + ldap_type: + type: string + description: LDAP type + x-ms-summary: LDAP type + ldap_host: + type: string + description: LDAP host + x-ms-summary: LDAP host + ldap_host_2: + type: string + description: LDAP backup host + x-ms-summary: LDAP backup host + ldap_host_3: + type: string + description: LDAP backup host + x-ms-summary: LDAP backup host + ldap_port: + type: integer + description: LDAP port + format: int32 + x-ms-summary: LDAP port + ldap_secure: + type: boolean + description: Use secure LDAP? + x-ms-summary: Use secure LDAP? + ldap_username: + type: string + description: Username for signing in to LDAP server. + x-ms-summary: Username for signing in to LDAP server. + ldap_username_field: + type: string + description: LDAP username field + x-ms-summary: LDAP username field + ldap_domain: + type: string + description: Domain name that will be appended to usernames + x-ms-summary: Domain name that will be appended to usernames + ldap_user_action: + type: string + description: Should we sync users from LDAP server? + x-ms-summary: Should we sync users from LDAP server? + ldap_group_action: + type: string + description: Should we sync groups from LDAP server? + x-ms-summary: Should we sync groups from LDAP server? + ldap_user_include_groups: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) - if provided, only users in these groups + will be added or synced. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) - if provided, only users in these groups + will be added or synced. + ldap_group_exclusion: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) to exclude when syncing. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) to exclude when syncing. + ldap_group_inclusion: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) to include when syncing. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) to include when syncing. + ldap_base_dn: + type: string + description: Base DN for looking up users in LDAP server + x-ms-summary: Base DN for looking up users in LDAP server + icon16_file: + type: string + format: binary + x-ms-summary: null + icon16_delete: + type: boolean + description: If true, will delete the file stored in icon16 + x-ms-summary: If true, will delete the file stored in icon16 + icon32_file: + type: string + format: binary + x-ms-summary: null + icon32_delete: + type: boolean + description: If true, will delete the file stored in icon32 + x-ms-summary: If true, will delete the file stored in icon32 + icon48_file: + type: string + format: binary + x-ms-summary: null + icon48_delete: + type: boolean + description: If true, will delete the file stored in icon48 + x-ms-summary: If true, will delete the file stored in icon48 + icon128_file: + type: string + format: binary + x-ms-summary: null + icon128_delete: + type: boolean + description: If true, will delete the file stored in icon128 + x-ms-summary: If true, will delete the file stored in icon128 + logo_file: + type: string + format: binary + x-ms-summary: null + logo_delete: + type: boolean + description: If true, will delete the file stored in logo + x-ms-summary: If true, will delete the file stored in logo + disable_2fa_with_delay: + type: boolean + description: If set to true, we will begin the process of disabling + 2FA on this site. + x-ms-summary: If set to true, we will begin the process of disabling + 2FA on this site. + ldap_password_change: + type: string + description: New LDAP password. + x-ms-summary: New LDAP password. + ldap_password_change_confirmation: + type: string + description: Confirm new LDAP password. + x-ms-summary: Confirm new LDAP password. + smtp_password: + type: string + description: Password for SMTP server. + x-ms-summary: Password for SMTP server. + multipart/form-data: + schema: + properties: + name: + type: string + description: Site name + x-ms-summary: Site name + subdomain: + type: string + description: Site subdomain + x-ms-summary: Site subdomain + domain: + type: string + description: Custom domain + x-ms-summary: Custom domain + email: + type: string + description: Main email for this site + x-ms-summary: Main email for this site + reply_to_email: + type: string + description: Reply-to email for this site + x-ms-summary: Reply-to email for this site + allow_bundle_names: + type: boolean + description: Are manual Bundle names allowed? + x-ms-summary: Are manual Bundle names allowed? + bundle_expiration: + type: integer + description: Site-wide Bundle expiration in days + format: int32 + x-ms-summary: Site-wide Bundle expiration in days + overage_notify: + type: boolean + description: Notify site email of overages? + x-ms-summary: Notify site email of overages? + welcome_email_enabled: + type: boolean + description: Will the welcome email be sent to new users? + x-ms-summary: Will the welcome email be sent to new users? + ask_about_overwrites: + type: boolean + description: If false, rename conflicting files instead of asking + for overwrite confirmation. Only applies to web interface. + x-ms-summary: If false, rename conflicting files instead of asking + for overwrite confirmation. Only applies to web interface. + show_request_access_link: + type: boolean + description: Show request access link for users without access? Currently + unused. + x-ms-summary: Show request access link for users without access? Currently + unused. + welcome_email_cc: + type: string + description: Include this email in welcome emails if enabled + x-ms-summary: Include this email in welcome emails if enabled + welcome_custom_text: + type: string + description: Custom text send in user welcome email + x-ms-summary: Custom text send in user welcome email + language: + type: string + description: Site default language + x-ms-summary: Site default language + windows_mode_ftp: + type: boolean + description: Does FTP user Windows emulation mode? + x-ms-summary: Does FTP user Windows emulation mode? + default_time_zone: + type: string + description: Site default time zone + x-ms-summary: Site default time zone + desktop_app: + type: boolean + description: Is the desktop app enabled? + x-ms-summary: Is the desktop app enabled? + desktop_app_session_ip_pinning: + type: boolean + description: Is desktop app session IP pinning enabled? + x-ms-summary: Is desktop app session IP pinning enabled? + desktop_app_session_lifetime: + type: integer + description: Desktop app session lifetime (in hours) + format: int32 + x-ms-summary: Desktop app session lifetime (in hours) + mobile_app: + type: boolean + description: Is the mobile app enabled? + x-ms-summary: Is the mobile app enabled? + mobile_app_session_ip_pinning: + type: boolean + description: Is mobile app session IP pinning enabled? + x-ms-summary: Is mobile app session IP pinning enabled? + mobile_app_session_lifetime: + type: integer + description: Mobile app session lifetime (in hours) + format: int32 + x-ms-summary: Mobile app session lifetime (in hours) + folder_permissions_groups_only: + type: boolean + description: If true, permissions for this site must be bound to + a group (not a user). Otherwise, permissions must be bound to + a user. + x-ms-summary: If true, permissions for this site must be bound to + a group (not a user). Otherwise, permissions must be bound to + a user. + welcome_screen: + type: string + description: Does the welcome screen appear? + x-ms-summary: Does the welcome screen appear? + office_integration_available: + type: boolean + description: Allow users to use Office for the web? + x-ms-summary: Allow users to use Office for the web? + session_expiry: + type: number + description: Session expiry in hours + format: double + x-ms-summary: Session expiry in hours + ssl_required: + type: boolean + description: Is SSL required? Disabling this is insecure. + x-ms-summary: Is SSL required? Disabling this is insecure. + tls_disabled: + type: boolean + description: Is TLS disabled(site setting)? + x-ms-summary: Is TLS disabled(site setting)? + user_lockout: + type: boolean + description: Will users be locked out after incorrect login attempts? + x-ms-summary: Will users be locked out after incorrect login attempts? + user_lockout_tries: + type: integer + description: Number of login tries within `user_lockout_within` + hours before users are locked out + format: int32 + x-ms-summary: Number of login tries within `user_lockout_within` + hours before users are locked out + user_lockout_within: + type: integer + description: Number of hours for user lockout window + format: int32 + x-ms-summary: Number of hours for user lockout window + user_lockout_lock_period: + type: integer + description: How many hours to lock user out for failed password? + format: int32 + x-ms-summary: How many hours to lock user out for failed password? + include_password_in_welcome_email: + type: boolean + description: Include password in emails to new users? + x-ms-summary: Include password in emails to new users? + allowed_countries: + type: string + description: Comma seperated list of allowed Country codes + x-ms-summary: Comma seperated list of allowed Country codes + allowed_ips: + type: string + description: List of allowed IP addresses + x-ms-summary: List of allowed IP addresses + disallowed_countries: + type: string + description: Comma seperated list of disallowed Country codes + x-ms-summary: Comma seperated list of disallowed Country codes + days_to_retain_backups: + type: integer + description: Number of days to keep deleted files + format: int32 + x-ms-summary: Number of days to keep deleted files + max_prior_passwords: + type: integer + description: Number of prior passwords to disallow + format: int32 + x-ms-summary: Number of prior passwords to disallow + password_validity_days: + type: integer + description: Number of days password is valid + format: int32 + x-ms-summary: Number of days password is valid + password_min_length: + type: integer + description: Shortest password length for users + format: int32 + x-ms-summary: Shortest password length for users + password_require_letter: + type: boolean + description: Require a letter in passwords? + x-ms-summary: Require a letter in passwords? + password_require_mixed: + type: boolean + description: Require lower and upper case letters in passwords? + x-ms-summary: Require lower and upper case letters in passwords? + password_require_special: + type: boolean + description: Require special characters in password? + x-ms-summary: Require special characters in password? + password_require_number: + type: boolean + description: Require a number in passwords? + x-ms-summary: Require a number in passwords? + password_require_unbreached: + type: boolean + description: Require passwords that have not been previously breached? + (see https://haveibeenpwned.com/) + x-ms-summary: Require passwords that have not been previously breached? + (see https://haveibeenpwned.com/) + sftp_user_root_enabled: + type: boolean + description: Use user FTP roots also for SFTP? + x-ms-summary: Use user FTP roots also for SFTP? + disable_password_reset: + type: boolean + description: Is password reset disabled? + x-ms-summary: Is password reset disabled? + immutable_files: + type: boolean + description: Are files protected from modification? + x-ms-summary: Are files protected from modification? + session_pinned_by_ip: + type: boolean + description: Are sessions locked to the same IP? (i.e. do users + need to log in again if they change IPs?) + x-ms-summary: Are sessions locked to the same IP? (i.e. do users + need to log in again if they change IPs?) + bundle_password_required: + type: boolean + description: Do Bundles require password protection? + x-ms-summary: Do Bundles require password protection? + bundle_require_share_recipient: + type: boolean + description: Do Bundles require recipients for sharing? + x-ms-summary: Do Bundles require recipients for sharing? + password_requirements_apply_to_bundles: + type: boolean + description: Require bundles' passwords, and passwords for other + items (inboxes, public shares, etc.) to conform to the same requirements + as users' passwords? + x-ms-summary: Require bundles' passwords, and passwords for other + items (inboxes, public shares, etc.) to conform to the same requirements + as users' passwords? + opt_out_global: + type: boolean + description: Use servers in the USA only? + x-ms-summary: Use servers in the USA only? + use_provided_modified_at: + type: boolean + description: Allow uploaders to set `provided_modified_at` for uploaded + files? + x-ms-summary: Allow uploaders to set `provided_modified_at` for + uploaded files? + custom_namespace: + type: boolean + description: Is this site using a custom namespace for users? + x-ms-summary: Is this site using a custom namespace for users? + disable_users_from_inactivity_period_days: + type: integer + description: If greater than zero, users will unable to login if + they do not show activity within this number of days. + format: int32 + x-ms-summary: If greater than zero, users will unable to login if + they do not show activity within this number of days. + non_sso_groups_allowed: + type: boolean + description: If true, groups can be manually created / modified + / deleted by Site Admins. Otherwise, groups can only be managed + via your SSO provider. + x-ms-summary: If true, groups can be manually created / modified + / deleted by Site Admins. Otherwise, groups can only be managed + via your SSO provider. + non_sso_users_allowed: + type: boolean + description: If true, users can be manually created / modified / + deleted by Site Admins. Otherwise, users can only be managed via + your SSO provider. + x-ms-summary: If true, users can be manually created / modified + / deleted by Site Admins. Otherwise, users can only be managed + via your SSO provider. + sharing_enabled: + type: boolean + description: Allow bundle creation + x-ms-summary: Allow bundle creation + user_requests_enabled: + type: boolean + description: Enable User Requests feature + x-ms-summary: Enable User Requests feature + allowed_2fa_method_sms: + type: boolean + description: Is SMS two factor authentication allowed? + x-ms-summary: Is SMS two factor authentication allowed? + allowed_2fa_method_u2f: + type: boolean + description: Is U2F two factor authentication allowed? + x-ms-summary: Is U2F two factor authentication allowed? + allowed_2fa_method_totp: + type: boolean + description: Is TOTP two factor authentication allowed? + x-ms-summary: Is TOTP two factor authentication allowed? + allowed_2fa_method_yubi: + type: boolean + description: Is yubikey two factor authentication allowed? + x-ms-summary: Is yubikey two factor authentication allowed? + require_2fa: + type: boolean + description: Require two-factor authentication for all users? + x-ms-summary: Require two-factor authentication for all users? + require_2fa_user_type: + type: string + description: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + x-ms-summary: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + color2_top: + type: string + description: Top bar background color + x-ms-summary: Top bar background color + color2_left: + type: string + description: Page link and button color + x-ms-summary: Page link and button color + color2_link: + type: string + description: Top bar link color + x-ms-summary: Top bar link color + color2_text: + type: string + description: Page link and button color + x-ms-summary: Page link and button color + color2_top_text: + type: string + description: Top bar text color + x-ms-summary: Top bar text color + site_header: + type: string + description: Custom site header text + x-ms-summary: Custom site header text + site_footer: + type: string + description: Custom site footer text + x-ms-summary: Custom site footer text + login_help_text: + type: string + description: Login help text + x-ms-summary: Login help text + smtp_address: + type: string + description: SMTP server hostname or IP + x-ms-summary: SMTP server hostname or IP + smtp_authentication: + type: string + description: SMTP server authentication type + x-ms-summary: SMTP server authentication type + smtp_from: + type: string + description: From address to use when mailing through custom SMTP + x-ms-summary: From address to use when mailing through custom SMTP + smtp_username: + type: string + description: SMTP server username + x-ms-summary: SMTP server username + smtp_port: + type: integer + description: SMTP server port + format: int32 + x-ms-summary: SMTP server port + ldap_enabled: + type: boolean + description: 'Main LDAP setting: is LDAP enabled?' + x-ms-summary: 'Main LDAP setting: is LDAP enabled?' + ldap_type: + type: string + description: LDAP type + x-ms-summary: LDAP type + ldap_host: + type: string + description: LDAP host + x-ms-summary: LDAP host + ldap_host_2: + type: string + description: LDAP backup host + x-ms-summary: LDAP backup host + ldap_host_3: + type: string + description: LDAP backup host + x-ms-summary: LDAP backup host + ldap_port: + type: integer + description: LDAP port + format: int32 + x-ms-summary: LDAP port + ldap_secure: + type: boolean + description: Use secure LDAP? + x-ms-summary: Use secure LDAP? + ldap_username: + type: string + description: Username for signing in to LDAP server. + x-ms-summary: Username for signing in to LDAP server. + ldap_username_field: + type: string + description: LDAP username field + x-ms-summary: LDAP username field + ldap_domain: + type: string + description: Domain name that will be appended to usernames + x-ms-summary: Domain name that will be appended to usernames + ldap_user_action: + type: string + description: Should we sync users from LDAP server? + x-ms-summary: Should we sync users from LDAP server? + ldap_group_action: + type: string + description: Should we sync groups from LDAP server? + x-ms-summary: Should we sync groups from LDAP server? + ldap_user_include_groups: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) - if provided, only users in these groups + will be added or synced. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) - if provided, only users in these groups + will be added or synced. + ldap_group_exclusion: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) to exclude when syncing. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) to exclude when syncing. + ldap_group_inclusion: + type: string + description: Comma or newline separated list of group names (with + optional wildcards) to include when syncing. + x-ms-summary: Comma or newline separated list of group names (with + optional wildcards) to include when syncing. + ldap_base_dn: + type: string + description: Base DN for looking up users in LDAP server + x-ms-summary: Base DN for looking up users in LDAP server + icon16_file: + type: string + format: binary + x-ms-summary: null + icon16_delete: + type: boolean + description: If true, will delete the file stored in icon16 + x-ms-summary: If true, will delete the file stored in icon16 + icon32_file: + type: string + format: binary + x-ms-summary: null + icon32_delete: + type: boolean + description: If true, will delete the file stored in icon32 + x-ms-summary: If true, will delete the file stored in icon32 + icon48_file: + type: string + format: binary + x-ms-summary: null + icon48_delete: + type: boolean + description: If true, will delete the file stored in icon48 + x-ms-summary: If true, will delete the file stored in icon48 + icon128_file: + type: string + format: binary + x-ms-summary: null + icon128_delete: + type: boolean + description: If true, will delete the file stored in icon128 + x-ms-summary: If true, will delete the file stored in icon128 + logo_file: + type: string + format: binary + x-ms-summary: null + logo_delete: + type: boolean + description: If true, will delete the file stored in logo + x-ms-summary: If true, will delete the file stored in logo + disable_2fa_with_delay: + type: boolean + description: If set to true, we will begin the process of disabling + 2FA on this site. + x-ms-summary: If set to true, we will begin the process of disabling + 2FA on this site. + ldap_password_change: + type: string + description: New LDAP password. + x-ms-summary: New LDAP password. + ldap_password_change_confirmation: + type: string + description: Confirm new LDAP password. + x-ms-summary: Confirm new LDAP password. + smtp_password: + type: string + description: Password for SMTP server. + x-ms-summary: Password for SMTP server. + responses: + 200: + description: The Site object. + content: + application/json: + schema: + $ref: '#/components/schemas/SiteEntity' + x-ms-summary: The Site object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-reauthentication: + required: true + params: + - email + - require_2fa + - require_2fa_user_type + - disable_2fa_with_delay + /site/ip_addresses: + get: + tags: + - site + summary: List IP Addresses associated with the current site + description: List IP Addresses associated with the current site + operationId: GetSiteIpAddresses + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of IpAddresses objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/IpAddressEntity' + x-ms-summary: A list of IpAddresses objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-path_aliases: + - site/ip_addresses + /site/dns_records: + get: + tags: + - site + summary: Show site DNS configuration. + description: Show site DNS configuration. + operationId: GetSiteDnsRecords + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of DnsRecords objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/DnsRecordEntity' + x-ms-summary: A list of DnsRecords objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-path_aliases: + - site/dns_records + /site/test-webhook: + post: + tags: + - site + summary: Test webhook. + description: Test webhook. + operationId: PostSiteTestWebhook + requestBody: + content: + application/json: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + application/x-www-form-urlencoded: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + multipart/form-data: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + required: true + responses: + 200: + description: The Behaviors object. + content: + application/json: + schema: + description: Test webhook status. + $ref: '#/components/schemas/StatusEntity' + x-ms-summary: The Behaviors object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + x-path_aliases: + - site/test-webhook + /site/api_keys: + get: + tags: + - site + summary: List Api Keys + description: List Api Keys + operationId: GetSiteApiKeys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + responses: + 200: + description: A list of ApiKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: A list of ApiKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + post: + tags: + - site + summary: Create Api Key + description: Create Api Key + operationId: PostSiteApiKeys + requestBody: + content: + application/json: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + application/x-www-form-urlencoded: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + multipart/form-data: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + responses: + 201: + description: The ApiKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + /user: + patch: + tags: + - user + summary: Update User + description: Update User + operationId: PatchUser + requestBody: + content: + application/json: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + application/x-www-form-urlencoded: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + multipart/form-data: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + responses: + 200: + description: The Users object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserEntity' + x-ms-summary: The Users object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-reauthentication: + required: true + params: + - password + - change_password + - email + - site_admin + x-path_aliases: + - user + /user/public_keys: + get: + tags: + - user + summary: List Public Keys + description: List Public Keys + operationId: GetUserPublicKeys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of PublicKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: A list of PublicKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/public_keys + - users/:user_id/public_keys + post: + tags: + - user + summary: Create Public Key + description: Create Public Key + operationId: PostUserPublicKeys + requestBody: + content: + application/json: + schema: + required: + - public_key + - title + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + application/x-www-form-urlencoded: + schema: + required: + - public_key + - title + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + multipart/form-data: + schema: + required: + - public_key + - title + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + required: true + responses: + 201: + description: The PublicKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: The PublicKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/public_keys + - users/:user_id/public_keys + /user/groups: + get: + tags: + - user + summary: List Group Users + description: List Group Users + operationId: GetUserGroups + parameters: + - name: user_id + in: query + description: User ID. If provided, will return group_users of this user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. If provided, will return group_users of this user. + x-ms-summary: User ID. If provided, will return group_users of this user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: group_id + in: query + description: Group ID. If provided, will return group_users of this group. + schema: + type: integer + format: int32 + x-ms-summary: Group ID. If provided, will return group_users of this group. + x-ms-summary: Group ID. If provided, will return group_users of this group. + responses: + 200: + description: A list of GroupUsers objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: A list of GroupUsers objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - user/groups + - users/:user_id/groups + - groups/:group_id/users + /user/as2_keys: + get: + tags: + - user + summary: List As2 Keys + description: List As2 Keys + operationId: GetUserAs2Keys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of As2Keys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: A list of As2Keys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + - trusted_relay_without_user + x-path_aliases: + - user/as2_keys + - users/:user_id/as2_keys + post: + tags: + - user + summary: Create As2 Key + description: Create As2 Key + operationId: PostUserAs2Keys + requestBody: + content: + application/json: + schema: + required: + - as2_partnership_name + - public_key + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + application/x-www-form-urlencoded: + schema: + required: + - as2_partnership_name + - public_key + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + multipart/form-data: + schema: + required: + - as2_partnership_name + - public_key + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + required: true + responses: + 201: + description: The As2Keys object. + content: + application/json: + schema: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: The As2Keys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/as2_keys + - users/:user_id/as2_keys + /user/api_keys: + get: + tags: + - user + summary: List Api Keys + description: List Api Keys + operationId: GetUserApiKeys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + responses: + 200: + description: A list of ApiKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: A list of ApiKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + post: + tags: + - user + summary: Create Api Key + description: Create Api Key + operationId: PostUserApiKeys + requestBody: + content: + application/json: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + application/x-www-form-urlencoded: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + multipart/form-data: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + responses: + 201: + description: The ApiKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + /users/{id}/unlock: + post: + tags: + - users + summary: Unlock user who has been locked out due to failed logins. + description: Unlock user who has been locked out due to failed logins. + operationId: PostUsersIdUnlock + parameters: + - name: id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + /users/{id}/resend_welcome_email: + post: + tags: + - users + summary: Resend user welcome email + description: Resend user welcome email + operationId: PostUsersIdResendWelcomeEmail + parameters: + - name: id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + /users/{id}/2fa/reset: + post: + tags: + - users + summary: Trigger 2FA Reset process for user who has lost access to their existing + 2FA methods. + description: Trigger 2FA Reset process for user who has lost access to their + existing 2FA methods. + operationId: PostUsersId2faReset + parameters: + - name: id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-reauthentication: + required: true + always: true + /users/{id}: + get: + tags: + - users + summary: Show User + description: Show User + operationId: GetUsersId + parameters: + - name: id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + responses: + 200: + description: The Users object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserEntity' + x-ms-summary: The Users object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + - overdue_ok + delete: + tags: + - users + summary: Delete User + description: Delete User + operationId: DeleteUsersId + parameters: + - name: id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-reauthentication: + required: true + always: true + patch: + tags: + - users + summary: Update User + description: Update User + operationId: PatchUsersId + parameters: + - name: id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + requestBody: + content: + application/json: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + application/x-www-form-urlencoded: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + multipart/form-data: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + responses: + 200: + description: The Users object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserEntity' + x-ms-summary: The Users object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-reauthentication: + required: true + params: + - password + - change_password + - email + - site_admin + x-path_aliases: + - user + /users: + get: + tags: + - users + summary: List Users + description: List Users + operationId: GetUsers + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `authenticate_until`, + `email`, `last_desktop_login_at`, `last_login_at`, `username`, `company`, + `name`, `site_admin`, `receive_admin_alerts`, `password_validity_days`, + `ssl_required` or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `authenticate_until`, `email`, `last_desktop_login_at`, `last_login_at`, + `username`, `company`, `name`, `site_admin`, `receive_admin_alerts`, `password_validity_days`, + `ssl_required` or `not_site_admin`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `authenticate_until`, `email`, `last_desktop_login_at`, `last_login_at`, + `username`, `company`, `name`, `site_admin`, `receive_admin_alerts`, `password_validity_days`, + `ssl_required` or `not_site_admin`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `username`, `email`, `company`, `site_admin`, + `password_validity_days`, `ssl_required`, `last_login_at`, `authenticate_until` + or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `username`, `email`, `company`, `site_admin`, + `password_validity_days`, `ssl_required`, `last_login_at`, `authenticate_until` + or `not_site_admin`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `username`, `email`, + `company`, `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `username`, `email`, + `company`, `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `username`, `email`, + `company`, `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `username`, `email`, `company`, `site_admin`, + `password_validity_days`, `ssl_required`, `last_login_at`, `authenticate_until` + or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `username`, `email`, `company`, `site_admin`, + `password_validity_days`, `ssl_required`, `last_login_at`, `authenticate_until` + or `not_site_admin`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `username`, `email`, `company`, `site_admin`, + `password_validity_days`, `ssl_required`, `last_login_at`, `authenticate_until` + or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `username`, `email`, `company`, `site_admin`, + `password_validity_days`, `ssl_required`, `last_login_at`, `authenticate_until` + or `not_site_admin`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `username`, `email`, + `company`, `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `username`, `email`, `company`, + `site_admin`, `password_validity_days`, `ssl_required`, `last_login_at`, + `authenticate_until` or `not_site_admin`. + - name: ids + in: query + description: comma-separated list of User IDs + schema: + type: string + x-ms-summary: comma-separated list of User IDs + x-ms-summary: comma-separated list of User IDs + - name: q[username] + in: query + description: List users matching username. + schema: + type: string + x-ms-summary: List users matching username. + x-ms-summary: List users matching username. + - name: q[email] + in: query + description: List users matching email. + schema: + type: string + x-ms-summary: List users matching email. + x-ms-summary: List users matching email. + - name: q[notes] + in: query + description: List users matching notes field. + schema: + type: string + x-ms-summary: List users matching notes field. + x-ms-summary: List users matching notes field. + - name: q[admin] + in: query + description: If `true`, list only admin users. + schema: + type: string + x-ms-summary: If `true`, list only admin users. + x-ms-summary: If `true`, list only admin users. + - name: q[allowed_ips] + in: query + description: If set, list only users with overridden allowed IP setting. + schema: + type: string + x-ms-summary: If set, list only users with overridden allowed IP setting. + x-ms-summary: If set, list only users with overridden allowed IP setting. + - name: q[password_validity_days] + in: query + description: If set, list only users with overridden password validity days + setting. + schema: + type: string + x-ms-summary: If set, list only users with overridden password validity + days setting. + x-ms-summary: If set, list only users with overridden password validity days + setting. + - name: q[ssl_required] + in: query + description: If set, list only users with overridden SSL required setting. + schema: + type: string + x-ms-summary: If set, list only users with overridden SSL required setting. + x-ms-summary: If set, list only users with overridden SSL required setting. + - name: search + in: query + description: Searches for partial matches of name, username, or email. + schema: + type: string + x-ms-summary: Searches for partial matches of name, username, or email. + x-ms-summary: Searches for partial matches of name, username, or email. + responses: + 200: + description: A list of Users objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UserEntity' + x-ms-summary: A list of Users objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + - overdue_ok + post: + tags: + - users + summary: Create User + description: Create User + operationId: PostUsers + requestBody: + content: + application/json: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + application/x-www-form-urlencoded: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + multipart/form-data: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_id: + type: integer + description: Group ID to associate this user with. + format: int32 + x-ms-summary: Group ID to associate this user with. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + responses: + 201: + description: The Users object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserEntity' + x-ms-summary: The Users object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - groups/:group_id/users + /users/{user_id}/cipher_uses: + get: + tags: + - users + summary: List User Cipher Uses + description: List User Cipher Uses + operationId: GetUsersUserIdCipherUses + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of UserCipherUses objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UserCipherUseEntity' + x-ms-summary: A list of UserCipherUses objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - users/:user_id/cipher_uses + /users/{user_id}/public_keys: + get: + tags: + - users + summary: List Public Keys + description: List Public Keys + operationId: GetUsersUserIdPublicKeys + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of PublicKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: A list of PublicKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/public_keys + - users/:user_id/public_keys + post: + tags: + - users + summary: Create Public Key + description: Create Public Key + operationId: PostUsersUserIdPublicKeys + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + requestBody: + content: + application/json: + schema: + required: + - public_key + - title + properties: + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + application/x-www-form-urlencoded: + schema: + required: + - public_key + - title + properties: + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + multipart/form-data: + schema: + required: + - public_key + - title + properties: + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + required: true + responses: + 201: + description: The PublicKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: The PublicKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/public_keys + - users/:user_id/public_keys + /users/{user_id}/permissions: + get: + tags: + - users + summary: List Permissions + description: List Permissions + operationId: GetUsersUserIdPermissions + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `group_id`, + `path`, `user_id` or `permission`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `group_id`, `path`, `user_id` or `permission`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `group_id`, `path`, `user_id` or `permission`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `group_id`, `user_id` or + `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `group_id`, `user_id` or + `path`. + # - name: path + # in: query + # description: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + # schema: + # type: string + # x-ms-summary: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + # x-ms-summary: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + - name: group_id + in: query + description: 'DEPRECATED: Group ID. If provided, will scope permissions to + this group. Use `filter[group_id]` instead.' + schema: + type: string + x-ms-summary: 'DEPRECATED: Group ID. If provided, will scope permissions + to this group. Use `filter[group_id]` instead.`' + x-ms-summary: 'DEPRECATED: Group ID. If provided, will scope permissions + to this group. Use `filter[group_id]` instead.`' + - name: user_id + in: path + description: 'DEPRECATED: User ID. If provided, will scope permissions to + this user. Use `filter[user_id]` instead.' + required: true + schema: + type: string + x-ms-summary: 'DEPRECATED: User ID. If provided, will scope permissions + to this user. Use `filter[user_id]` instead.`' + x-ms-summary: 'DEPRECATED: User ID. If provided, will scope permissions to + this user. Use `filter[user_id]` instead.`' + - name: include_groups + in: query + description: If searching by user or group, also include user's permissions + that are inherited from its groups? + schema: + type: boolean + x-ms-summary: If searching by user or group, also include user's permissions + that are inherited from its groups? + x-ms-summary: If searching by user or group, also include user's permissions + that are inherited from its groups? + responses: + 200: + description: A list of Permissions objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PermissionEntity' + x-ms-summary: A list of Permissions objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - groups/:group_id/permissions + - users/:user_id/permissions + /users/{user_id}/groups: + get: + tags: + - users + summary: List Group Users + description: List Group Users + operationId: GetUsersUserIdGroups + parameters: + - name: user_id + in: path + description: User ID. If provided, will return group_users of this user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. If provided, will return group_users of this user. + x-ms-summary: User ID. If provided, will return group_users of this user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: group_id + in: query + description: Group ID. If provided, will return group_users of this group. + schema: + type: integer + format: int32 + x-ms-summary: Group ID. If provided, will return group_users of this group. + x-ms-summary: Group ID. If provided, will return group_users of this group. + responses: + 200: + description: A list of GroupUsers objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: A list of GroupUsers objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - user/groups + - users/:user_id/groups + - groups/:group_id/users + /users/{user_id}/as2_keys: + get: + tags: + - users + summary: List As2 Keys + description: List As2 Keys + operationId: GetUsersUserIdAs2Keys + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of As2Keys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: A list of As2Keys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + - trusted_relay_without_user + x-path_aliases: + - user/as2_keys + - users/:user_id/as2_keys + post: + tags: + - users + summary: Create As2 Key + description: Create As2 Key + operationId: PostUsersUserIdAs2Keys + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + requestBody: + content: + application/json: + schema: + required: + - as2_partnership_name + - public_key + properties: + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + application/x-www-form-urlencoded: + schema: + required: + - as2_partnership_name + - public_key + properties: + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + multipart/form-data: + schema: + required: + - as2_partnership_name + - public_key + properties: + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + required: true + responses: + 201: + description: The As2Keys object. + content: + application/json: + schema: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: The As2Keys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/as2_keys + - users/:user_id/as2_keys + /users/{user_id}/api_keys: + get: + tags: + - users + summary: List Api Keys + description: List Api Keys + operationId: GetUsersUserIdApiKeys + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `expires_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `expires_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `expires_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `expires_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `expires_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `expires_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `expires_at`. + responses: + 200: + description: A list of ApiKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: A list of ApiKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + post: + tags: + - users + summary: Create Api Key + description: Create Api Key + operationId: PostUsersUserIdApiKeys + parameters: + - name: user_id + in: path + description: User ID. Provide a value of `0` to operate the current session's + user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + multipart/form-data: + schema: + properties: + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + x-ms-summary: Internal name for the API Key. For your use. + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: API Key expiration date + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + example: full + default: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + x-ms-summary: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided + in our Desktop App (File and Share Link operations). Additional + permission sets may become available in the future, such as for + a Site Admin to give a key with no administrator privileges. If + you have ideas for permission sets, please let us know. + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + x-ms-summary: Folder path restriction for this api key. + responses: + 201: + description: The ApiKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyEntity' + x-ms-summary: The ApiKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - site/api_keys + - user/api_keys + - users/:user_id/api_keys + /apps: + get: + tags: + - apps + summary: List Apps + description: List Apps + operationId: GetApps + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `name` + and `app_type`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `name` and `app_type`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `name` and `app_type`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name` and `app_type`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `name` and `app_type`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name` and `app_type`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `name` and `app_type`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `name` and `app_type`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `name` and `app_type`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `name` and `app_type`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `name` and `app_type`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `name` and `app_type`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name` and `app_type`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `name` and `app_type`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name` and `app_type`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `name` and `app_type`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `name` and `app_type`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `name` and `app_type`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `name` and `app_type`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `name` and `app_type`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `name` and `app_type`. + responses: + 200: + description: A list of Apps objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AppEntity' + x-ms-summary: A list of Apps objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - none + /as2_keys/{id}: + get: + tags: + - as2_keys + summary: Show As2 Key + description: Show As2 Key + operationId: GetAs2KeysId + parameters: + - name: id + in: path + description: As2 Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: As2 Key ID. + x-ms-summary: As2 Key ID. + responses: + 200: + description: The As2Keys object. + content: + application/json: + schema: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: The As2Keys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + delete: + tags: + - as2_keys + summary: Delete As2 Key + description: Delete As2 Key + operationId: DeleteAs2KeysId + parameters: + - name: id + in: path + description: As2 Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: As2 Key ID. + x-ms-summary: As2 Key ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + patch: + tags: + - as2_keys + summary: Update As2 Key + description: Update As2 Key + operationId: PatchAs2KeysId + parameters: + - name: id + in: path + description: As2 Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: As2 Key ID. + x-ms-summary: As2 Key ID. + requestBody: + content: + application/json: + schema: + required: + - as2_partnership_name + properties: + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + application/x-www-form-urlencoded: + schema: + required: + - as2_partnership_name + properties: + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + multipart/form-data: + schema: + required: + - as2_partnership_name + properties: + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + required: true + responses: + 200: + description: The As2Keys object. + content: + application/json: + schema: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: The As2Keys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + /as2_keys: + get: + tags: + - as2_keys + summary: List As2 Keys + description: List As2 Keys + operationId: GetAs2Keys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of As2Keys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: A list of As2Keys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + - trusted_relay_without_user + x-path_aliases: + - user/as2_keys + - users/:user_id/as2_keys + post: + tags: + - as2_keys + summary: Create As2 Key + description: Create As2 Key + operationId: PostAs2Keys + requestBody: + content: + application/json: + schema: + required: + - as2_partnership_name + - public_key + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + application/x-www-form-urlencoded: + schema: + required: + - as2_partnership_name + - public_key + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + multipart/form-data: + schema: + required: + - as2_partnership_name + - public_key + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + x-ms-summary: AS2 Partnership Name + public_key: + type: string + description: Actual contents of Public key. + x-ms-summary: Actual contents of Public key. + required: true + responses: + 201: + description: The As2Keys object. + content: + application/json: + schema: + $ref: '#/components/schemas/As2KeyEntity' + x-ms-summary: The As2Keys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/as2_keys + - users/:user_id/as2_keys + /automations/{id}: + get: + tags: + - automations + summary: Show Automation + description: Show Automation + operationId: GetAutomationsId + parameters: + - name: id + in: path + description: Automation ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Automation ID. + x-ms-summary: Automation ID. + responses: + 200: + description: The Automations object. + content: + application/json: + schema: + $ref: '#/components/schemas/AutomationEntity' + x-ms-summary: The Automations object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + delete: + tags: + - automations + summary: Delete Automation + description: Delete Automation + operationId: DeleteAutomationsId + parameters: + - name: id + in: path + description: Automation ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Automation ID. + x-ms-summary: Automation ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + patch: + tags: + - automations + summary: Update Automation + description: Update Automation + operationId: PatchAutomationsId + parameters: + - name: id + in: path + description: Automation ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Automation ID. + x-ms-summary: Automation ID. + requestBody: + content: + application/json: + schema: + required: + - automation + properties: + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + x-ms-summary: Automation type + source: + type: string + description: Source Path + example: source + x-ms-summary: Source Path + destination: + type: string + description: 'DEPRECATED: Destination Path. Use `destinations` instead.' + x-ms-summary: 'DEPRECATED: Destination Path. Use `destinations` + instead.' + destinations: + type: array + description: A list of String destination paths or Hash of folder_path + and optional file_path. + example: '["folder_a/file_a.txt", {"folder_path":"folder_b", "file_path":"file_b.txt"}, + {"folder_path":"folder_c"}]' + items: + type: string + x-ms-summary: A list of String destination paths or Hash of folder_path + and optional file_path. + destination_replace_from: + type: string + description: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + x-ms-summary: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + x-ms-summary: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + interval: + type: string + description: 'How often to run this automation? One of: `day`, `week`, + `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, `year`, + `year_end`' + example: year + x-ms-summary: 'How often to run this automation? One of: `day`, + `week`, `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, + `year`, `year_end`' + path: + type: string + description: Path on which this Automation runs. Supports globs. + x-ms-summary: Path on which this Automation runs. Supports globs. + user_ids: + type: string + description: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + schedule: + type: object + description: Custom schedule for running this automation. + example: '{"days_of_week": [ 0, 1, 3 ], "times_of_day": [ "7:30", + "11:30" ], "time_zone": "Eastern Time (US & Canada)"}' + x-ms-summary: Custom schedule for running this automation. + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + x-ms-summary: 'How this automation is triggered to run. One of: + `realtime`, `daily`, `custom_schedule`, `webhook`, `email`, or + `action`.' + trigger_actions: + type: array + description: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + example: '[ "create" ]' + items: + type: string + x-ms-summary: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for + the specified trigger actions. + example: path/to/file/or/folder + x-ms-summary: If trigger is `action`, this is the path to watch + for the specified trigger actions. + value: + type: object + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + x-ms-summary: A Hash of attributes specific to the automation type. + application/x-www-form-urlencoded: + schema: + required: + - automation + properties: + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + x-ms-summary: Automation type + source: + type: string + description: Source Path + example: source + x-ms-summary: Source Path + destination: + type: string + description: 'DEPRECATED: Destination Path. Use `destinations` instead.' + x-ms-summary: 'DEPRECATED: Destination Path. Use `destinations` + instead.' + destinations: + type: array + description: A list of String destination paths or Hash of folder_path + and optional file_path. + example: '["folder_a/file_a.txt", {"folder_path":"folder_b", "file_path":"file_b.txt"}, + {"folder_path":"folder_c"}]' + items: + type: string + x-ms-summary: A list of String destination paths or Hash of folder_path + and optional file_path. + destination_replace_from: + type: string + description: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + x-ms-summary: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + x-ms-summary: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + interval: + type: string + description: 'How often to run this automation? One of: `day`, `week`, + `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, `year`, + `year_end`' + example: year + x-ms-summary: 'How often to run this automation? One of: `day`, + `week`, `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, + `year`, `year_end`' + path: + type: string + description: Path on which this Automation runs. Supports globs. + x-ms-summary: Path on which this Automation runs. Supports globs. + user_ids: + type: string + description: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + schedule: + type: object + description: Custom schedule for running this automation. + example: '{"days_of_week": [ 0, 1, 3 ], "times_of_day": [ "7:30", + "11:30" ], "time_zone": "Eastern Time (US & Canada)"}' + x-ms-summary: Custom schedule for running this automation. + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + x-ms-summary: 'How this automation is triggered to run. One of: + `realtime`, `daily`, `custom_schedule`, `webhook`, `email`, or + `action`.' + trigger_actions: + type: array + description: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + example: '[ "create" ]' + items: + type: string + x-ms-summary: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for + the specified trigger actions. + example: path/to/file/or/folder + x-ms-summary: If trigger is `action`, this is the path to watch + for the specified trigger actions. + value: + type: object + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + x-ms-summary: A Hash of attributes specific to the automation type. + multipart/form-data: + schema: + required: + - automation + properties: + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + x-ms-summary: Automation type + source: + type: string + description: Source Path + example: source + x-ms-summary: Source Path + destination: + type: string + description: 'DEPRECATED: Destination Path. Use `destinations` instead.' + x-ms-summary: 'DEPRECATED: Destination Path. Use `destinations` + instead.' + destinations: + type: array + description: A list of String destination paths or Hash of folder_path + and optional file_path. + example: '["folder_a/file_a.txt", {"folder_path":"folder_b", "file_path":"file_b.txt"}, + {"folder_path":"folder_c"}]' + items: + type: string + x-ms-summary: A list of String destination paths or Hash of folder_path + and optional file_path. + destination_replace_from: + type: string + description: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + x-ms-summary: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + x-ms-summary: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + interval: + type: string + description: 'How often to run this automation? One of: `day`, `week`, + `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, `year`, + `year_end`' + example: year + x-ms-summary: 'How often to run this automation? One of: `day`, + `week`, `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, + `year`, `year_end`' + path: + type: string + description: Path on which this Automation runs. Supports globs. + x-ms-summary: Path on which this Automation runs. Supports globs. + user_ids: + type: string + description: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + schedule: + type: object + description: Custom schedule for running this automation. + example: '{"days_of_week": [ 0, 1, 3 ], "times_of_day": [ "7:30", + "11:30" ], "time_zone": "Eastern Time (US & Canada)"}' + x-ms-summary: Custom schedule for running this automation. + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + x-ms-summary: 'How this automation is triggered to run. One of: + `realtime`, `daily`, `custom_schedule`, `webhook`, `email`, or + `action`.' + trigger_actions: + type: array + description: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + example: '[ "create" ]' + items: + type: string + x-ms-summary: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for + the specified trigger actions. + example: path/to/file/or/folder + x-ms-summary: If trigger is `action`, this is the path to watch + for the specified trigger actions. + value: + type: object + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + x-ms-summary: A Hash of attributes specific to the automation type. + required: true + responses: + 200: + description: The Automations object. + content: + application/json: + schema: + $ref: '#/components/schemas/AutomationEntity' + x-ms-summary: The Automations object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + /automations: + get: + tags: + - automations + summary: List Automations + description: List Automations + operationId: GetAutomations + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `automation`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `automation`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `automation`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `automation`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `automation`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `automation`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `automation`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `automation`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `automation`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `automation`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `automation`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `automation`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `automation`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `automation`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `automation`. + - name: automation + in: query + description: 'DEPRECATED: Type of automation to filter by. Use `filter[automation]` + instead.' + schema: + type: string + x-ms-summary: 'DEPRECATED: Type of automation to filter by. Use `filter[automation]` + instead.' + x-ms-summary: 'DEPRECATED: Type of automation to filter by. Use `filter[automation]` + instead.' + responses: + 200: + description: A list of Automations objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AutomationEntity' + x-ms-summary: A list of Automations objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + post: + tags: + - automations + summary: Create Automation + description: Create Automation + operationId: PostAutomations + requestBody: + content: + application/json: + schema: + required: + - automation + properties: + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + x-ms-summary: Automation type + source: + type: string + description: Source Path + example: source + x-ms-summary: Source Path + destination: + type: string + description: 'DEPRECATED: Destination Path. Use `destinations` instead.' + x-ms-summary: 'DEPRECATED: Destination Path. Use `destinations` + instead.' + destinations: + type: array + description: A list of String destination paths or Hash of folder_path + and optional file_path. + example: '["folder_a/file_a.txt", {"folder_path":"folder_b", "file_path":"file_b.txt"}, + {"folder_path":"folder_c"}]' + items: + type: string + x-ms-summary: A list of String destination paths or Hash of folder_path + and optional file_path. + destination_replace_from: + type: string + description: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + x-ms-summary: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + x-ms-summary: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + interval: + type: string + description: 'How often to run this automation? One of: `day`, `week`, + `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, `year`, + `year_end`' + example: year + x-ms-summary: 'How often to run this automation? One of: `day`, + `week`, `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, + `year`, `year_end`' + path: + type: string + description: Path on which this Automation runs. Supports globs. + x-ms-summary: Path on which this Automation runs. Supports globs. + user_ids: + type: string + description: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + schedule: + type: object + description: Custom schedule for running this automation. + example: '{"days_of_week": [ 0, 1, 3 ], "times_of_day": [ "7:30", + "11:30" ], "time_zone": "Eastern Time (US & Canada)"}' + x-ms-summary: Custom schedule for running this automation. + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + x-ms-summary: 'How this automation is triggered to run. One of: + `realtime`, `daily`, `custom_schedule`, `webhook`, `email`, or + `action`.' + trigger_actions: + type: array + description: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + example: '[ "create" ]' + items: + type: string + x-ms-summary: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for + the specified trigger actions. + example: path/to/file/or/folder + x-ms-summary: If trigger is `action`, this is the path to watch + for the specified trigger actions. + value: + type: object + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + x-ms-summary: A Hash of attributes specific to the automation type. + application/x-www-form-urlencoded: + schema: + required: + - automation + properties: + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + x-ms-summary: Automation type + source: + type: string + description: Source Path + example: source + x-ms-summary: Source Path + destination: + type: string + description: 'DEPRECATED: Destination Path. Use `destinations` instead.' + x-ms-summary: 'DEPRECATED: Destination Path. Use `destinations` + instead.' + destinations: + type: array + description: A list of String destination paths or Hash of folder_path + and optional file_path. + example: '["folder_a/file_a.txt", {"folder_path":"folder_b", "file_path":"file_b.txt"}, + {"folder_path":"folder_c"}]' + items: + type: string + x-ms-summary: A list of String destination paths or Hash of folder_path + and optional file_path. + destination_replace_from: + type: string + description: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + x-ms-summary: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + x-ms-summary: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + interval: + type: string + description: 'How often to run this automation? One of: `day`, `week`, + `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, `year`, + `year_end`' + example: year + x-ms-summary: 'How often to run this automation? One of: `day`, + `week`, `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, + `year`, `year_end`' + path: + type: string + description: Path on which this Automation runs. Supports globs. + x-ms-summary: Path on which this Automation runs. Supports globs. + user_ids: + type: string + description: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + schedule: + type: object + description: Custom schedule for running this automation. + example: '{"days_of_week": [ 0, 1, 3 ], "times_of_day": [ "7:30", + "11:30" ], "time_zone": "Eastern Time (US & Canada)"}' + x-ms-summary: Custom schedule for running this automation. + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + x-ms-summary: 'How this automation is triggered to run. One of: + `realtime`, `daily`, `custom_schedule`, `webhook`, `email`, or + `action`.' + trigger_actions: + type: array + description: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + example: '[ "create" ]' + items: + type: string + x-ms-summary: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for + the specified trigger actions. + example: path/to/file/or/folder + x-ms-summary: If trigger is `action`, this is the path to watch + for the specified trigger actions. + value: + type: object + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + x-ms-summary: A Hash of attributes specific to the automation type. + multipart/form-data: + schema: + required: + - automation + properties: + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + x-ms-summary: Automation type + source: + type: string + description: Source Path + example: source + x-ms-summary: Source Path + destination: + type: string + description: 'DEPRECATED: Destination Path. Use `destinations` instead.' + x-ms-summary: 'DEPRECATED: Destination Path. Use `destinations` + instead.' + destinations: + type: array + description: A list of String destination paths or Hash of folder_path + and optional file_path. + example: '["folder_a/file_a.txt", {"folder_path":"folder_b", "file_path":"file_b.txt"}, + {"folder_path":"folder_c"}]' + items: + type: string + x-ms-summary: A list of String destination paths or Hash of folder_path + and optional file_path. + destination_replace_from: + type: string + description: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + x-ms-summary: If set, this string in the destination path will be + replaced with the value in `destination_replace_to`. + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + x-ms-summary: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + interval: + type: string + description: 'How often to run this automation? One of: `day`, `week`, + `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, `year`, + `year_end`' + example: year + x-ms-summary: 'How often to run this automation? One of: `day`, + `week`, `week_end`, `month`, `month_end`, `quarter`, `quarter_end`, + `year`, `year_end`' + path: + type: string + description: Path on which this Automation runs. Supports globs. + x-ms-summary: Path on which this Automation runs. Supports globs. + user_ids: + type: string + description: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs the automation is associated with. + If sent as a string, it should be comma-delimited. + schedule: + type: object + description: Custom schedule for running this automation. + example: '{"days_of_week": [ 0, 1, 3 ], "times_of_day": [ "7:30", + "11:30" ], "time_zone": "Eastern Time (US & Canada)"}' + x-ms-summary: Custom schedule for running this automation. + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + x-ms-summary: 'How this automation is triggered to run. One of: + `realtime`, `daily`, `custom_schedule`, `webhook`, `email`, or + `action`.' + trigger_actions: + type: array + description: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + example: '[ "create" ]' + items: + type: string + x-ms-summary: If trigger is `action`, this is the list of action + types on which to trigger the automation. Valid actions are create, + read, update, destroy, move, copy + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for + the specified trigger actions. + example: path/to/file/or/folder + x-ms-summary: If trigger is `action`, this is the path to watch + for the specified trigger actions. + value: + type: object + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + x-ms-summary: A Hash of attributes specific to the automation type. + required: true + responses: + 201: + description: The Automations object. + content: + application/json: + schema: + $ref: '#/components/schemas/AutomationEntity' + x-ms-summary: The Automations object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + /bandwidth_snapshots: + get: + tags: + - bandwidth_snapshots + summary: List Bandwidth Snapshots + description: List Bandwidth Snapshots + operationId: GetBandwidthSnapshots + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `logged_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `logged_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `logged_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `logged_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `logged_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `logged_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `logged_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `logged_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `logged_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `logged_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `logged_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `logged_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `logged_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `logged_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `logged_at`. + responses: + 200: + description: A list of BandwidthSnapshots objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BandwidthSnapshotEntity' + x-ms-summary: A list of BandwidthSnapshots objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /behaviors/webhook/test: + post: + tags: + - behaviors + summary: Test webhook. + description: Test webhook. + operationId: PostBehaviorsWebhookTest + requestBody: + content: + application/json: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + application/x-www-form-urlencoded: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + multipart/form-data: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + required: true + responses: + 200: + description: The Behaviors object. + content: + application/json: + schema: + description: Test webhook fields. + $ref: '#/components/schemas/StatusEntity' + x-ms-summary: The Behaviors object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + x-path_aliases: + - site/test-webhook + /behaviors/{id}: + get: + tags: + - behaviors + summary: Show Behavior + description: Show Behavior + operationId: GetBehaviorsId + parameters: + - name: id + in: path + description: Behavior ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Behavior ID. + x-ms-summary: Behavior ID. + responses: + 200: + description: The Behaviors object. + content: + application/json: + schema: + $ref: '#/components/schemas/BehaviorEntity' + x-ms-summary: The Behaviors object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - behaviors + summary: Delete Behavior + description: Delete Behavior + operationId: DeleteBehaviorsId + parameters: + - name: id + in: path + description: Behavior ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Behavior ID. + x-ms-summary: Behavior ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - behaviors + summary: Update Behavior + description: Update Behavior + operationId: PatchBehaviorsId + parameters: + - name: id + in: path + description: Behavior ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Behavior ID. + x-types: + - type: string + - type: integer + format: int32 + - type: object + x-ms-summary: Behavior ID. + x-types: + - type: string + - type: integer + format: int32 + - type: object + requestBody: + content: + application/json: + schema: + properties: + value: + type: string + description: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + example: '{"method": "GET"}' + x-ms-summary: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + attachment_file: + type: string + description: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + format: binary + x-ms-summary: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + behavior: + type: string + description: Behavior type. + example: webhook + x-ms-summary: Behavior type. + path: + type: string + description: Folder behaviors path. + x-ms-summary: Folder behaviors path. + x-types: + - type: string + - type: integer + format: int32 + - type: object + application/x-www-form-urlencoded: + schema: + properties: + value: + type: string + description: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + example: '{"method": "GET"}' + x-ms-summary: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + attachment_file: + type: string + description: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + format: binary + x-ms-summary: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + behavior: + type: string + description: Behavior type. + example: webhook + x-ms-summary: Behavior type. + path: + type: string + description: Folder behaviors path. + x-ms-summary: Folder behaviors path. + x-types: + - type: string + - type: integer + format: int32 + - type: object + multipart/form-data: + schema: + properties: + value: + type: string + description: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + example: '{"method": "GET"}' + x-ms-summary: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + attachment_file: + type: string + description: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + format: binary + x-ms-summary: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + behavior: + type: string + description: Behavior type. + example: webhook + x-ms-summary: Behavior type. + path: + type: string + description: Folder behaviors path. + x-ms-summary: Folder behaviors path. + x-types: + - type: string + - type: integer + format: int32 + - type: object + responses: + 200: + description: The Behaviors object. + content: + application/json: + schema: + $ref: '#/components/schemas/BehaviorEntity' + x-ms-summary: The Behaviors object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /behaviors: + get: + tags: + - behaviors + summary: List Behaviors + description: List Behaviors + operationId: GetBehaviors + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `behavior`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `behavior`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `behavior`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `behavior`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `behavior`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `behavior`. + - name: behavior + in: query + description: If set, only shows folder behaviors matching this behavior type. + schema: + type: string + x-ms-summary: If set, only shows folder behaviors matching this behavior + type. + x-ms-summary: If set, only shows folder behaviors matching this behavior type. + responses: + 200: + description: A list of Behaviors objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BehaviorEntity' + x-ms-summary: A list of Behaviors objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - behaviors + summary: Create Behavior + description: Create Behavior + operationId: PostBehaviors + requestBody: + content: + application/json: + schema: + required: + - behavior + - path + properties: + value: + type: string + description: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + example: '{"method": "GET"}' + x-ms-summary: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + attachment_file: + type: string + description: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + format: binary + x-ms-summary: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + path: + type: string + description: Folder behaviors path. + x-ms-summary: Folder behaviors path. + behavior: + type: string + description: Behavior type. + example: webhook + x-ms-summary: Behavior type. + application/x-www-form-urlencoded: + schema: + required: + - behavior + - path + properties: + value: + type: string + description: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + example: '{"method": "GET"}' + x-ms-summary: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + attachment_file: + type: string + description: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + format: binary + x-ms-summary: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + path: + type: string + description: Folder behaviors path. + x-ms-summary: Folder behaviors path. + behavior: + type: string + description: Behavior type. + example: webhook + x-ms-summary: Behavior type. + multipart/form-data: + schema: + required: + - behavior + - path + properties: + value: + type: string + description: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + example: '{"method": "GET"}' + x-ms-summary: The value of the folder behavior. Can be a integer, + array, or hash depending on the type of folder behavior. See The + Behavior Types section for example values for each type of behavior. + attachment_file: + type: string + description: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + format: binary + x-ms-summary: Certain behaviors may require a file, for instance, + the "watermark" behavior requires a watermark image + path: + type: string + description: Folder behaviors path. + x-ms-summary: Folder behaviors path. + behavior: + type: string + description: Behavior type. + example: webhook + x-ms-summary: Behavior type. + required: true + responses: + 201: + description: The Behaviors object. + content: + application/json: + schema: + $ref: '#/components/schemas/BehaviorEntity' + x-ms-summary: The Behaviors object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /behaviors/folders/{operationPath}: + get: + tags: + - behaviors + summary: List Behaviors by path + description: List Behaviors by path + operationId: BehaviorListForPath + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `behavior`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `behavior`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `behavior`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `behavior`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `behavior`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `behavior`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `behavior`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `behavior`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `behavior`. + - name: operationPath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + - name: recursive + in: query + description: Show behaviors above this path? + schema: + type: string + x-ms-summary: Show behaviors above this path? + x-ms-summary: Show behaviors above this path? + - name: behavior + in: query + description: 'DEPRECATED: If set only shows folder behaviors matching this + behavior type. Use `filter[behavior]` instead.' + schema: + type: string + x-ms-summary: 'DEPRECATED: If set only shows folder behaviors matching this + behavior type. Use `filter[behavior]` instead.' + x-ms-summary: 'DEPRECATED: If set only shows folder behaviors matching this + behavior type. Use `filter[behavior]` instead.' + responses: + 200: + description: A list of Behaviors objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BehaviorEntity' + x-ms-summary: A list of Behaviors objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /bundles/{id}: + get: + tags: + - bundles + summary: Show Bundle + description: Show Bundle + operationId: GetBundlesId + parameters: + - name: id + in: path + description: Bundle ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Bundle ID. + x-ms-summary: Bundle ID. + responses: + 200: + description: The Bundles object. + content: + application/json: + schema: + $ref: '#/components/schemas/BundleEntity' + x-ms-summary: The Bundles object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - bundles + summary: Delete Bundle + description: Delete Bundle + operationId: DeleteBundlesId + parameters: + - name: id + in: path + description: Bundle ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Bundle ID. + x-ms-summary: Bundle ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - bundles + summary: Update Bundle + description: Update Bundle + operationId: PatchBundlesId + parameters: + - name: id + in: path + description: Bundle ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Bundle ID. + x-ms-summary: Bundle ID. + requestBody: + content: + application/json: + schema: + properties: + paths: + type: array + description: A list of paths to include in this bundle. + example: + - file.txt + items: + type: string + x-ms-summary: A list of paths to include in this bundle. + password: + type: string + description: Password for this bundle. + example: Password + x-ms-summary: Password for this bundle. + form_field_set_id: + type: integer + description: Id of Form Field Set to use with this bundle + format: int32 + x-ms-summary: Id of Form Field Set to use with this bundle + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + x-ms-summary: ID of the clickwrap to use with this bundle. + code: + type: string + description: Bundle code. This code forms the end part of the Public + URL. + example: abc123 + x-ms-summary: Bundle code. This code forms the end part of the + Public URL. + description: + type: string + description: Public description + example: The public description of the bundle. + x-ms-summary: Public description + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Bundle expiration date/time + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + x-ms-summary: ID of the associated inbox, if available. + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + x-ms-summary: Maximum number of times bundle can be accessed + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + x-ms-summary: Bundle internal note + preview_only: + type: boolean + description: Restrict users to previewing files only? + x-ms-summary: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's + name and email address? + x-ms-summary: Show a registration page that captures the downloader's + name and email address? + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + x-ms-summary: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + application/x-www-form-urlencoded: + schema: + properties: + paths: + type: array + description: A list of paths to include in this bundle. + example: + - file.txt + items: + type: string + x-ms-summary: A list of paths to include in this bundle. + password: + type: string + description: Password for this bundle. + example: Password + x-ms-summary: Password for this bundle. + form_field_set_id: + type: integer + description: Id of Form Field Set to use with this bundle + format: int32 + x-ms-summary: Id of Form Field Set to use with this bundle + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + x-ms-summary: ID of the clickwrap to use with this bundle. + code: + type: string + description: Bundle code. This code forms the end part of the Public + URL. + example: abc123 + x-ms-summary: Bundle code. This code forms the end part of the + Public URL. + description: + type: string + description: Public description + example: The public description of the bundle. + x-ms-summary: Public description + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Bundle expiration date/time + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + x-ms-summary: ID of the associated inbox, if available. + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + x-ms-summary: Maximum number of times bundle can be accessed + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + x-ms-summary: Bundle internal note + preview_only: + type: boolean + description: Restrict users to previewing files only? + x-ms-summary: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's + name and email address? + x-ms-summary: Show a registration page that captures the downloader's + name and email address? + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + x-ms-summary: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + multipart/form-data: + schema: + properties: + paths: + type: array + description: A list of paths to include in this bundle. + example: + - file.txt + items: + type: string + x-ms-summary: A list of paths to include in this bundle. + password: + type: string + description: Password for this bundle. + example: Password + x-ms-summary: Password for this bundle. + form_field_set_id: + type: integer + description: Id of Form Field Set to use with this bundle + format: int32 + x-ms-summary: Id of Form Field Set to use with this bundle + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + x-ms-summary: ID of the clickwrap to use with this bundle. + code: + type: string + description: Bundle code. This code forms the end part of the Public + URL. + example: abc123 + x-ms-summary: Bundle code. This code forms the end part of the + Public URL. + description: + type: string + description: Public description + example: The public description of the bundle. + x-ms-summary: Public description + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Bundle expiration date/time + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + x-ms-summary: ID of the associated inbox, if available. + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + x-ms-summary: Maximum number of times bundle can be accessed + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + x-ms-summary: Bundle internal note + preview_only: + type: boolean + description: Restrict users to previewing files only? + x-ms-summary: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's + name and email address? + x-ms-summary: Show a registration page that captures the downloader's + name and email address? + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + x-ms-summary: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + responses: + 200: + description: The Bundles object. + content: + application/json: + schema: + $ref: '#/components/schemas/BundleEntity' + x-ms-summary: The Bundles object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /bundles: + get: + tags: + - bundles + summary: List Bundles + description: List Bundles + operationId: GetBundles + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `created_at` + and `code`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `created_at` and `code`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `created_at` and `code`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`. + responses: + 200: + description: A list of Bundles objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BundleEntity' + x-ms-summary: A list of Bundles objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - bundles + summary: Create Bundle + description: Create Bundle + operationId: PostBundles + requestBody: + content: + application/json: + schema: + required: + - paths + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + paths: + type: array + description: A list of paths to include in this bundle. + example: + - file.txt + items: + type: string + x-ms-summary: A list of paths to include in this bundle. + password: + type: string + description: Password for this bundle. + example: Password + x-ms-summary: Password for this bundle. + form_field_set_id: + type: integer + description: Id of Form Field Set to use with this bundle + format: int32 + x-ms-summary: Id of Form Field Set to use with this bundle + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Bundle expiration date/time + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + x-ms-summary: Maximum number of times bundle can be accessed + description: + type: string + description: Public description + example: The public description of the bundle. + x-ms-summary: Public description + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + x-ms-summary: Bundle internal note + code: + type: string + description: Bundle code. This code forms the end part of the Public + URL. + example: abc123 + x-ms-summary: Bundle code. This code forms the end part of the + Public URL. + preview_only: + type: boolean + description: Restrict users to previewing files only? + x-ms-summary: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's + name and email address? + x-ms-summary: Show a registration page that captures the downloader's + name and email address? + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + x-ms-summary: ID of the clickwrap to use with this bundle. + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + x-ms-summary: ID of the associated inbox, if available. + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + x-ms-summary: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + application/x-www-form-urlencoded: + schema: + required: + - paths + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + paths: + type: array + description: A list of paths to include in this bundle. + example: + - file.txt + items: + type: string + x-ms-summary: A list of paths to include in this bundle. + password: + type: string + description: Password for this bundle. + example: Password + x-ms-summary: Password for this bundle. + form_field_set_id: + type: integer + description: Id of Form Field Set to use with this bundle + format: int32 + x-ms-summary: Id of Form Field Set to use with this bundle + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Bundle expiration date/time + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + x-ms-summary: Maximum number of times bundle can be accessed + description: + type: string + description: Public description + example: The public description of the bundle. + x-ms-summary: Public description + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + x-ms-summary: Bundle internal note + code: + type: string + description: Bundle code. This code forms the end part of the Public + URL. + example: abc123 + x-ms-summary: Bundle code. This code forms the end part of the + Public URL. + preview_only: + type: boolean + description: Restrict users to previewing files only? + x-ms-summary: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's + name and email address? + x-ms-summary: Show a registration page that captures the downloader's + name and email address? + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + x-ms-summary: ID of the clickwrap to use with this bundle. + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + x-ms-summary: ID of the associated inbox, if available. + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + x-ms-summary: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + multipart/form-data: + schema: + required: + - paths + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + paths: + type: array + description: A list of paths to include in this bundle. + example: + - file.txt + items: + type: string + x-ms-summary: A list of paths to include in this bundle. + password: + type: string + description: Password for this bundle. + example: Password + x-ms-summary: Password for this bundle. + form_field_set_id: + type: integer + description: Id of Form Field Set to use with this bundle + format: int32 + x-ms-summary: Id of Form Field Set to use with this bundle + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Bundle expiration date/time + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + x-ms-summary: Maximum number of times bundle can be accessed + description: + type: string + description: Public description + example: The public description of the bundle. + x-ms-summary: Public description + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + x-ms-summary: Bundle internal note + code: + type: string + description: Bundle code. This code forms the end part of the Public + URL. + example: abc123 + x-ms-summary: Bundle code. This code forms the end part of the + Public URL. + preview_only: + type: boolean + description: Restrict users to previewing files only? + x-ms-summary: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's + name and email address? + x-ms-summary: Show a registration page that captures the downloader's + name and email address? + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + x-ms-summary: ID of the clickwrap to use with this bundle. + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + x-ms-summary: ID of the associated inbox, if available. + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + x-ms-summary: Only allow access to recipients who have explicitly + received the share via an email sent through the Files.com UI? + required: true + responses: + 201: + description: The Bundles object. + content: + application/json: + schema: + $ref: '#/components/schemas/BundleEntity' + x-ms-summary: The Bundles object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + /bundles/{id}/share: + post: + tags: + - bundles + summary: Send email(s) with a link to bundle + description: Send email(s) with a link to bundle + operationId: PostBundlesIdShare + parameters: + - name: id + in: path + description: Bundle ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Bundle ID. + x-ms-summary: Bundle ID. + requestBody: + content: + application/json: + schema: + properties: + to: + type: array + description: A list of email addresses to share this bundle with. + Required unless `recipients` is used. + example: + - johndoe@gmail.com + items: + type: string + x-ms-summary: A list of email addresses to share this bundle with. + Required unless `recipients` is used. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + recipients: + type: array + description: A list of recipients to share this bundle with. Required + unless `to` is used. + example: + - name: John Doe + company: Acme Ltd + recipient: johndoe@gmail.com + items: + type: object + properties: {} + x-ms-summary: A list of recipients to share this bundle with. Required + unless `to` is used. + application/x-www-form-urlencoded: + schema: + properties: + to: + type: array + description: A list of email addresses to share this bundle with. + Required unless `recipients` is used. + example: + - johndoe@gmail.com + items: + type: string + x-ms-summary: A list of email addresses to share this bundle with. + Required unless `recipients` is used. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + recipients: + type: array + description: A list of recipients to share this bundle with. Required + unless `to` is used. + example: + - name: John Doe + company: Acme Ltd + recipient: johndoe@gmail.com + items: + type: object + properties: {} + x-ms-summary: A list of recipients to share this bundle with. Required + unless `to` is used. + multipart/form-data: + schema: + properties: + to: + type: array + description: A list of email addresses to share this bundle with. + Required unless `recipients` is used. + example: + - johndoe@gmail.com + items: + type: string + x-ms-summary: A list of email addresses to share this bundle with. + Required unless `recipients` is used. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + recipients: + type: array + description: A list of recipients to share this bundle with. Required + unless `to` is used. + example: + - name: John Doe + company: Acme Ltd + recipient: johndoe@gmail.com + items: + type: object + properties: {} + x-ms-summary: A list of recipients to share this bundle with. Required + unless `to` is used. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /bundle_downloads: + get: + tags: + - bundle_downloads + summary: List Bundle Downloads + description: List Bundle Downloads + operationId: GetBundleDownloads + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `created_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`. + - name: bundle_id + in: query + description: Bundle ID + schema: + type: integer + format: int32 + x-ms-summary: Bundle ID + x-ms-summary: Bundle ID + - name: bundle_registration_id + in: query + description: BundleRegistration ID + schema: + type: integer + format: int32 + x-ms-summary: BundleRegistration ID + x-ms-summary: BundleRegistration ID + responses: + 200: + description: A list of BundleDownloads objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BundleDownloadEntity' + x-ms-summary: A list of BundleDownloads objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /bundle_recipients: + get: + tags: + - bundle_recipients + summary: List Bundle Recipients + description: List Bundle Recipients + operationId: GetBundleRecipients + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `has_registrations`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `has_registrations`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `has_registrations`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `has_registrations`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `has_registrations`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `has_registrations`. + - name: bundle_id + in: query + description: List recipients for the bundle with this ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: List recipients for the bundle with this ID. + x-ms-summary: List recipients for the bundle with this ID. + responses: + 200: + description: A list of BundleRecipients objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BundleRecipientEntity' + x-ms-summary: A list of BundleRecipients objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - bundle_recipients + summary: Create Bundle Recipient + description: Create Bundle Recipient + operationId: PostBundleRecipients + requestBody: + content: + application/json: + schema: + required: + - bundle_id + - recipient + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + bundle_id: + type: integer + description: Bundle to share. + format: int32 + x-ms-summary: Bundle to share. + recipient: + type: string + description: Email addresses to share this bundle with. + example: johndoe@gmail.com + x-ms-summary: Email addresses to share this bundle with. + name: + type: string + description: Name of recipient. + example: John Smith + x-ms-summary: Name of recipient. + company: + type: string + description: Company of recipient. + example: Acme Ltd + x-ms-summary: Company of recipient. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + share_after_create: + type: boolean + description: Set to true to share the link with the recipient upon + creation. + x-ms-summary: Set to true to share the link with the recipient upon + creation. + application/x-www-form-urlencoded: + schema: + required: + - bundle_id + - recipient + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + bundle_id: + type: integer + description: Bundle to share. + format: int32 + x-ms-summary: Bundle to share. + recipient: + type: string + description: Email addresses to share this bundle with. + example: johndoe@gmail.com + x-ms-summary: Email addresses to share this bundle with. + name: + type: string + description: Name of recipient. + example: John Smith + x-ms-summary: Name of recipient. + company: + type: string + description: Company of recipient. + example: Acme Ltd + x-ms-summary: Company of recipient. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + share_after_create: + type: boolean + description: Set to true to share the link with the recipient upon + creation. + x-ms-summary: Set to true to share the link with the recipient upon + creation. + multipart/form-data: + schema: + required: + - bundle_id + - recipient + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + bundle_id: + type: integer + description: Bundle to share. + format: int32 + x-ms-summary: Bundle to share. + recipient: + type: string + description: Email addresses to share this bundle with. + example: johndoe@gmail.com + x-ms-summary: Email addresses to share this bundle with. + name: + type: string + description: Name of recipient. + example: John Smith + x-ms-summary: Name of recipient. + company: + type: string + description: Company of recipient. + example: Acme Ltd + x-ms-summary: Company of recipient. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + share_after_create: + type: boolean + description: Set to true to share the link with the recipient upon + creation. + x-ms-summary: Set to true to share the link with the recipient upon + creation. + required: true + responses: + 201: + description: The BundleRecipients object. + content: + application/json: + schema: + $ref: '#/components/schemas/BundleRecipientEntity' + x-ms-summary: The BundleRecipients object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /bundle_registrations: + get: + tags: + - bundle_registrations + summary: List Bundle Registrations + description: List Bundle Registrations + operationId: GetBundleRegistrations + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: bundle_id + in: query + description: ID of the associated Bundle + schema: + type: integer + format: int32 + x-ms-summary: ID of the associated Bundle + x-ms-summary: ID of the associated Bundle + responses: + 200: + description: A list of BundleRegistrations objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BundleRegistrationEntity' + x-ms-summary: A list of BundleRegistrations objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /clickwraps: + get: + tags: + - clickwraps + summary: List Clickwraps + description: List Clickwraps + operationId: GetClickwraps + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of Clickwraps objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ClickwrapEntity' + x-ms-summary: A list of Clickwraps objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - clickwraps + summary: Create Clickwrap + description: Create Clickwrap + operationId: PostClickwraps + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + example: Example Site NDA for Files.com Use + x-ms-summary: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + x-ms-summary: Body text of Clickwrap (supports Markdown formatting). + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Bundles? + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Inboxes? + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + enum: + - none + - require + x-ms-summary: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + example: Example Site NDA for Files.com Use + x-ms-summary: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + x-ms-summary: Body text of Clickwrap (supports Markdown formatting). + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Bundles? + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Inboxes? + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + enum: + - none + - require + x-ms-summary: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + multipart/form-data: + schema: + properties: + name: + type: string + description: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + example: Example Site NDA for Files.com Use + x-ms-summary: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + x-ms-summary: Body text of Clickwrap (supports Markdown formatting). + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Bundles? + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Inboxes? + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + enum: + - none + - require + x-ms-summary: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + responses: + 201: + description: The Clickwraps object. + content: + application/json: + schema: + $ref: '#/components/schemas/ClickwrapEntity' + x-ms-summary: The Clickwraps object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /clickwraps/{id}: + get: + tags: + - clickwraps + summary: Show Clickwrap + description: Show Clickwrap + operationId: GetClickwrapsId + parameters: + - name: id + in: path + description: Clickwrap ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Clickwrap ID. + x-ms-summary: Clickwrap ID. + responses: + 200: + description: The Clickwraps object. + content: + application/json: + schema: + $ref: '#/components/schemas/ClickwrapEntity' + x-ms-summary: The Clickwraps object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + delete: + tags: + - clickwraps + summary: Delete Clickwrap + description: Delete Clickwrap + operationId: DeleteClickwrapsId + parameters: + - name: id + in: path + description: Clickwrap ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Clickwrap ID. + x-ms-summary: Clickwrap ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + patch: + tags: + - clickwraps + summary: Update Clickwrap + description: Update Clickwrap + operationId: PatchClickwrapsId + parameters: + - name: id + in: path + description: Clickwrap ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Clickwrap ID. + x-ms-summary: Clickwrap ID. + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + example: Example Site NDA for Files.com Use + x-ms-summary: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + x-ms-summary: Body text of Clickwrap (supports Markdown formatting). + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Bundles? + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Inboxes? + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + enum: + - none + - require + x-ms-summary: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + example: Example Site NDA for Files.com Use + x-ms-summary: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + x-ms-summary: Body text of Clickwrap (supports Markdown formatting). + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Bundles? + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Inboxes? + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + enum: + - none + - require + x-ms-summary: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + multipart/form-data: + schema: + properties: + name: + type: string + description: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + example: Example Site NDA for Files.com Use + x-ms-summary: Name of the Clickwrap agreement (used when selecting + from multiple Clickwrap agreements.) + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + x-ms-summary: Body text of Clickwrap (supports Markdown formatting). + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Bundles? + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + enum: + - none + - available + - require + x-ms-summary: Use this Clickwrap for Inboxes? + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + enum: + - none + - require + x-ms-summary: 'Use this Clickwrap for User Registrations? Note: + This only applies to User Registrations where the User is invited + to your Files.com site using an E-Mail invitation process where + they then set their own password.' + responses: + 200: + description: The Clickwraps object. + content: + application/json: + schema: + $ref: '#/components/schemas/ClickwrapEntity' + x-ms-summary: The Clickwraps object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /dns_records: + get: + tags: + - dns_records + summary: Show site DNS configuration. + description: Show site DNS configuration. + operationId: GetDnsRecords + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of DnsRecords objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/DnsRecordEntity' + x-ms-summary: A list of DnsRecords objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-path_aliases: + - site/dns_records + /external_events: + get: + tags: + - external_events + summary: List External Events + description: List External Events + operationId: GetExternalEvents + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `remote_server_type`, + `event_type`, `created_at`, `status`, `site_id` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `remote_server_type`, `event_type`, `created_at`, `status`, `site_id` + or `folder_behavior_id`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `remote_server_type`, `event_type`, `created_at`, `status`, `site_id` or + `folder_behavior_id`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`, `event_type`, `remote_server_type`, + `status` or `folder_behavior_id`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`, `event_type`, + `remote_server_type`, `status` or `folder_behavior_id`. + responses: + 200: + description: A list of ExternalEvents objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ExternalEventEntity' + x-ms-summary: A list of ExternalEvents objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + post: + tags: + - external_events + summary: Create External Event + description: Create External Event + operationId: PostExternalEvents + requestBody: + content: + application/json: + schema: + required: + - body + - status + properties: + status: + type: string + description: Status of event. + enum: + - success + - error + - partial_failure + x-ms-summary: Status of event. + body: + type: string + description: Event body + x-ms-summary: Event body + application/x-www-form-urlencoded: + schema: + required: + - body + - status + properties: + status: + type: string + description: Status of event. + enum: + - success + - error + - partial_failure + x-ms-summary: Status of event. + body: + type: string + description: Event body + x-ms-summary: Event body + multipart/form-data: + schema: + required: + - body + - status + properties: + status: + type: string + description: Status of event. + enum: + - success + - error + - partial_failure + x-ms-summary: Status of event. + body: + type: string + description: Event body + x-ms-summary: Event body + required: true + responses: + 201: + description: The ExternalEvents object. + content: + application/json: + schema: + $ref: '#/components/schemas/ExternalEventEntity' + x-ms-summary: The ExternalEvents object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /external_events/{id}: + get: + tags: + - external_events + summary: Show External Event + description: Show External Event + operationId: GetExternalEventsId + parameters: + - name: id + in: path + description: External Event ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: External Event ID. + x-ms-summary: External Event ID. + responses: + 200: + description: The ExternalEvents object. + content: + application/json: + schema: + $ref: '#/components/schemas/ExternalEventEntity' + x-ms-summary: The ExternalEvents object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /files/{filePath}: + get: + tags: + - files + summary: Download file + description: Download file + operationId: FileDownload + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + - name: action + in: query + description: Can be blank, `redirect` or `stat`. If set to `stat`, we will + return file information but without a download URL, and without logging + a download. If set to `redirect` we will serve a 302 redirect directly + to the file. This is used for integrations with Zapier, and is not recommended + for most integrations. + schema: + type: string + x-ms-summary: Can be blank, `redirect` or `stat`. If set to `stat`, we + will return file information but without a download URL, and without logging + a download. If set to `redirect` we will serve a 302 redirect directly + to the file. This is used for integrations with Zapier, and is not recommended + for most integrations. + x-ms-summary: Can be blank, `redirect` or `stat`. If set to `stat`, we will + return file information but without a download URL, and without logging + a download. If set to `redirect` we will serve a 302 redirect directly + to the file. This is used for integrations with Zapier, and is not recommended + for most integrations. + - name: preview_size + in: query + description: Request a preview size. Can be `small` (default), `large`, `xlarge`, + or `pdf`. + schema: + type: string + x-ms-summary: Request a preview size. Can be `small` (default), `large`, + `xlarge`, or `pdf`. + x-ms-summary: Request a preview size. Can be `small` (default), `large`, + `xlarge`, or `pdf`. + - name: with_previews + in: query + description: Include file preview information? + schema: + type: boolean + x-ms-summary: Include file preview information? + x-ms-summary: Include file preview information? + - name: with_priority_color + in: query + description: Include file priority color information? + schema: + type: boolean + x-ms-summary: Include file priority color information? + x-ms-summary: Include file priority color information? + responses: + 200: + description: The Files object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileEntity' + x-ms-summary: The Files object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + - no_readonly + post: + tags: + - files + summary: Upload file + description: Upload file + operationId: PostFilesPath + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + requestBody: + content: + application/json: + schema: + required: + - etags[etag] + - etags[part] + properties: + action: + type: string + description: The action to perform. Can be `append`, `attachment`, + `end`, `upload`, `put`, or may not exist + x-ms-summary: The action to perform. Can be `append`, `attachment`, + `end`, `upload`, `put`, or may not exist + etags[etag]: + type: array + description: etag identifier. + items: + type: string + x-ms-summary: etag identifier. + etags[part]: + type: array + description: Part number. + items: + type: integer + format: int32 + x-ms-summary: Part number. + length: + type: integer + description: Length of file. + format: int32 + x-ms-summary: Length of file. + mkdir_parents: + type: boolean + description: Create parent directories if they do not exist? + x-ms-summary: Create parent directories if they do not exist? + part: + type: integer + description: Part if uploading a part. + format: int32 + x-ms-summary: Part if uploading a part. + parts: + type: integer + description: How many parts to fetch? + format: int32 + x-ms-summary: How many parts to fetch? + provided_mtime: + type: string + description: User provided modification time. + format: date-time + x-ms-summary: User provided modification time. + ref: + type: string + description: "" + x-ms-summary: "" + restart: + type: integer + description: File byte offset to restart from. + format: int32 + x-ms-summary: File byte offset to restart from. + size: + type: integer + description: Size of file. + format: int32 + x-ms-summary: Size of file. + structure: + type: string + description: If copying folder, copy just the structure? + x-ms-summary: If copying folder, copy just the structure? + with_rename: + type: boolean + description: Allow file rename instead of overwrite? + x-ms-summary: Allow file rename instead of overwrite? + application/x-www-form-urlencoded: + schema: + required: + - etags[etag] + - etags[part] + properties: + action: + type: string + description: The action to perform. Can be `append`, `attachment`, + `end`, `upload`, `put`, or may not exist + x-ms-summary: The action to perform. Can be `append`, `attachment`, + `end`, `upload`, `put`, or may not exist + etags[etag]: + type: array + description: etag identifier. + items: + type: string + x-ms-summary: etag identifier. + etags[part]: + type: array + description: Part number. + items: + type: integer + format: int32 + x-ms-summary: Part number. + length: + type: integer + description: Length of file. + format: int32 + x-ms-summary: Length of file. + mkdir_parents: + type: boolean + description: Create parent directories if they do not exist? + x-ms-summary: Create parent directories if they do not exist? + part: + type: integer + description: Part if uploading a part. + format: int32 + x-ms-summary: Part if uploading a part. + parts: + type: integer + description: How many parts to fetch? + format: int32 + x-ms-summary: How many parts to fetch? + provided_mtime: + type: string + description: User provided modification time. + format: date-time + x-ms-summary: User provided modification time. + ref: + type: string + description: "" + x-ms-summary: "" + restart: + type: integer + description: File byte offset to restart from. + format: int32 + x-ms-summary: File byte offset to restart from. + size: + type: integer + description: Size of file. + format: int32 + x-ms-summary: Size of file. + structure: + type: string + description: If copying folder, copy just the structure? + x-ms-summary: If copying folder, copy just the structure? + with_rename: + type: boolean + description: Allow file rename instead of overwrite? + x-ms-summary: Allow file rename instead of overwrite? + multipart/form-data: + schema: + required: + - etags[etag] + - etags[part] + properties: + action: + type: string + description: The action to perform. Can be `append`, `attachment`, + `end`, `upload`, `put`, or may not exist + x-ms-summary: The action to perform. Can be `append`, `attachment`, + `end`, `upload`, `put`, or may not exist + etags[etag]: + type: array + description: etag identifier. + items: + type: string + x-ms-summary: etag identifier. + etags[part]: + type: array + description: Part number. + items: + type: integer + format: int32 + x-ms-summary: Part number. + length: + type: integer + description: Length of file. + format: int32 + x-ms-summary: Length of file. + mkdir_parents: + type: boolean + description: Create parent directories if they do not exist? + x-ms-summary: Create parent directories if they do not exist? + part: + type: integer + description: Part if uploading a part. + format: int32 + x-ms-summary: Part if uploading a part. + parts: + type: integer + description: How many parts to fetch? + format: int32 + x-ms-summary: How many parts to fetch? + provided_mtime: + type: string + description: User provided modification time. + format: date-time + x-ms-summary: User provided modification time. + ref: + type: string + description: "" + x-ms-summary: "" + restart: + type: integer + description: File byte offset to restart from. + format: int32 + x-ms-summary: File byte offset to restart from. + size: + type: integer + description: Size of file. + format: int32 + x-ms-summary: Size of file. + structure: + type: string + description: If copying folder, copy just the structure? + x-ms-summary: If copying folder, copy just the structure? + with_rename: + type: boolean + description: Allow file rename instead of overwrite? + x-ms-summary: Allow file rename instead of overwrite? + required: true + responses: + 201: + description: The Files object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileEntity' + x-ms-summary: The Files object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + - inbox + delete: + tags: + - files + summary: Delete file/folder + description: Delete file/folder + operationId: DeleteFilesPath + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + - name: recursive + in: query + description: If true, will recursively delete folers. Otherwise, will error + on non-empty folders. + schema: + type: boolean + x-ms-summary: If true, will recursively delete folers. Otherwise, will + error on non-empty folders. + x-ms-summary: If true, will recursively delete folers. Otherwise, will error + on non-empty folders. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + - no_readonly + patch: + tags: + - files + summary: Update file/folder metadata + description: Update file/folder metadata + operationId: PatchFilesPath + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + requestBody: + content: + application/json: + schema: + properties: + provided_mtime: + type: string + description: Modified time of file. + format: date-time + x-ms-summary: Modified time of file. + priority_color: + type: string + description: Priority/Bookmark color of file. + example: red + x-ms-summary: Priority/Bookmark color of file. + application/x-www-form-urlencoded: + schema: + properties: + provided_mtime: + type: string + description: Modified time of file. + format: date-time + x-ms-summary: Modified time of file. + priority_color: + type: string + description: Priority/Bookmark color of file. + example: red + x-ms-summary: Priority/Bookmark color of file. + multipart/form-data: + schema: + properties: + provided_mtime: + type: string + description: Modified time of file. + format: date-time + x-ms-summary: Modified time of file. + priority_color: + type: string + description: Priority/Bookmark color of file. + example: red + x-ms-summary: Priority/Bookmark color of file. + responses: + 200: + description: The Files object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileEntity' + x-ms-summary: The Files object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + - no_readonly + /file_actions/metadata/{filePath}: + get: + tags: + - file_actions + summary: Return metadata for file/folder + description: Return metadata for file/folder + operationId: FileActionMetadata + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + - name: preview_size + in: query + description: Request a preview size. Can be `small` (default), `large`, `xlarge`, + or `pdf`. + schema: + type: string + x-ms-summary: Request a preview size. Can be `small` (default), `large`, + `xlarge`, or `pdf`. + x-ms-summary: Request a preview size. Can be `small` (default), `large`, + `xlarge`, or `pdf`. + - name: with_previews + in: query + description: Include file preview information? + schema: + type: boolean + x-ms-summary: Include file preview information? + x-ms-summary: Include file preview information? + - name: with_priority_color + in: query + description: Include file priority color information? + schema: + type: boolean + x-ms-summary: Include file priority color information? + x-ms-summary: Include file priority color information? + responses: + 200: + description: The FileActions object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileEntity' + x-ms-summary: The FileActions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + /file_actions/copy/{filePath}: + post: + tags: + - file_actions + summary: Copy file/folder + description: Copy file/folder + operationId: FileActionCopy + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + requestBody: + content: + application/json: + schema: + required: + - destination + properties: + destination: + type: string + description: Copy destination path. + x-ms-summary: Copy destination path. + structure: + type: boolean + description: Copy structure only? + x-ms-summary: Copy structure only? + application/x-www-form-urlencoded: + schema: + required: + - destination + properties: + destination: + type: string + description: Copy destination path. + x-ms-summary: Copy destination path. + structure: + type: boolean + description: Copy structure only? + x-ms-summary: Copy structure only? + multipart/form-data: + schema: + required: + - destination + properties: + destination: + type: string + description: Copy destination path. + x-ms-summary: Copy destination path. + structure: + type: boolean + description: Copy structure only? + x-ms-summary: Copy structure only? + required: true + responses: + 201: + description: The FileActions object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileActionEntity' + x-ms-summary: The FileActions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + /file_actions/move/{filePath}: + post: + tags: + - file_actions + summary: Move file/folder + description: Move file/folder + operationId: FileActionMove + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + requestBody: + content: + application/json: + schema: + required: + - destination + properties: + destination: + type: string + description: Move destination path. + x-ms-summary: Move destination path. + application/x-www-form-urlencoded: + schema: + required: + - destination + properties: + destination: + type: string + description: Move destination path. + x-ms-summary: Move destination path. + multipart/form-data: + schema: + required: + - destination + properties: + destination: + type: string + description: Move destination path. + x-ms-summary: Move destination path. + required: true + responses: + 201: + description: The FileActions object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileActionEntity' + x-ms-summary: The FileActions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + /file_actions/begin_upload/{filePath}: + post: + tags: + - file_actions + summary: Begin file upload + description: Begin file upload + operationId: FileActionBeginUpload + parameters: + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + requestBody: + content: + application/json: + schema: + properties: + mkdir_parents: + type: boolean + description: Create parent directories if they do not exist? + x-ms-summary: Create parent directories if they do not exist? + part: + type: integer + description: Part if uploading a part. + format: int32 + x-ms-summary: Part if uploading a part. + parts: + type: integer + description: How many parts to fetch? + format: int32 + x-ms-summary: How many parts to fetch? + ref: + type: string + description: "" + x-ms-summary: "" + restart: + type: integer + description: File byte offset to restart from. + format: int32 + x-ms-summary: File byte offset to restart from. + with_rename: + type: boolean + description: Allow file rename instead of overwrite? + x-ms-summary: Allow file rename instead of overwrite? + application/x-www-form-urlencoded: + schema: + properties: + mkdir_parents: + type: boolean + description: Create parent directories if they do not exist? + x-ms-summary: Create parent directories if they do not exist? + part: + type: integer + description: Part if uploading a part. + format: int32 + x-ms-summary: Part if uploading a part. + parts: + type: integer + description: How many parts to fetch? + format: int32 + x-ms-summary: How many parts to fetch? + ref: + type: string + description: "" + x-ms-summary: "" + restart: + type: integer + description: File byte offset to restart from. + format: int32 + x-ms-summary: File byte offset to restart from. + with_rename: + type: boolean + description: Allow file rename instead of overwrite? + x-ms-summary: Allow file rename instead of overwrite? + multipart/form-data: + schema: + properties: + mkdir_parents: + type: boolean + description: Create parent directories if they do not exist? + x-ms-summary: Create parent directories if they do not exist? + part: + type: integer + description: Part if uploading a part. + format: int32 + x-ms-summary: Part if uploading a part. + parts: + type: integer + description: How many parts to fetch? + format: int32 + x-ms-summary: How many parts to fetch? + ref: + type: string + description: "" + x-ms-summary: "" + restart: + type: integer + description: File byte offset to restart from. + format: int32 + x-ms-summary: File byte offset to restart from. + with_rename: + type: boolean + description: Allow file rename instead of overwrite? + x-ms-summary: Allow file rename instead of overwrite? + responses: + 200: + description: The FileActions object. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/FileUploadPartEntity' + x-ms-summary: The FileActions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + - inbox + /file_comments/{id}: + delete: + tags: + - file_comments + summary: Delete File Comment + description: Delete File Comment + operationId: DeleteFileCommentsId + parameters: + - name: id + in: path + description: File Comment ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: File Comment ID. + x-ms-summary: File Comment ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - file_comments + summary: Update File Comment + description: Update File Comment + operationId: PatchFileCommentsId + parameters: + - name: id + in: path + description: File Comment ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: File Comment ID. + x-ms-summary: File Comment ID. + requestBody: + content: + application/json: + schema: + required: + - body + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + application/x-www-form-urlencoded: + schema: + required: + - body + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + multipart/form-data: + schema: + required: + - body + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + required: true + responses: + 200: + description: The FileComments object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileCommentEntity' + x-ms-summary: The FileComments object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /file_comments: + post: + tags: + - file_comments + summary: Create File Comment + description: Create File Comment + operationId: PostFileComments + requestBody: + content: + application/json: + schema: + required: + - body + - path + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + path: + type: string + description: File path. + x-ms-summary: File path. + application/x-www-form-urlencoded: + schema: + required: + - body + - path + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + path: + type: string + description: File path. + x-ms-summary: File path. + multipart/form-data: + schema: + required: + - body + - path + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + path: + type: string + description: File path. + x-ms-summary: File path. + required: true + responses: + 201: + description: The FileComments object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileCommentEntity' + x-ms-summary: The FileComments object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /file_comments/files/{filePath}: + get: + tags: + - file_comments + summary: List File Comments by path + description: List File Comments by path + operationId: FileCommentListForPath + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + responses: + 200: + description: A list of FileComments objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/FileCommentEntity' + x-ms-summary: A list of FileComments objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /file_comment_reactions/{id}: + delete: + tags: + - file_comment_reactions + summary: Delete File Comment Reaction + description: Delete File Comment Reaction + operationId: DeleteFileCommentReactionsId + parameters: + - name: id + in: path + description: File Comment Reaction ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: File Comment Reaction ID. + x-ms-summary: File Comment Reaction ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /file_comment_reactions: + post: + tags: + - file_comment_reactions + summary: Create File Comment Reaction + description: Create File Comment Reaction + operationId: PostFileCommentReactions + requestBody: + content: + application/json: + schema: + required: + - emoji + - file_comment_id + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + file_comment_id: + type: integer + description: ID of file comment to attach reaction to. + format: int32 + x-ms-summary: ID of file comment to attach reaction to. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + application/x-www-form-urlencoded: + schema: + required: + - emoji + - file_comment_id + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + file_comment_id: + type: integer + description: ID of file comment to attach reaction to. + format: int32 + x-ms-summary: ID of file comment to attach reaction to. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + multipart/form-data: + schema: + required: + - emoji + - file_comment_id + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + file_comment_id: + type: integer + description: ID of file comment to attach reaction to. + format: int32 + x-ms-summary: ID of file comment to attach reaction to. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + required: true + responses: + 201: + description: The FileCommentReactions object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileCommentReactionEntity' + x-ms-summary: The FileCommentReactions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /file_migrations/{id}: + get: + tags: + - file_migrations + summary: Show File Migration + description: Show File Migration + operationId: GetFileMigrationsId + parameters: + - name: id + in: path + description: File Migration ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: File Migration ID. + x-ms-summary: File Migration ID. + responses: + 200: + description: The FileMigrations object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileMigrationEntity' + x-ms-summary: The FileMigrations object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + /folders/{folderPath}: + get: + tags: + - folders + summary: List Folders by path + description: List Folders by path + operationId: FolderListForPath + parameters: + - name: cursor + in: query + description: Send cursor to resume an existing list from the point at which + you left off. Get a cursor from an existing list via the X-Files-Cursor + header. + schema: + type: string + x-ms-summary: Send cursor to resume an existing list from the point at which + you left off. Get a cursor from an existing list via the X-Files-Cursor + header. + x-ms-summary: Send cursor to resume an existing list from the point at which + you left off. Get a cursor from an existing list via the X-Files-Cursor + header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: folderPath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + - name: filter + in: query + description: If specified, will filter folders/files list by this string. Wildcards + of `*` and `?` are acceptable here. + schema: + type: string + x-ms-summary: If specified, will filter folders/files list by this string. Wildcards + of `*` and `?` are acceptable here. + x-ms-summary: If specified, will filter folders/files list by this string. Wildcards + of `*` and `?` are acceptable here. + - name: preview_size + in: query + description: Request a preview size. Can be `small` (default), `large`, `xlarge`, + or `pdf`. + schema: + type: string + x-ms-summary: Request a preview size. Can be `small` (default), `large`, + `xlarge`, or `pdf`. + x-ms-summary: Request a preview size. Can be `small` (default), `large`, + `xlarge`, or `pdf`. + - name: search + in: query + description: If `search_all` is `true`, provide the search string here. Otherwise, + this parameter acts like an alias of `filter`. + schema: + type: string + x-ms-summary: If `search_all` is `true`, provide the search string here. Otherwise, + this parameter acts like an alias of `filter`. + x-ms-summary: If `search_all` is `true`, provide the search string here. Otherwise, + this parameter acts like an alias of `filter`. + - name: search_all + in: query + description: Search entire site? + schema: + type: boolean + x-ms-summary: Search entire site? + x-ms-summary: Search entire site? + - name: with_previews + in: query + description: Include file previews? + schema: + type: boolean + x-ms-summary: Include file previews? + x-ms-summary: Include file previews? + - name: with_priority_color + in: query + description: Include file priority color information? + schema: + type: boolean + x-ms-summary: Include file priority color information? + x-ms-summary: Include file priority color information? + responses: + 200: + description: A list of Folders objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/FileEntity' + x-ms-summary: A list of Folders objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + post: + tags: + - folders + summary: Create folder + description: Create folder + operationId: PostFoldersPath + parameters: + - name: folderPath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + responses: + 201: + description: The Folders object. + content: + application/json: + schema: + $ref: '#/components/schemas/FileEntity' + x-ms-summary: The Folders object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + /form_field_sets: + get: + tags: + - form_field_sets + summary: List Form Field Sets + description: List Form Field Sets + operationId: GetFormFieldSets + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of FormFieldSets objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/FormFieldSetEntity' + x-ms-summary: A list of FormFieldSets objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - form_field_sets + summary: Create Form Field Set + description: Create Form Field Set + operationId: PostFormFieldSets + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/postFormFieldSets' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/postFormFieldSets' + multipart/form-data: + schema: + $ref: '#/components/schemas/postFormFieldSets' + required: true + responses: + 201: + description: The FormFieldSets object. + content: + application/json: + schema: + $ref: '#/components/schemas/FormFieldSetEntity' + x-ms-summary: The FormFieldSets object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-codegen-request-body-name: FormFieldSets + /form_field_sets/{id}: + get: + tags: + - form_field_sets + summary: Show Form Field Set + description: Show Form Field Set + operationId: GetFormFieldSetsId + parameters: + - name: id + in: path + description: Form Field Set ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Form Field Set ID. + x-ms-summary: Form Field Set ID. + responses: + 200: + description: The FormFieldSets object. + content: + application/json: + schema: + $ref: '#/components/schemas/FormFieldSetEntity' + x-ms-summary: The FormFieldSets object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - form_field_sets + summary: Delete Form Field Set + description: Delete Form Field Set + operationId: DeleteFormFieldSetsId + parameters: + - name: id + in: path + description: Form Field Set ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Form Field Set ID. + x-ms-summary: Form Field Set ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - form_field_sets + summary: Update Form Field Set + description: Update Form Field Set + operationId: PatchFormFieldSetsId + parameters: + - name: id + in: path + description: Form Field Set ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Form Field Set ID. + x-ms-summary: Form Field Set ID. + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/patchFormFieldSets' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/patchFormFieldSets' + multipart/form-data: + schema: + $ref: '#/components/schemas/patchFormFieldSets' + required: true + responses: + 200: + description: The FormFieldSets object. + content: + application/json: + schema: + $ref: '#/components/schemas/FormFieldSetEntity' + x-ms-summary: The FormFieldSets object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-codegen-request-body-name: FormFieldSets + /groups/{group_id}/users: + get: + tags: + - groups + summary: List Group Users + description: List Group Users + operationId: GetGroupsGroupIdUsers + parameters: + - name: user_id + in: query + description: User ID. If provided, will return group_users of this user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. If provided, will return group_users of this user. + x-ms-summary: User ID. If provided, will return group_users of this user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: group_id + in: path + description: Group ID. If provided, will return group_users of this group. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID. If provided, will return group_users of this group. + x-ms-summary: Group ID. If provided, will return group_users of this group. + responses: + 200: + description: A list of GroupUsers objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: A list of GroupUsers objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - user/groups + - users/:user_id/groups + - groups/:group_id/users + post: + tags: + - groups + summary: Create User + description: Create User + operationId: PostGroupsGroupIdUsers + parameters: + - name: group_id + in: path + description: Group ID to associate this user with. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID to associate this user with. + x-ms-summary: Group ID to associate this user with. + requestBody: + content: + application/json: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + application/x-www-form-urlencoded: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + multipart/form-data: + schema: + properties: + avatar_file: + type: string + description: An image file for your user avatar. + format: binary + x-ms-summary: An image file for your user avatar. + avatar_delete: + type: boolean + description: If true, the avatar will be deleted. + x-ms-summary: If true, the avatar will be deleted. + change_password: + type: string + description: Used for changing a password on an existing user. + x-ms-summary: Used for changing a password on an existing user. + change_password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `change_password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `change_password`. + email: + type: string + description: User's email. + x-ms-summary: User's email. + grant_permission: + type: string + description: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + x-ms-summary: Permission to grant on the user root. Can be blank + or `full`, `read`, `write`, `list`, or `history`. + group_ids: + type: string + description: A list of group ids to associate this user with. Comma + delimited. + x-ms-summary: A list of group ids to associate this user with. Comma + delimited. + imported_password_hash: + type: string + description: Pre-calculated hash of the user's password. + x-ms-summary: Pre-calculated hash of the user's password. + password: + type: string + description: User password. + x-ms-summary: User password. + password_confirmation: + type: string + description: Optional, but if provided, we will ensure that it matches + the value sent in `password`. + x-ms-summary: Optional, but if provided, we will ensure that it + matches the value sent in `password`. + announcements_read: + type: boolean + description: Signifies that the user has read all the announcements + in the UI. + x-ms-summary: Signifies that the user has read all the announcements + in the UI. + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + x-ms-summary: A list of allowed IPs if applicable. Newline delimited + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + example: true + x-ms-summary: 'DEPRECATED: Can the user create Bundles (aka Share + Links)? Use the bundle permission instead.' + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Scheduled Date/Time at which user will be deactivated + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + x-ms-summary: How is this user authenticated? + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, + payments, and invoices? + x-ms-summary: Allow this user to perform operations on the account, + payments, and invoices? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + x-ms-summary: Exempt this user from being disabled based on inactivity? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + x-ms-summary: Allow this user to skip site-wide IP blacklists? + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + x-ms-summary: Can the user connect with WebDAV? + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + example: true + x-ms-summary: Is user disabled? Disabled users cannot log in, and + do not count for billing purposes. Users can be automatically + disabled after an inactivity period via a Site setting. + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + x-ms-summary: Can the user access with FTP/FTPS? + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + x-ms-summary: Text to display to the user in the header of the UI + language: + type: string + description: Preferred language + example: en + x-ms-summary: Preferred language + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + format: int32 + example: 18 + x-ms-summary: Hour of the day at which daily notifications should + be sent. Can be in range 0 to 23 + name: + type: string + description: User's full name + example: John Doe + x-ms-summary: User's full name + company: + type: string + description: User's company + example: ACME Corp. + x-ms-summary: User's company + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + x-ms-summary: Any internal notes on the user + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + x-ms-summary: Enable integration with Office for the web? + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + x-ms-summary: Number of days to allow user to use the same password + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate + expiration notifications and overages? + example: true + x-ms-summary: Should the user receive admin alerts such a certificate + expiration notifications and overages? + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + x-ms-summary: Is a password change required upon next user login? + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + x-ms-summary: Can this user access the REST API? + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it + a shared/bot user? + example: true + x-ms-summary: Does this user manage it's own credentials or is it + a shared/bot user? + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + x-ms-summary: Can the user access with SFTP? + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + x-ms-summary: Is the user an administrator for this site? + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + x-ms-summary: Skip Welcome page in the UI? + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: SSL required setting + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + x-ms-summary: SSO (Single Sign On) strategy ID for the user, if + applicable. + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + x-ms-summary: Is the user subscribed to the newsletter? + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + x-ms-summary: 2FA required setting + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + x-ms-summary: User time zone + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + x-ms-summary: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, + Desktop, or Web interface. + username: + type: string + description: User's username + example: user + x-ms-summary: User's username + responses: + 201: + description: The Users object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserEntity' + x-ms-summary: The Users object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - groups/:group_id/users + /groups/{group_id}/permissions: + get: + tags: + - groups + summary: List Permissions + description: List Permissions + operationId: GetGroupsGroupIdPermissions + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `group_id`, + `path`, `user_id` or `permission`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `group_id`, `path`, `user_id` or `permission`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `group_id`, `path`, `user_id` or `permission`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `group_id`, `user_id` or + `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `group_id`, `user_id` or + `path`. + # - name: path + # in: query + # description: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + # schema: + # type: string + # x-ms-summary: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + # x-ms-summary: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + - name: group_id + in: path + description: 'DEPRECATED: Group ID. If provided, will scope permissions to + this group. Use `filter[group_id]` instead.' + required: true + schema: + type: string + x-ms-summary: 'DEPRECATED: Group ID. If provided, will scope permissions + to this group. Use `filter[group_id]` instead.`' + x-ms-summary: 'DEPRECATED: Group ID. If provided, will scope permissions + to this group. Use `filter[group_id]` instead.`' + - name: user_id + in: query + description: 'DEPRECATED: User ID. If provided, will scope permissions to + this user. Use `filter[user_id]` instead.' + schema: + type: string + x-ms-summary: 'DEPRECATED: User ID. If provided, will scope permissions + to this user. Use `filter[user_id]` instead.`' + x-ms-summary: 'DEPRECATED: User ID. If provided, will scope permissions to + this user. Use `filter[user_id]` instead.`' + - name: include_groups + in: query + description: If searching by user or group, also include user's permissions + that are inherited from its groups? + schema: + type: boolean + x-ms-summary: If searching by user or group, also include user's permissions + that are inherited from its groups? + x-ms-summary: If searching by user or group, also include user's permissions + that are inherited from its groups? + responses: + 200: + description: A list of Permissions objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PermissionEntity' + x-ms-summary: A list of Permissions objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - groups/:group_id/permissions + - users/:user_id/permissions + /groups/{group_id}/memberships/{user_id}: + delete: + tags: + - groups + summary: Delete Group User + description: Delete Group User + operationId: DeleteGroupsGroupIdMembershipsUserId + parameters: + - name: group_id + in: path + description: Group ID from which to remove user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID from which to remove user. + x-ms-summary: Group ID from which to remove user. + - name: user_id + in: path + description: User ID to remove from group. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID to remove from group. + x-ms-summary: User ID to remove from group. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + x-path_aliases: + - groups/:group_id/memberships/:user_id + patch: + tags: + - groups + summary: Update Group User + description: Update Group User + operationId: PatchGroupsGroupIdMembershipsUserId + parameters: + - name: group_id + in: path + description: Group ID to add user to. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID to add user to. + x-ms-summary: Group ID to add user to. + - name: user_id + in: path + description: User ID to add to group. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID to add to group. + x-ms-summary: User ID to add to group. + requestBody: + content: + application/json: + schema: + properties: + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + application/x-www-form-urlencoded: + schema: + properties: + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + multipart/form-data: + schema: + properties: + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + responses: + 200: + description: The GroupUsers object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: The GroupUsers object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + x-path_aliases: + - groups/:group_id/memberships/:user_id + /groups/{id}: + get: + tags: + - groups + summary: Show Group + description: Show Group + operationId: GetGroupsId + parameters: + - name: id + in: path + description: Group ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID. + x-ms-summary: Group ID. + responses: + 200: + description: The Groups object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupEntity' + x-ms-summary: The Groups object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + delete: + tags: + - groups + summary: Delete Group + description: Delete Group + operationId: DeleteGroupsId + parameters: + - name: id + in: path + description: Group ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID. + x-ms-summary: Group ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + patch: + tags: + - groups + summary: Update Group + description: Update Group + operationId: PatchGroupsId + parameters: + - name: id + in: path + description: Group ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID. + x-ms-summary: Group ID. + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Group name. + x-ms-summary: Group name. + notes: + type: string + description: Group notes. + x-ms-summary: Group notes. + user_ids: + type: string + description: A list of user ids. If sent as a string, should be + comma-delimited. + x-ms-summary: A list of user ids. If sent as a string, should be + comma-delimited. + admin_ids: + type: string + description: A list of group admin user ids. If sent as a string, + should be comma-delimited. + x-ms-summary: A list of group admin user ids. If sent as a string, + should be comma-delimited. + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Group name. + x-ms-summary: Group name. + notes: + type: string + description: Group notes. + x-ms-summary: Group notes. + user_ids: + type: string + description: A list of user ids. If sent as a string, should be + comma-delimited. + x-ms-summary: A list of user ids. If sent as a string, should be + comma-delimited. + admin_ids: + type: string + description: A list of group admin user ids. If sent as a string, + should be comma-delimited. + x-ms-summary: A list of group admin user ids. If sent as a string, + should be comma-delimited. + multipart/form-data: + schema: + properties: + name: + type: string + description: Group name. + x-ms-summary: Group name. + notes: + type: string + description: Group notes. + x-ms-summary: Group notes. + user_ids: + type: string + description: A list of user ids. If sent as a string, should be + comma-delimited. + x-ms-summary: A list of user ids. If sent as a string, should be + comma-delimited. + admin_ids: + type: string + description: A list of group admin user ids. If sent as a string, + should be comma-delimited. + x-ms-summary: A list of group admin user ids. If sent as a string, + should be comma-delimited. + responses: + 200: + description: The Groups object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupEntity' + x-ms-summary: The Groups object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /groups: + get: + tags: + - groups + summary: List Groups + description: List Groups + operationId: GetGroups + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `name`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `name`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `name`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `name`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `name`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `name`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `name`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `name`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `name`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `name`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `name`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `name`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `name`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `name`. + - name: ids + in: query + description: Comma-separated list of group ids to include in results. + schema: + type: string + x-ms-summary: Comma-separated list of group ids to include in results. + x-ms-summary: Comma-separated list of group ids to include in results. + responses: + 200: + description: A list of Groups objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/GroupEntity' + x-ms-summary: A list of Groups objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + post: + tags: + - groups + summary: Create Group + description: Create Group + operationId: PostGroups + requestBody: + content: + application/json: + schema: + properties: + name: + type: string + description: Group name. + x-ms-summary: Group name. + notes: + type: string + description: Group notes. + x-ms-summary: Group notes. + user_ids: + type: string + description: A list of user ids. If sent as a string, should be + comma-delimited. + x-ms-summary: A list of user ids. If sent as a string, should be + comma-delimited. + admin_ids: + type: string + description: A list of group admin user ids. If sent as a string, + should be comma-delimited. + x-ms-summary: A list of group admin user ids. If sent as a string, + should be comma-delimited. + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Group name. + x-ms-summary: Group name. + notes: + type: string + description: Group notes. + x-ms-summary: Group notes. + user_ids: + type: string + description: A list of user ids. If sent as a string, should be + comma-delimited. + x-ms-summary: A list of user ids. If sent as a string, should be + comma-delimited. + admin_ids: + type: string + description: A list of group admin user ids. If sent as a string, + should be comma-delimited. + x-ms-summary: A list of group admin user ids. If sent as a string, + should be comma-delimited. + multipart/form-data: + schema: + properties: + name: + type: string + description: Group name. + x-ms-summary: Group name. + notes: + type: string + description: Group notes. + x-ms-summary: Group notes. + user_ids: + type: string + description: A list of user ids. If sent as a string, should be + comma-delimited. + x-ms-summary: A list of user ids. If sent as a string, should be + comma-delimited. + admin_ids: + type: string + description: A list of group admin user ids. If sent as a string, + should be comma-delimited. + x-ms-summary: A list of group admin user ids. If sent as a string, + should be comma-delimited. + responses: + 201: + description: The Groups object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupEntity' + x-ms-summary: The Groups object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /group_users/{id}: + delete: + tags: + - group_users + summary: Delete Group User + description: Delete Group User + operationId: DeleteGroupUsersId + parameters: + - name: id + in: path + description: Group User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group User ID. + x-ms-summary: Group User ID. + - name: group_id + in: query + description: Group ID from which to remove user. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group ID from which to remove user. + x-ms-summary: Group ID from which to remove user. + - name: user_id + in: query + description: User ID to remove from group. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID to remove from group. + x-ms-summary: User ID to remove from group. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + x-path_aliases: + - groups/:group_id/memberships/:user_id + patch: + tags: + - group_users + summary: Update Group User + description: Update Group User + operationId: PatchGroupUsersId + parameters: + - name: id + in: path + description: Group User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Group User ID. + x-ms-summary: Group User ID. + requestBody: + content: + application/json: + schema: + required: + - group_id + - user_id + properties: + group_id: + type: integer + description: Group ID to add user to. + format: int32 + x-ms-summary: Group ID to add user to. + user_id: + type: integer + description: User ID to add to group. + format: int32 + x-ms-summary: User ID to add to group. + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + application/x-www-form-urlencoded: + schema: + required: + - group_id + - user_id + properties: + group_id: + type: integer + description: Group ID to add user to. + format: int32 + x-ms-summary: Group ID to add user to. + user_id: + type: integer + description: User ID to add to group. + format: int32 + x-ms-summary: User ID to add to group. + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + multipart/form-data: + schema: + required: + - group_id + - user_id + properties: + group_id: + type: integer + description: Group ID to add user to. + format: int32 + x-ms-summary: Group ID to add user to. + user_id: + type: integer + description: User ID to add to group. + format: int32 + x-ms-summary: User ID to add to group. + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + required: true + responses: + 200: + description: The GroupUsers object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: The GroupUsers object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + x-path_aliases: + - groups/:group_id/memberships/:user_id + /group_users: + get: + tags: + - group_users + summary: List Group Users + description: List Group Users + operationId: GetGroupUsers + parameters: + - name: user_id + in: query + description: User ID. If provided, will return group_users of this user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. If provided, will return group_users of this user. + x-ms-summary: User ID. If provided, will return group_users of this user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: group_id + in: query + description: Group ID. If provided, will return group_users of this group. + schema: + type: integer + format: int32 + x-ms-summary: Group ID. If provided, will return group_users of this group. + x-ms-summary: Group ID. If provided, will return group_users of this group. + responses: + 200: + description: A list of GroupUsers objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: A list of GroupUsers objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - user/groups + - users/:user_id/groups + - groups/:group_id/users + post: + tags: + - group_users + summary: Create Group User + description: Create Group User + operationId: PostGroupUsers + requestBody: + content: + application/json: + schema: + required: + - group_id + - user_id + properties: + group_id: + type: integer + description: Group ID to add user to. + format: int32 + x-ms-summary: Group ID to add user to. + user_id: + type: integer + description: User ID to add to group. + format: int32 + x-ms-summary: User ID to add to group. + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + application/x-www-form-urlencoded: + schema: + required: + - group_id + - user_id + properties: + group_id: + type: integer + description: Group ID to add user to. + format: int32 + x-ms-summary: Group ID to add user to. + user_id: + type: integer + description: User ID to add to group. + format: int32 + x-ms-summary: User ID to add to group. + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + multipart/form-data: + schema: + required: + - group_id + - user_id + properties: + group_id: + type: integer + description: Group ID to add user to. + format: int32 + x-ms-summary: Group ID to add user to. + user_id: + type: integer + description: User ID to add to group. + format: int32 + x-ms-summary: User ID to add to group. + admin: + type: boolean + description: Is the user a group administrator? + x-ms-summary: Is the user a group administrator? + required: true + responses: + 201: + description: The GroupUsers object. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupUserEntity' + x-ms-summary: The GroupUsers object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /history/files/{filePath}: + get: + tags: + - history + summary: List history for specific file. + description: List history for specific file. + operationId: HistoryListForFile + parameters: + - name: start_at + in: query + description: Leave blank or set to a date/time to filter earlier entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + - name: end_at + in: query + description: Leave blank or set to a date/time to filter later entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter later entries. + x-ms-summary: Leave blank or set to a date/time to filter later entries. + - name: display + in: query + description: Display format. Leave blank or set to `full` or `parent`. + schema: + type: string + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `user_id` + and `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + - name: filePath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + responses: + 200: + description: A list of History objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ActionEntity' + x-ms-summary: A list of History objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /history/folders/{folderPath}: + get: + tags: + - history + summary: List history for specific folder. + description: List history for specific folder. + operationId: HistoryListForFolder + parameters: + - name: start_at + in: query + description: Leave blank or set to a date/time to filter earlier entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + - name: end_at + in: query + description: Leave blank or set to a date/time to filter later entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter later entries. + x-ms-summary: Leave blank or set to a date/time to filter later entries. + - name: display + in: query + description: Display format. Leave blank or set to `full` or `parent`. + schema: + type: string + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `user_id` + and `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + - name: folderPath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + responses: + 200: + description: A list of History objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ActionEntity' + x-ms-summary: A list of History objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /history/users/{user_id}: + get: + tags: + - history + summary: List history for specific user. + description: List history for specific user. + operationId: HistoryListForUser + parameters: + - name: start_at + in: query + description: Leave blank or set to a date/time to filter earlier entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + - name: end_at + in: query + description: Leave blank or set to a date/time to filter later entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter later entries. + x-ms-summary: Leave blank or set to a date/time to filter later entries. + - name: display + in: query + description: Display format. Leave blank or set to `full` or `parent`. + schema: + type: string + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `user_id` + and `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + - name: user_id + in: path + description: User ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User ID. + x-ms-summary: User ID. + responses: + 200: + description: A list of History objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ActionEntity' + x-ms-summary: A list of History objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /history/login: + get: + tags: + - history + summary: List site login history. + description: List site login history. + operationId: HistoryListLogins + parameters: + - name: start_at + in: query + description: Leave blank or set to a date/time to filter earlier entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + - name: end_at + in: query + description: Leave blank or set to a date/time to filter later entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter later entries. + x-ms-summary: Leave blank or set to a date/time to filter later entries. + - name: display + in: query + description: Display format. Leave blank or set to `full` or `parent`. + schema: + type: string + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `user_id` + and `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `user_id` and `created_at`. + responses: + 200: + description: A list of History objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ActionEntity' + x-ms-summary: A list of History objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /history: + get: + tags: + - history + summary: List site full action history. + description: List site full action history. + operationId: HistoryList + parameters: + - name: start_at + in: query + description: Leave blank or set to a date/time to filter earlier entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + x-ms-summary: Leave blank or set to a date/time to filter earlier entries. + - name: end_at + in: query + description: Leave blank or set to a date/time to filter later entries. + schema: + type: string + format: date-time + x-ms-summary: Leave blank or set to a date/time to filter later entries. + x-ms-summary: Leave blank or set to a date/time to filter later entries. + - name: display + in: query + description: Display format. Leave blank or set to `full` or `parent`. + schema: + type: string + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + x-ms-summary: Display format. Leave blank or set to `full` or `parent`. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `path`, + `folder`, `user_id` or `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `path`, `folder`, `user_id` or `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `path`, `folder`, `user_id` or `created_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `folder` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `user_id`, `folder` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `folder` or `path`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `user_id`, `folder` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `user_id`, `folder` or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `user_id`, `folder` or `path`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `user_id`, `folder` + or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `user_id`, `folder` + or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `user_id`, `folder` + or `path`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `folder` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `user_id`, `folder` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `folder` or `path`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `user_id`, `folder` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `user_id`, `folder` or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `user_id`, `folder` or `path`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `user_id`, `folder` or + `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `user_id`, `folder` + or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `user_id`, `folder` or + `path`. + responses: + 200: + description: A list of History objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ActionEntity' + x-ms-summary: A list of History objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /history_exports: + post: + tags: + - history_exports + summary: Create History Export + description: Create History Export + operationId: PostHistoryExports + requestBody: + content: + application/json: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Start date/time of export range. + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: End date/time of export range. + query_action: + type: string + description: 'Filter results by this this action type. Valid values: + `create`, `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, + `copy`, `user_create`, `user_update`, `user_destroy`, `group_create`, + `group_update`, `group_destroy`, `permission_create`, `permission_destroy`, + `api_key_create`, `api_key_update`, `api_key_destroy`' + example: read + x-ms-summary: 'Filter results by this this action type. Valid values: + `create`, `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, + `copy`, `user_create`, `user_update`, `user_destroy`, `group_create`, + `group_update`, `group_destroy`, `permission_create`, `permission_destroy`, + `api_key_create`, `api_key_update`, `api_key_destroy`' + query_interface: + type: string + description: 'Filter results by this this interface type. Valid + values: `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, + `dav`, `desktop`, `restapi`, `scim`, `office`, `mobile`' + example: ftp + x-ms-summary: 'Filter results by this this interface type. Valid + values: `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, + `dav`, `desktop`, `restapi`, `scim`, `office`, `mobile`' + query_user_id: + type: string + description: Return results that are actions performed by the user + indiciated by this User ID + example: "1" + x-ms-summary: Return results that are actions performed by the user + indiciated by this User ID + query_file_id: + type: string + description: Return results that are file actions related to the + file indicated by this File ID + example: "1" + x-ms-summary: Return results that are file actions related to the + file indicated by this File ID + query_parent_id: + type: string + description: Return results that are file actions inside the parent + folder specified by this folder ID + example: "1" + x-ms-summary: Return results that are file actions inside the parent + folder specified by this folder ID + query_path: + type: string + description: Return results that are file actions related to this + path. + example: MyFile.txt + x-ms-summary: Return results that are file actions related to this + path. + query_folder: + type: string + description: Return results that are file actions related to files + or folders inside this folder path. + example: Folder + x-ms-summary: Return results that are file actions related to files + or folders inside this folder path. + query_src: + type: string + description: Return results that are file moves originating from + this path. + example: SrcFolder + x-ms-summary: Return results that are file moves originating from + this path. + query_destination: + type: string + description: Return results that are file moves with this path as + destination. + example: DestFolder + x-ms-summary: Return results that are file moves with this path + as destination. + query_ip: + type: string + description: Filter results by this IP address. + example: 127.0.0.1 + x-ms-summary: Filter results by this IP address. + query_username: + type: string + description: Filter results by this username. + example: jerry + x-ms-summary: Filter results by this username. + query_failure_type: + type: string + description: 'If searching for Histories about login failures, this + parameter restricts results to failures of this specific type. Valid + values: `expired_trial`, `account_overdue`, `locked_out`, `ip_mismatch`, + `password_mismatch`, `site_mismatch`, `username_not_found`, `none`, + `no_ftp_permission`, `no_web_permission`, `no_directory`, `errno_enoent`, + `no_sftp_permission`, `no_dav_permission`, `no_restapi_permission`, + `key_mismatch`, `region_mismatch`, `expired_access`, `desktop_ip_mismatch`, + `desktop_api_key_not_used_quickly_enough`, `disabled`, `country_mismatch`' + example: bad_password + x-ms-summary: 'If searching for Histories about login failures, + this parameter restricts results to failures of this specific + type. Valid values: `expired_trial`, `account_overdue`, `locked_out`, + `ip_mismatch`, `password_mismatch`, `site_mismatch`, `username_not_found`, + `none`, `no_ftp_permission`, `no_web_permission`, `no_directory`, + `errno_enoent`, `no_sftp_permission`, `no_dav_permission`, `no_restapi_permission`, + `key_mismatch`, `region_mismatch`, `expired_access`, `desktop_ip_mismatch`, + `desktop_api_key_not_used_quickly_enough`, `disabled`, `country_mismatch`' + query_target_id: + type: string + description: If searching for Histories about specific objects (such + as Users, or API Keys), this paremeter restricts results to objects + that match this ID. + example: "1" + x-ms-summary: If searching for Histories about specific objects + (such as Users, or API Keys), this paremeter restricts results + to objects that match this ID. + query_target_name: + type: string + description: If searching for Histories about Users, Groups or other + objects with names, this parameter restricts results to objects + with this name/username. + example: full + x-ms-summary: If searching for Histories about Users, Groups or + other objects with names, this parameter restricts results to + objects with this name/username. + query_target_permission: + type: string + description: If searching for Histories about Permisisons, this + parameter restricts results to permissions of this level. + example: full + x-ms-summary: If searching for Histories about Permisisons, this + parameter restricts results to permissions of this level. + query_target_user_id: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this user ID. + example: "1" + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this user ID. + query_target_username: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this username. + example: jerry + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this username. + query_target_platform: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys associated with this platform. + example: windows + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys associated with this platform. + query_target_permission_set: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys with this permission set. + example: desktop_app + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys with this permission set. + application/x-www-form-urlencoded: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Start date/time of export range. + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: End date/time of export range. + query_action: + type: string + description: 'Filter results by this this action type. Valid values: + `create`, `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, + `copy`, `user_create`, `user_update`, `user_destroy`, `group_create`, + `group_update`, `group_destroy`, `permission_create`, `permission_destroy`, + `api_key_create`, `api_key_update`, `api_key_destroy`' + example: read + x-ms-summary: 'Filter results by this this action type. Valid values: + `create`, `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, + `copy`, `user_create`, `user_update`, `user_destroy`, `group_create`, + `group_update`, `group_destroy`, `permission_create`, `permission_destroy`, + `api_key_create`, `api_key_update`, `api_key_destroy`' + query_interface: + type: string + description: 'Filter results by this this interface type. Valid + values: `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, + `dav`, `desktop`, `restapi`, `scim`, `office`, `mobile`' + example: ftp + x-ms-summary: 'Filter results by this this interface type. Valid + values: `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, + `dav`, `desktop`, `restapi`, `scim`, `office`, `mobile`' + query_user_id: + type: string + description: Return results that are actions performed by the user + indiciated by this User ID + example: "1" + x-ms-summary: Return results that are actions performed by the user + indiciated by this User ID + query_file_id: + type: string + description: Return results that are file actions related to the + file indicated by this File ID + example: "1" + x-ms-summary: Return results that are file actions related to the + file indicated by this File ID + query_parent_id: + type: string + description: Return results that are file actions inside the parent + folder specified by this folder ID + example: "1" + x-ms-summary: Return results that are file actions inside the parent + folder specified by this folder ID + query_path: + type: string + description: Return results that are file actions related to this + path. + example: MyFile.txt + x-ms-summary: Return results that are file actions related to this + path. + query_folder: + type: string + description: Return results that are file actions related to files + or folders inside this folder path. + example: Folder + x-ms-summary: Return results that are file actions related to files + or folders inside this folder path. + query_src: + type: string + description: Return results that are file moves originating from + this path. + example: SrcFolder + x-ms-summary: Return results that are file moves originating from + this path. + query_destination: + type: string + description: Return results that are file moves with this path as + destination. + example: DestFolder + x-ms-summary: Return results that are file moves with this path + as destination. + query_ip: + type: string + description: Filter results by this IP address. + example: 127.0.0.1 + x-ms-summary: Filter results by this IP address. + query_username: + type: string + description: Filter results by this username. + example: jerry + x-ms-summary: Filter results by this username. + query_failure_type: + type: string + description: 'If searching for Histories about login failures, this + parameter restricts results to failures of this specific type. Valid + values: `expired_trial`, `account_overdue`, `locked_out`, `ip_mismatch`, + `password_mismatch`, `site_mismatch`, `username_not_found`, `none`, + `no_ftp_permission`, `no_web_permission`, `no_directory`, `errno_enoent`, + `no_sftp_permission`, `no_dav_permission`, `no_restapi_permission`, + `key_mismatch`, `region_mismatch`, `expired_access`, `desktop_ip_mismatch`, + `desktop_api_key_not_used_quickly_enough`, `disabled`, `country_mismatch`' + example: bad_password + x-ms-summary: 'If searching for Histories about login failures, + this parameter restricts results to failures of this specific + type. Valid values: `expired_trial`, `account_overdue`, `locked_out`, + `ip_mismatch`, `password_mismatch`, `site_mismatch`, `username_not_found`, + `none`, `no_ftp_permission`, `no_web_permission`, `no_directory`, + `errno_enoent`, `no_sftp_permission`, `no_dav_permission`, `no_restapi_permission`, + `key_mismatch`, `region_mismatch`, `expired_access`, `desktop_ip_mismatch`, + `desktop_api_key_not_used_quickly_enough`, `disabled`, `country_mismatch`' + query_target_id: + type: string + description: If searching for Histories about specific objects (such + as Users, or API Keys), this paremeter restricts results to objects + that match this ID. + example: "1" + x-ms-summary: If searching for Histories about specific objects + (such as Users, or API Keys), this paremeter restricts results + to objects that match this ID. + query_target_name: + type: string + description: If searching for Histories about Users, Groups or other + objects with names, this parameter restricts results to objects + with this name/username. + example: full + x-ms-summary: If searching for Histories about Users, Groups or + other objects with names, this parameter restricts results to + objects with this name/username. + query_target_permission: + type: string + description: If searching for Histories about Permisisons, this + parameter restricts results to permissions of this level. + example: full + x-ms-summary: If searching for Histories about Permisisons, this + parameter restricts results to permissions of this level. + query_target_user_id: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this user ID. + example: "1" + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this user ID. + query_target_username: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this username. + example: jerry + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this username. + query_target_platform: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys associated with this platform. + example: windows + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys associated with this platform. + query_target_permission_set: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys with this permission set. + example: desktop_app + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys with this permission set. + multipart/form-data: + schema: + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: Start date/time of export range. + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + x-ms-summary: End date/time of export range. + query_action: + type: string + description: 'Filter results by this this action type. Valid values: + `create`, `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, + `copy`, `user_create`, `user_update`, `user_destroy`, `group_create`, + `group_update`, `group_destroy`, `permission_create`, `permission_destroy`, + `api_key_create`, `api_key_update`, `api_key_destroy`' + example: read + x-ms-summary: 'Filter results by this this action type. Valid values: + `create`, `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, + `copy`, `user_create`, `user_update`, `user_destroy`, `group_create`, + `group_update`, `group_destroy`, `permission_create`, `permission_destroy`, + `api_key_create`, `api_key_update`, `api_key_destroy`' + query_interface: + type: string + description: 'Filter results by this this interface type. Valid + values: `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, + `dav`, `desktop`, `restapi`, `scim`, `office`, `mobile`' + example: ftp + x-ms-summary: 'Filter results by this this interface type. Valid + values: `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, + `dav`, `desktop`, `restapi`, `scim`, `office`, `mobile`' + query_user_id: + type: string + description: Return results that are actions performed by the user + indiciated by this User ID + example: "1" + x-ms-summary: Return results that are actions performed by the user + indiciated by this User ID + query_file_id: + type: string + description: Return results that are file actions related to the + file indicated by this File ID + example: "1" + x-ms-summary: Return results that are file actions related to the + file indicated by this File ID + query_parent_id: + type: string + description: Return results that are file actions inside the parent + folder specified by this folder ID + example: "1" + x-ms-summary: Return results that are file actions inside the parent + folder specified by this folder ID + query_path: + type: string + description: Return results that are file actions related to this + path. + example: MyFile.txt + x-ms-summary: Return results that are file actions related to this + path. + query_folder: + type: string + description: Return results that are file actions related to files + or folders inside this folder path. + example: Folder + x-ms-summary: Return results that are file actions related to files + or folders inside this folder path. + query_src: + type: string + description: Return results that are file moves originating from + this path. + example: SrcFolder + x-ms-summary: Return results that are file moves originating from + this path. + query_destination: + type: string + description: Return results that are file moves with this path as + destination. + example: DestFolder + x-ms-summary: Return results that are file moves with this path + as destination. + query_ip: + type: string + description: Filter results by this IP address. + example: 127.0.0.1 + x-ms-summary: Filter results by this IP address. + query_username: + type: string + description: Filter results by this username. + example: jerry + x-ms-summary: Filter results by this username. + query_failure_type: + type: string + description: 'If searching for Histories about login failures, this + parameter restricts results to failures of this specific type. Valid + values: `expired_trial`, `account_overdue`, `locked_out`, `ip_mismatch`, + `password_mismatch`, `site_mismatch`, `username_not_found`, `none`, + `no_ftp_permission`, `no_web_permission`, `no_directory`, `errno_enoent`, + `no_sftp_permission`, `no_dav_permission`, `no_restapi_permission`, + `key_mismatch`, `region_mismatch`, `expired_access`, `desktop_ip_mismatch`, + `desktop_api_key_not_used_quickly_enough`, `disabled`, `country_mismatch`' + example: bad_password + x-ms-summary: 'If searching for Histories about login failures, + this parameter restricts results to failures of this specific + type. Valid values: `expired_trial`, `account_overdue`, `locked_out`, + `ip_mismatch`, `password_mismatch`, `site_mismatch`, `username_not_found`, + `none`, `no_ftp_permission`, `no_web_permission`, `no_directory`, + `errno_enoent`, `no_sftp_permission`, `no_dav_permission`, `no_restapi_permission`, + `key_mismatch`, `region_mismatch`, `expired_access`, `desktop_ip_mismatch`, + `desktop_api_key_not_used_quickly_enough`, `disabled`, `country_mismatch`' + query_target_id: + type: string + description: If searching for Histories about specific objects (such + as Users, or API Keys), this paremeter restricts results to objects + that match this ID. + example: "1" + x-ms-summary: If searching for Histories about specific objects + (such as Users, or API Keys), this paremeter restricts results + to objects that match this ID. + query_target_name: + type: string + description: If searching for Histories about Users, Groups or other + objects with names, this parameter restricts results to objects + with this name/username. + example: full + x-ms-summary: If searching for Histories about Users, Groups or + other objects with names, this parameter restricts results to + objects with this name/username. + query_target_permission: + type: string + description: If searching for Histories about Permisisons, this + parameter restricts results to permissions of this level. + example: full + x-ms-summary: If searching for Histories about Permisisons, this + parameter restricts results to permissions of this level. + query_target_user_id: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this user ID. + example: "1" + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this user ID. + query_target_username: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this username. + example: jerry + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys created by/for this username. + query_target_platform: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys associated with this platform. + example: windows + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys associated with this platform. + query_target_permission_set: + type: string + description: If searching for Histories about API keys, this parameter + restricts results to API keys with this permission set. + example: desktop_app + x-ms-summary: If searching for Histories about API keys, this parameter + restricts results to API keys with this permission set. + responses: + 201: + description: The HistoryExports object. + content: + application/json: + schema: + $ref: '#/components/schemas/HistoryExportEntity' + x-ms-summary: The HistoryExports object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - readonly_ok + /history_exports/{id}: + get: + tags: + - history_exports + summary: Show History Export + description: Show History Export + operationId: GetHistoryExportsId + parameters: + - name: id + in: path + description: History Export ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: History Export ID. + x-ms-summary: History Export ID. + responses: + 200: + description: The HistoryExports object. + content: + application/json: + schema: + $ref: '#/components/schemas/HistoryExportEntity' + x-ms-summary: The HistoryExports object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - readonly_ok + /history_export_results: + get: + tags: + - history_export_results + summary: List History Export Results + description: List History Export Results + operationId: GetHistoryExportResults + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: history_export_id + in: query + description: ID of the associated history export. + required: true + schema: + type: integer + format: int32 + x-ms-summary: ID of the associated history export. + x-ms-summary: ID of the associated history export. + responses: + 200: + description: A list of HistoryExportResults objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/HistoryExportResultEntity' + x-ms-summary: A list of HistoryExportResults objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /inbox_recipients: + get: + tags: + - inbox_recipients + summary: List Inbox Recipients + description: List Inbox Recipients + operationId: GetInboxRecipients + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `has_registrations`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `has_registrations`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `has_registrations`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `has_registrations`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `has_registrations`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `has_registrations`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `has_registrations`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `has_registrations`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `has_registrations`. + - name: inbox_id + in: query + description: List recipients for the inbox with this ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: List recipients for the inbox with this ID. + x-ms-summary: List recipients for the inbox with this ID. + responses: + 200: + description: A list of InboxRecipients objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/InboxRecipientEntity' + x-ms-summary: A list of InboxRecipients objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - inbox_recipients + summary: Create Inbox Recipient + description: Create Inbox Recipient + operationId: PostInboxRecipients + requestBody: + content: + application/json: + schema: + required: + - inbox_id + - recipient + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + inbox_id: + type: integer + description: Inbox to share. + format: int32 + x-ms-summary: Inbox to share. + recipient: + type: string + description: Email address to share this inbox with. + example: johndoe@gmail.com + x-ms-summary: Email address to share this inbox with. + name: + type: string + description: Name of recipient. + example: John Smith + x-ms-summary: Name of recipient. + company: + type: string + description: Company of recipient. + example: Acme Ltd + x-ms-summary: Company of recipient. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + share_after_create: + type: boolean + description: Set to true to share the link with the recipient upon + creation. + x-ms-summary: Set to true to share the link with the recipient upon + creation. + application/x-www-form-urlencoded: + schema: + required: + - inbox_id + - recipient + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + inbox_id: + type: integer + description: Inbox to share. + format: int32 + x-ms-summary: Inbox to share. + recipient: + type: string + description: Email address to share this inbox with. + example: johndoe@gmail.com + x-ms-summary: Email address to share this inbox with. + name: + type: string + description: Name of recipient. + example: John Smith + x-ms-summary: Name of recipient. + company: + type: string + description: Company of recipient. + example: Acme Ltd + x-ms-summary: Company of recipient. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + share_after_create: + type: boolean + description: Set to true to share the link with the recipient upon + creation. + x-ms-summary: Set to true to share the link with the recipient upon + creation. + multipart/form-data: + schema: + required: + - inbox_id + - recipient + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + inbox_id: + type: integer + description: Inbox to share. + format: int32 + x-ms-summary: Inbox to share. + recipient: + type: string + description: Email address to share this inbox with. + example: johndoe@gmail.com + x-ms-summary: Email address to share this inbox with. + name: + type: string + description: Name of recipient. + example: John Smith + x-ms-summary: Name of recipient. + company: + type: string + description: Company of recipient. + example: Acme Ltd + x-ms-summary: Company of recipient. + note: + type: string + description: Note to include in email. + example: Just a note. + x-ms-summary: Note to include in email. + share_after_create: + type: boolean + description: Set to true to share the link with the recipient upon + creation. + x-ms-summary: Set to true to share the link with the recipient upon + creation. + required: true + responses: + 201: + description: The InboxRecipients object. + content: + application/json: + schema: + $ref: '#/components/schemas/InboxRecipientEntity' + x-ms-summary: The InboxRecipients object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /inbox_registrations: + get: + tags: + - inbox_registrations + summary: List Inbox Registrations + description: List Inbox Registrations + operationId: GetInboxRegistrations + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: folder_behavior_id + in: query + description: ID of the associated Inbox. + required: true + schema: + type: integer + format: int32 + x-ms-summary: ID of the associated Inbox. + x-ms-summary: ID of the associated Inbox. + responses: + 200: + description: A list of InboxRegistrations objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/InboxRegistrationEntity' + x-ms-summary: A list of InboxRegistrations objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /inbox_uploads: + get: + tags: + - inbox_uploads + summary: List Inbox Uploads + description: List Inbox Uploads + operationId: GetInboxUploads + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `created_at`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `created_at`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `created_at`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `created_at`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `created_at`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `created_at`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `created_at`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `created_at`. + - name: inbox_registration_id + in: query + description: InboxRegistration ID + schema: + type: integer + format: int32 + x-ms-summary: InboxRegistration ID + x-ms-summary: InboxRegistration ID + - name: inbox_id + in: query + description: Inbox ID + schema: + type: integer + format: int32 + x-ms-summary: Inbox ID + x-ms-summary: Inbox ID + responses: + 200: + description: A list of InboxUploads objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/InboxUploadEntity' + x-ms-summary: A list of InboxUploads objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin + /invoices/{id}: + get: + tags: + - invoices + summary: Show Invoice + description: Show Invoice + operationId: GetInvoicesId + parameters: + - name: id + in: path + description: Invoice ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Invoice ID. + x-ms-summary: Invoice ID. + responses: + 200: + description: The Invoices object. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountLineItemEntity' + x-ms-summary: The Invoices object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - overdue_ok + - billing + /invoices: + get: + tags: + - invoices + summary: List Invoices + description: List Invoices + operationId: GetInvoices + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of Invoices objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AccountLineItemEntity' + x-ms-summary: A list of Invoices objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - overdue_ok + - billing + /ip_addresses/reserved: + get: + tags: + - ip_addresses + summary: List all possible public IP addresses + description: List all possible public IP addresses + operationId: GetIpAddressesReserved + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of IpAddresses objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PublicIpAddressEntity' + x-ms-summary: A list of IpAddresses objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - none + /ip_addresses: + get: + tags: + - ip_addresses + summary: List IP Addresses associated with the current site + description: List IP Addresses associated with the current site + operationId: GetIpAddresses + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of IpAddresses objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/IpAddressEntity' + x-ms-summary: A list of IpAddresses objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + - overdue_ok + x-path_aliases: + - site/ip_addresses + /locks/{lockPath}: + get: + tags: + - locks + summary: List Locks by path + description: List Locks by path + operationId: LockListForPath + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: lockPath + in: path + description: Path to operate on. + required: true + schema: + type: string + x-ms-summary: Path to operate on. + x-ms-summary: Path to operate on. + - name: include_children + in: query + description: Include locks from children objects? + schema: + type: boolean + x-ms-summary: Include locks from children objects? + x-ms-summary: Include locks from children objects? + responses: + 200: + description: A list of Locks objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/LockEntity' + x-ms-summary: A list of Locks objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + post: + tags: + - locks + summary: Create Lock + description: Create Lock + operationId: PostLocksPath + parameters: + - name: lockPath + in: path + description: Path + required: true + schema: + type: string + x-ms-summary: Path + x-ms-summary: Path + requestBody: + content: + application/json: + schema: + properties: + allow_access_by_any_user: + type: boolean + description: Allow lock to be updated by any user? + x-ms-summary: Allow lock to be updated by any user? + exclusive: + type: boolean + description: Is lock exclusive? + x-ms-summary: Is lock exclusive? + recursive: + type: string + description: Does lock apply to subfolders? + x-ms-summary: Does lock apply to subfolders? + timeout: + type: integer + description: Lock timeout length + format: int32 + x-ms-summary: Lock timeout length + application/x-www-form-urlencoded: + schema: + properties: + allow_access_by_any_user: + type: boolean + description: Allow lock to be updated by any user? + x-ms-summary: Allow lock to be updated by any user? + exclusive: + type: boolean + description: Is lock exclusive? + x-ms-summary: Is lock exclusive? + recursive: + type: string + description: Does lock apply to subfolders? + x-ms-summary: Does lock apply to subfolders? + timeout: + type: integer + description: Lock timeout length + format: int32 + x-ms-summary: Lock timeout length + multipart/form-data: + schema: + properties: + allow_access_by_any_user: + type: boolean + description: Allow lock to be updated by any user? + x-ms-summary: Allow lock to be updated by any user? + exclusive: + type: boolean + description: Is lock exclusive? + x-ms-summary: Is lock exclusive? + recursive: + type: string + description: Does lock apply to subfolders? + x-ms-summary: Does lock apply to subfolders? + timeout: + type: integer + description: Lock timeout length + format: int32 + x-ms-summary: Lock timeout length + responses: + 201: + description: The Locks object. + content: + application/json: + schema: + $ref: '#/components/schemas/LockEntity' + x-ms-summary: The Locks object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + delete: + tags: + - locks + summary: Delete Lock + description: Delete Lock + operationId: DeleteLocksPath + parameters: + - name: lockPath + in: path + description: Path + required: true + schema: + type: string + x-ms-summary: Path + x-ms-summary: Path + - name: token + in: query + description: Lock token + required: true + schema: + type: string + x-ms-summary: Lock token + x-ms-summary: Lock token + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - native_app + - office_integration + /messages/{id}: + get: + tags: + - messages + summary: Show Message + description: Show Message + operationId: GetMessagesId + parameters: + - name: id + in: path + description: Message ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message ID. + x-ms-summary: Message ID. + responses: + 200: + description: The Messages object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageEntity' + x-ms-summary: The Messages object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - messages + summary: Delete Message + description: Delete Message + operationId: DeleteMessagesId + parameters: + - name: id + in: path + description: Message ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message ID. + x-ms-summary: Message ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - messages + summary: Update Message + description: Update Message + operationId: PatchMessagesId + parameters: + - name: id + in: path + description: Message ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message ID. + x-ms-summary: Message ID. + requestBody: + content: + application/json: + schema: + required: + - body + - project_id + - subject + properties: + project_id: + type: integer + description: Project to which the message should be attached. + format: int32 + x-ms-summary: Project to which the message should be attached. + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + x-ms-summary: Message subject. + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + x-ms-summary: Message body. + application/x-www-form-urlencoded: + schema: + required: + - body + - project_id + - subject + properties: + project_id: + type: integer + description: Project to which the message should be attached. + format: int32 + x-ms-summary: Project to which the message should be attached. + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + x-ms-summary: Message subject. + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + x-ms-summary: Message body. + multipart/form-data: + schema: + required: + - body + - project_id + - subject + properties: + project_id: + type: integer + description: Project to which the message should be attached. + format: int32 + x-ms-summary: Project to which the message should be attached. + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + x-ms-summary: Message subject. + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + x-ms-summary: Message body. + required: true + responses: + 200: + description: The Messages object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageEntity' + x-ms-summary: The Messages object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /messages: + get: + tags: + - messages + summary: List Messages + description: List Messages + operationId: GetMessages + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: project_id + in: query + description: Project for which to return messages. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Project for which to return messages. + x-ms-summary: Project for which to return messages. + responses: + 200: + description: A list of Messages objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessageEntity' + x-ms-summary: A list of Messages objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - messages + summary: Create Message + description: Create Message + operationId: PostMessages + requestBody: + content: + application/json: + schema: + required: + - body + - project_id + - subject + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + project_id: + type: integer + description: Project to which the message should be attached. + format: int32 + x-ms-summary: Project to which the message should be attached. + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + x-ms-summary: Message subject. + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + x-ms-summary: Message body. + application/x-www-form-urlencoded: + schema: + required: + - body + - project_id + - subject + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + project_id: + type: integer + description: Project to which the message should be attached. + format: int32 + x-ms-summary: Project to which the message should be attached. + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + x-ms-summary: Message subject. + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + x-ms-summary: Message body. + multipart/form-data: + schema: + required: + - body + - project_id + - subject + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + project_id: + type: integer + description: Project to which the message should be attached. + format: int32 + x-ms-summary: Project to which the message should be attached. + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + x-ms-summary: Message subject. + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + x-ms-summary: Message body. + required: true + responses: + 201: + description: The Messages object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageEntity' + x-ms-summary: The Messages object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /message_comments/{id}: + get: + tags: + - message_comments + summary: Show Message Comment + description: Show Message Comment + operationId: GetMessageCommentsId + parameters: + - name: id + in: path + description: Message Comment ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Comment ID. + x-ms-summary: Message Comment ID. + responses: + 200: + description: The MessageComments object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageCommentEntity' + x-ms-summary: The MessageComments object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - message_comments + summary: Delete Message Comment + description: Delete Message Comment + operationId: DeleteMessageCommentsId + parameters: + - name: id + in: path + description: Message Comment ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Comment ID. + x-ms-summary: Message Comment ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - message_comments + summary: Update Message Comment + description: Update Message Comment + operationId: PatchMessageCommentsId + parameters: + - name: id + in: path + description: Message Comment ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Comment ID. + x-ms-summary: Message Comment ID. + requestBody: + content: + application/json: + schema: + required: + - body + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + application/x-www-form-urlencoded: + schema: + required: + - body + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + multipart/form-data: + schema: + required: + - body + properties: + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + required: true + responses: + 200: + description: The MessageComments object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageCommentEntity' + x-ms-summary: The MessageComments object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /message_comments: + get: + tags: + - message_comments + summary: List Message Comments + description: List Message Comments + operationId: GetMessageComments + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: message_id + in: query + description: Message comment to return comments for. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message comment to return comments for. + x-ms-summary: Message comment to return comments for. + responses: + 200: + description: A list of MessageComments objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessageCommentEntity' + x-ms-summary: A list of MessageComments objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - message_comments + summary: Create Message Comment + description: Create Message Comment + operationId: PostMessageComments + requestBody: + content: + application/json: + schema: + required: + - body + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + application/x-www-form-urlencoded: + schema: + required: + - body + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + multipart/form-data: + schema: + required: + - body + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + body: + type: string + description: Comment body. + x-ms-summary: Comment body. + required: true + responses: + 201: + description: The MessageComments object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageCommentEntity' + x-ms-summary: The MessageComments object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /message_comment_reactions/{id}: + get: + tags: + - message_comment_reactions + summary: Show Message Comment Reaction + description: Show Message Comment Reaction + operationId: GetMessageCommentReactionsId + parameters: + - name: id + in: path + description: Message Comment Reaction ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Comment Reaction ID. + x-ms-summary: Message Comment Reaction ID. + responses: + 200: + description: The MessageCommentReactions object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageCommentReactionEntity' + x-ms-summary: The MessageCommentReactions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - message_comment_reactions + summary: Delete Message Comment Reaction + description: Delete Message Comment Reaction + operationId: DeleteMessageCommentReactionsId + parameters: + - name: id + in: path + description: Message Comment Reaction ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Comment Reaction ID. + x-ms-summary: Message Comment Reaction ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /message_comment_reactions: + get: + tags: + - message_comment_reactions + summary: List Message Comment Reactions + description: List Message Comment Reactions + operationId: GetMessageCommentReactions + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: message_comment_id + in: query + description: Message comment to return reactions for. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message comment to return reactions for. + x-ms-summary: Message comment to return reactions for. + responses: + 200: + description: A list of MessageCommentReactions objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessageCommentReactionEntity' + x-ms-summary: A list of MessageCommentReactions objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - message_comment_reactions + summary: Create Message Comment Reaction + description: Create Message Comment Reaction + operationId: PostMessageCommentReactions + requestBody: + content: + application/json: + schema: + required: + - emoji + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + application/x-www-form-urlencoded: + schema: + required: + - emoji + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + multipart/form-data: + schema: + required: + - emoji + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + required: true + responses: + 201: + description: The MessageCommentReactions object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageCommentReactionEntity' + x-ms-summary: The MessageCommentReactions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /message_reactions/{id}: + get: + tags: + - message_reactions + summary: Show Message Reaction + description: Show Message Reaction + operationId: GetMessageReactionsId + parameters: + - name: id + in: path + description: Message Reaction ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Reaction ID. + x-ms-summary: Message Reaction ID. + responses: + 200: + description: The MessageReactions object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageReactionEntity' + x-ms-summary: The MessageReactions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - message_reactions + summary: Delete Message Reaction + description: Delete Message Reaction + operationId: DeleteMessageReactionsId + parameters: + - name: id + in: path + description: Message Reaction ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message Reaction ID. + x-ms-summary: Message Reaction ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /message_reactions: + get: + tags: + - message_reactions + summary: List Message Reactions + description: List Message Reactions + operationId: GetMessageReactions + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: message_id + in: query + description: Message to return reactions for. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Message to return reactions for. + x-ms-summary: Message to return reactions for. + responses: + 200: + description: A list of MessageReactions objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessageReactionEntity' + x-ms-summary: A list of MessageReactions objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - message_reactions + summary: Create Message Reaction + description: Create Message Reaction + operationId: PostMessageReactions + requestBody: + content: + application/json: + schema: + required: + - emoji + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + application/x-www-form-urlencoded: + schema: + required: + - emoji + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + multipart/form-data: + schema: + required: + - emoji + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + emoji: + type: string + description: Emoji to react with. + x-ms-summary: Emoji to react with. + required: true + responses: + 201: + description: The MessageReactions object. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageReactionEntity' + x-ms-summary: The MessageReactions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /notifications/{id}: + get: + tags: + - notifications + summary: Show Notification + description: Show Notification + operationId: GetNotificationsId + parameters: + - name: id + in: path + description: Notification ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Notification ID. + x-ms-summary: Notification ID. + responses: + 200: + description: The Notifications object. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEntity' + x-ms-summary: The Notifications object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - notifications + summary: Delete Notification + description: Delete Notification + operationId: DeleteNotificationsId + parameters: + - name: id + in: path + description: Notification ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Notification ID. + x-ms-summary: Notification ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + patch: + tags: + - notifications + summary: Update Notification + description: Update Notification + operationId: PatchNotificationsId + parameters: + - name: id + in: path + description: Notification ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Notification ID. + x-ms-summary: Notification ID. + requestBody: + content: + application/json: + schema: + properties: + notify_on_copy: + type: boolean + description: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + x-ms-summary: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + notify_user_actions: + type: boolean + description: If `true` actions initiated by the user will still + result in a notification + x-ms-summary: If `true` actions initiated by the user will still + result in a notification + recursive: + type: boolean + description: If `true`, enable notifications for each subfolder + in this path + x-ms-summary: If `true`, enable notifications for each subfolder + in this path + send_interval: + type: string + description: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + example: daily + x-ms-summary: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + application/x-www-form-urlencoded: + schema: + properties: + notify_on_copy: + type: boolean + description: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + x-ms-summary: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + notify_user_actions: + type: boolean + description: If `true` actions initiated by the user will still + result in a notification + x-ms-summary: If `true` actions initiated by the user will still + result in a notification + recursive: + type: boolean + description: If `true`, enable notifications for each subfolder + in this path + x-ms-summary: If `true`, enable notifications for each subfolder + in this path + send_interval: + type: string + description: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + example: daily + x-ms-summary: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + multipart/form-data: + schema: + properties: + notify_on_copy: + type: boolean + description: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + x-ms-summary: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + notify_user_actions: + type: boolean + description: If `true` actions initiated by the user will still + result in a notification + x-ms-summary: If `true` actions initiated by the user will still + result in a notification + recursive: + type: boolean + description: If `true`, enable notifications for each subfolder + in this path + x-ms-summary: If `true`, enable notifications for each subfolder + in this path + send_interval: + type: string + description: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + example: daily + x-ms-summary: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + responses: + 200: + description: The Notifications object. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEntity' + x-ms-summary: The Notifications object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /notifications: + get: + tags: + - notifications + summary: List Notifications + description: List Notifications + operationId: GetNotifications + parameters: + - name: user_id + in: query + description: 'DEPRECATED: Show notifications for this User ID. Use `filter[user_id]` + instead.' + schema: + type: integer + format: int32 + x-ms-summary: 'DEPRECATED: Show notifications for this User ID. Use `filter[user_id]` + instead.' + x-ms-summary: 'DEPRECATED: Show notifications for this User ID. Use `filter[user_id]` + instead.' + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `path`, + `user_id` or `group_id`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `path`, `user_id` or `group_id`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `path`, `user_id` or `group_id`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `group_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `user_id`, `group_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `group_id` or `path`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `user_id`, `group_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `user_id`, `group_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `user_id`, `group_id` or `path`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `user_id`, `group_id` + or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `user_id`, `group_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `user_id`, `group_id` + or `path`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `group_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `user_id`, `group_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `user_id`, `group_id` or `path`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `user_id`, `group_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `user_id`, `group_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `user_id`, `group_id` or `path`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `user_id`, `group_id` or + `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `user_id`, `group_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `user_id`, `group_id` or + `path`. + - name: group_id + in: query + description: 'DEPRECATED: Show notifications for this Group ID. Use `filter[group_id]` + instead.' + schema: + type: integer + format: int32 + x-ms-summary: 'DEPRECATED: Show notifications for this Group ID. Use `filter[group_id]` + instead.' + x-ms-summary: 'DEPRECATED: Show notifications for this Group ID. Use `filter[group_id]` + instead.' + - name: path + in: query + description: Show notifications for this Path. + schema: + type: string + x-ms-summary: Show notifications for this Path. + x-ms-summary: Show notifications for this Path. + - name: include_ancestors + in: query + description: If `include_ancestors` is `true` and `path` is specified, include + notifications for any parent paths. Ignored if `path` is not specified. + schema: + type: boolean + x-ms-summary: If `include_ancestors` is `true` and `path` is specified, + include notifications for any parent paths. Ignored if `path` is not specified. + x-ms-summary: If `include_ancestors` is `true` and `path` is specified, include + notifications for any parent paths. Ignored if `path` is not specified. + responses: + 200: + description: A list of Notifications objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationEntity' + x-ms-summary: A list of Notifications objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + post: + tags: + - notifications + summary: Create Notification + description: Create Notification + operationId: PostNotifications + requestBody: + content: + application/json: + schema: + properties: + user_id: + type: integer + description: The id of the user to notify. Provide `user_id`, `username` + or `group_id`. + format: int32 + x-ms-summary: The id of the user to notify. Provide `user_id`, `username` + or `group_id`. + notify_on_copy: + type: boolean + description: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + x-ms-summary: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + notify_user_actions: + type: boolean + description: If `true` actions initiated by the user will still + result in a notification + x-ms-summary: If `true` actions initiated by the user will still + result in a notification + recursive: + type: boolean + description: If `true`, enable notifications for each subfolder + in this path + x-ms-summary: If `true`, enable notifications for each subfolder + in this path + send_interval: + type: string + description: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + example: daily + x-ms-summary: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + group_id: + type: integer + description: The ID of the group to notify. Provide `user_id`, + `username` or `group_id`. + format: int32 + x-ms-summary: The ID of the group to notify. Provide `user_id`, + `username` or `group_id`. + path: + type: string + description: Path + x-ms-summary: Path + username: + type: string + description: The username of the user to notify. Provide `user_id`, + `username` or `group_id`. + x-ms-summary: The username of the user to notify. Provide `user_id`, + `username` or `group_id`. + application/x-www-form-urlencoded: + schema: + properties: + user_id: + type: integer + description: The id of the user to notify. Provide `user_id`, `username` + or `group_id`. + format: int32 + x-ms-summary: The id of the user to notify. Provide `user_id`, `username` + or `group_id`. + notify_on_copy: + type: boolean + description: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + x-ms-summary: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + notify_user_actions: + type: boolean + description: If `true` actions initiated by the user will still + result in a notification + x-ms-summary: If `true` actions initiated by the user will still + result in a notification + recursive: + type: boolean + description: If `true`, enable notifications for each subfolder + in this path + x-ms-summary: If `true`, enable notifications for each subfolder + in this path + send_interval: + type: string + description: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + example: daily + x-ms-summary: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + group_id: + type: integer + description: The ID of the group to notify. Provide `user_id`, + `username` or `group_id`. + format: int32 + x-ms-summary: The ID of the group to notify. Provide `user_id`, + `username` or `group_id`. + path: + type: string + description: Path + x-ms-summary: Path + username: + type: string + description: The username of the user to notify. Provide `user_id`, + `username` or `group_id`. + x-ms-summary: The username of the user to notify. Provide `user_id`, + `username` or `group_id`. + multipart/form-data: + schema: + properties: + user_id: + type: integer + description: The id of the user to notify. Provide `user_id`, `username` + or `group_id`. + format: int32 + x-ms-summary: The id of the user to notify. Provide `user_id`, `username` + or `group_id`. + notify_on_copy: + type: boolean + description: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + x-ms-summary: If `true`, copying or moving resources into this path + will trigger a notification, in addition to just uploads. + notify_user_actions: + type: boolean + description: If `true` actions initiated by the user will still + result in a notification + x-ms-summary: If `true` actions initiated by the user will still + result in a notification + recursive: + type: boolean + description: If `true`, enable notifications for each subfolder + in this path + x-ms-summary: If `true`, enable notifications for each subfolder + in this path + send_interval: + type: string + description: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + example: daily + x-ms-summary: The time interval that notifications are aggregated + by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`. + group_id: + type: integer + description: The ID of the group to notify. Provide `user_id`, + `username` or `group_id`. + format: int32 + x-ms-summary: The ID of the group to notify. Provide `user_id`, + `username` or `group_id`. + path: + type: string + description: Path + x-ms-summary: Path + username: + type: string + description: The username of the user to notify. Provide `user_id`, + `username` or `group_id`. + x-ms-summary: The username of the user to notify. Provide `user_id`, + `username` or `group_id`. + responses: + 201: + description: The Notifications object. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEntity' + x-ms-summary: The Notifications object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /payments/{id}: + get: + tags: + - payments + summary: Show Payment + description: Show Payment + operationId: GetPaymentsId + parameters: + - name: id + in: path + description: Payment ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Payment ID. + x-ms-summary: Payment ID. + responses: + 200: + description: The Payments object. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountLineItemEntity' + x-ms-summary: The Payments object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - overdue_ok + - billing + /payments: + get: + tags: + - payments + summary: List Payments + description: List Payments + operationId: GetPayments + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of Payments objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AccountLineItemEntity' + x-ms-summary: A list of Payments objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - overdue_ok + - billing + /permissions/{id}: + delete: + tags: + - permissions + summary: Delete Permission + description: Delete Permission + operationId: DeletePermissionsId + parameters: + - name: id + in: path + description: Permission ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Permission ID. + x-ms-summary: Permission ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /permissions: + get: + tags: + - permissions + summary: List Permissions + description: List Permissions + operationId: GetPermissions + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `group_id`, + `path`, `user_id` or `permission`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `group_id`, `path`, `user_id` or `permission`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `group_id`, `path`, `user_id` or `permission`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `group_id`, `user_id` or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `group_id`, `user_id` or `path`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `group_id`, `user_id` or + `path`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `group_id`, `user_id` + or `path`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `group_id`, `user_id` or + `path`. + # - name: path + # in: query + # description: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + # schema: + # type: string + # x-ms-summary: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + # x-ms-summary: 'DEPRECATED: Permission path. If provided, will scope permissions + # to this path. Use `filter[path]` instead.' + - name: group_id + in: query + description: 'DEPRECATED: Group ID. If provided, will scope permissions to + this group. Use `filter[group_id]` instead.' + schema: + type: string + x-ms-summary: 'DEPRECATED: Group ID. If provided, will scope permissions + to this group. Use `filter[group_id]` instead.`' + x-ms-summary: 'DEPRECATED: Group ID. If provided, will scope permissions + to this group. Use `filter[group_id]` instead.`' + - name: user_id + in: query + description: 'DEPRECATED: User ID. If provided, will scope permissions to + this user. Use `filter[user_id]` instead.' + schema: + type: string + x-ms-summary: 'DEPRECATED: User ID. If provided, will scope permissions + to this user. Use `filter[user_id]` instead.`' + x-ms-summary: 'DEPRECATED: User ID. If provided, will scope permissions to + this user. Use `filter[user_id]` instead.`' + - name: include_groups + in: query + description: If searching by user or group, also include user's permissions + that are inherited from its groups? + schema: + type: boolean + x-ms-summary: If searching by user or group, also include user's permissions + that are inherited from its groups? + x-ms-summary: If searching by user or group, also include user's permissions + that are inherited from its groups? + responses: + 200: + description: A list of Permissions objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PermissionEntity' + x-ms-summary: A list of Permissions objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - groups/:group_id/permissions + - users/:user_id/permissions + post: + tags: + - permissions + summary: Create Permission + description: Create Permission + operationId: PostPermissions + requestBody: + content: + application/json: + schema: + properties: + group_id: + type: integer + description: Group ID + format: int32 + x-ms-summary: Group ID + path: + type: string + description: Folder path + x-ms-summary: Folder path + permission: + type: string + description: ' Permission type. Can be `admin`, `full`, `readonly`, + `writeonly`, `list`, or `history`' + x-ms-summary: ' Permission type. Can be `admin`, `full`, `readonly`, + `writeonly`, `list`, or `history`' + recursive: + type: boolean + description: Apply to subfolders recursively? + x-ms-summary: Apply to subfolders recursively? + user_id: + type: integer + description: User ID. Provide `username` or `user_id` + format: int32 + x-ms-summary: User ID. Provide `username` or `user_id` + username: + type: string + description: User username. Provide `username` or `user_id` + x-ms-summary: User username. Provide `username` or `user_id` + application/x-www-form-urlencoded: + schema: + properties: + group_id: + type: integer + description: Group ID + format: int32 + x-ms-summary: Group ID + path: + type: string + description: Folder path + x-ms-summary: Folder path + permission: + type: string + description: ' Permission type. Can be `admin`, `full`, `readonly`, + `writeonly`, `list`, or `history`' + x-ms-summary: ' Permission type. Can be `admin`, `full`, `readonly`, + `writeonly`, `list`, or `history`' + recursive: + type: boolean + description: Apply to subfolders recursively? + x-ms-summary: Apply to subfolders recursively? + user_id: + type: integer + description: User ID. Provide `username` or `user_id` + format: int32 + x-ms-summary: User ID. Provide `username` or `user_id` + username: + type: string + description: User username. Provide `username` or `user_id` + x-ms-summary: User username. Provide `username` or `user_id` + multipart/form-data: + schema: + properties: + group_id: + type: integer + description: Group ID + format: int32 + x-ms-summary: Group ID + path: + type: string + description: Folder path + x-ms-summary: Folder path + permission: + type: string + description: ' Permission type. Can be `admin`, `full`, `readonly`, + `writeonly`, `list`, or `history`' + x-ms-summary: ' Permission type. Can be `admin`, `full`, `readonly`, + `writeonly`, `list`, or `history`' + recursive: + type: boolean + description: Apply to subfolders recursively? + x-ms-summary: Apply to subfolders recursively? + user_id: + type: integer + description: User ID. Provide `username` or `user_id` + format: int32 + x-ms-summary: User ID. Provide `username` or `user_id` + username: + type: string + description: User username. Provide `username` or `user_id` + x-ms-summary: User username. Provide `username` or `user_id` + responses: + 201: + description: The Permissions object. + content: + application/json: + schema: + $ref: '#/components/schemas/PermissionEntity' + x-ms-summary: The Permissions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /projects/{id}: + get: + tags: + - projects + summary: Show Project + description: Show Project + operationId: GetProjectsId + parameters: + - name: id + in: path + description: Project ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Project ID. + x-ms-summary: Project ID. + responses: + 200: + description: The Projects object. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectEntity' + x-ms-summary: The Projects object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + delete: + tags: + - projects + summary: Delete Project + description: Delete Project + operationId: DeleteProjectsId + parameters: + - name: id + in: path + description: Project ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Project ID. + x-ms-summary: Project ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + patch: + tags: + - projects + summary: Update Project + description: Update Project + operationId: PatchProjectsId + parameters: + - name: id + in: path + description: Project ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Project ID. + x-ms-summary: Project ID. + requestBody: + content: + application/json: + schema: + required: + - global_access + properties: + global_access: + type: string + description: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + x-ms-summary: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + application/x-www-form-urlencoded: + schema: + required: + - global_access + properties: + global_access: + type: string + description: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + x-ms-summary: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + multipart/form-data: + schema: + required: + - global_access + properties: + global_access: + type: string + description: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + x-ms-summary: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + required: true + responses: + 200: + description: The Projects object. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectEntity' + x-ms-summary: The Projects object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /projects: + get: + tags: + - projects + summary: List Projects + description: List Projects + operationId: GetProjects + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of Projects objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ProjectEntity' + x-ms-summary: A list of Projects objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + post: + tags: + - projects + summary: Create Project + description: Create Project + operationId: PostProjects + requestBody: + content: + application/json: + schema: + required: + - global_access + properties: + global_access: + type: string + description: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + x-ms-summary: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + application/x-www-form-urlencoded: + schema: + required: + - global_access + properties: + global_access: + type: string + description: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + x-ms-summary: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + multipart/form-data: + schema: + required: + - global_access + properties: + global_access: + type: string + description: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + x-ms-summary: 'Global permissions. Can be: `none`, `anyone_with_read`, + `anyone_with_full`.' + required: true + responses: + 201: + description: The Projects object. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectEntity' + x-ms-summary: The Projects object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /public_keys/{id}: + get: + tags: + - public_keys + summary: Show Public Key + description: Show Public Key + operationId: GetPublicKeysId + parameters: + - name: id + in: path + description: Public Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Public Key ID. + x-ms-summary: Public Key ID. + responses: + 200: + description: The PublicKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: The PublicKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + delete: + tags: + - public_keys + summary: Delete Public Key + description: Delete Public Key + operationId: DeletePublicKeysId + parameters: + - name: id + in: path + description: Public Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Public Key ID. + x-ms-summary: Public Key ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + patch: + tags: + - public_keys + summary: Update Public Key + description: Update Public Key + operationId: PatchPublicKeysId + parameters: + - name: id + in: path + description: Public Key ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Public Key ID. + x-ms-summary: Public Key ID. + requestBody: + content: + application/json: + schema: + required: + - title + properties: + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + application/x-www-form-urlencoded: + schema: + required: + - title + properties: + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + multipart/form-data: + schema: + required: + - title + properties: + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + required: true + responses: + 200: + description: The PublicKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: The PublicKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + /public_keys: + get: + tags: + - public_keys + summary: List Public Keys + description: List Public Keys + operationId: GetPublicKeys + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of PublicKeys objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: A list of PublicKeys objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/public_keys + - users/:user_id/public_keys + post: + tags: + - public_keys + summary: Create Public Key + description: Create Public Key + operationId: PostPublicKeys + requestBody: + content: + application/json: + schema: + required: + - public_key + - title + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + application/x-www-form-urlencoded: + schema: + required: + - public_key + - title + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + multipart/form-data: + schema: + required: + - public_key + - title + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current + session's user. + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current + session's user. + title: + type: string + description: Internal reference for key. + example: My Main Key + x-ms-summary: Internal reference for key. + public_key: + type: string + description: Actual contents of SSH key. + x-ms-summary: Actual contents of SSH key. + required: true + responses: + 201: + description: The PublicKeys object. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicKeyEntity' + x-ms-summary: The PublicKeys object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - user/public_keys + - users/:user_id/public_keys + /remote_servers: + get: + tags: + - remote_servers + summary: List Remote Servers + description: List Remote Servers + operationId: GetRemoteServers + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of RemoteServers objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RemoteServerEntity' + x-ms-summary: A list of RemoteServers objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + post: + tags: + - remote_servers + summary: Create Remote Server + description: Create Remote Server + operationId: PostRemoteServers + requestBody: + content: + application/json: + schema: + properties: + aws_access_key: + type: string + description: AWS Access Key. + x-ms-summary: AWS Access Key. + aws_secret_key: + type: string + description: AWS secret key. + x-ms-summary: AWS secret key. + password: + type: string + description: Password if needed. + x-ms-summary: Password if needed. + private_key: + type: string + description: Private key if needed. + x-ms-summary: Private key if needed. + ssl_certificate: + type: string + description: SSL client certificate. + x-ms-summary: SSL client certificate. + google_cloud_storage_credentials_json: + type: string + description: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + x-ms-summary: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + wasabi_access_key: + type: string + description: Wasabi access key. + x-ms-summary: Wasabi access key. + wasabi_secret_key: + type: string + description: Wasabi secret key. + x-ms-summary: Wasabi secret key. + backblaze_b2_key_id: + type: string + description: Backblaze B2 Cloud Storage keyID. + x-ms-summary: Backblaze B2 Cloud Storage keyID. + backblaze_b2_application_key: + type: string + description: Backblaze B2 Cloud Storage applicationKey. + x-ms-summary: Backblaze B2 Cloud Storage applicationKey. + rackspace_api_key: + type: string + description: Rackspace API key from the Rackspace Cloud Control + Panel. + x-ms-summary: Rackspace API key from the Rackspace Cloud Control + Panel. + reset_authentication: + type: boolean + description: Reset authenticated account + x-ms-summary: Reset authenticated account + azure_blob_storage_access_key: + type: string + description: Azure Blob Storage secret key. + x-ms-summary: Azure Blob Storage secret key. + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + x-ms-summary: Hostname or IP address + name: + type: string + description: Internal name for your reference + example: My Remote server + x-ms-summary: Internal name for your reference + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + format: int32 + example: 1 + x-ms-summary: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + x-ms-summary: Port for remote server. Not needed for S3. + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + x-ms-summary: S3 bucket name + s3_region: + type: string + description: S3 region + example: us-east-1 + x-ms-summary: S3 region + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + x-ms-summary: Remote server certificate + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + example: '[public key]' + x-ms-summary: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + x-ms-summary: Remote server type. + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + x-ms-summary: Should we require SSL? + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + x-ms-summary: Remote server username. Not needed for S3 buckets. + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + x-ms-summary: Google Cloud Storage bucket name + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + x-ms-summary: Google Cloud Project ID + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + x-ms-summary: Backblaze B2 Cloud Storage Bucket name + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + x-ms-summary: Backblaze B2 Cloud Storage S3 Endpoint + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + x-ms-summary: Wasabi Bucket name + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + x-ms-summary: Wasabi region + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud + Control Panel. + example: rackspaceuser + x-ms-summary: Rackspace username used to login to the Rackspace + Cloud Control Panel. + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + example: dfw + x-ms-summary: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + rackspace_container: + type: string + description: The name of the container (top level directory) where + files will sync. + example: my-container + x-ms-summary: The name of the container (top level directory) where + files will sync. + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + x-ms-summary: Either personal or business_other account types + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + x-ms-summary: Azure Blob Storage Account name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + x-ms-summary: Azure Blob Storage Container name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + x-ms-summary: S3-compatible Bucket name + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + x-ms-summary: S3-compatible Bucket name + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + x-ms-summary: S3-compatible endpoint + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from + dedicated IPs' + example: true + x-ms-summary: '`true` if remote server only accepts connections + from dedicated IPs' + s3_compatible_access_key: + type: string + description: S3-compatible access key + x-ms-summary: S3-compatible access key + s3_compatible_secret_key: + type: string + description: S3-compatible secret key + x-ms-summary: S3-compatible secret key + application/x-www-form-urlencoded: + schema: + properties: + aws_access_key: + type: string + description: AWS Access Key. + x-ms-summary: AWS Access Key. + aws_secret_key: + type: string + description: AWS secret key. + x-ms-summary: AWS secret key. + password: + type: string + description: Password if needed. + x-ms-summary: Password if needed. + private_key: + type: string + description: Private key if needed. + x-ms-summary: Private key if needed. + ssl_certificate: + type: string + description: SSL client certificate. + x-ms-summary: SSL client certificate. + google_cloud_storage_credentials_json: + type: string + description: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + x-ms-summary: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + wasabi_access_key: + type: string + description: Wasabi access key. + x-ms-summary: Wasabi access key. + wasabi_secret_key: + type: string + description: Wasabi secret key. + x-ms-summary: Wasabi secret key. + backblaze_b2_key_id: + type: string + description: Backblaze B2 Cloud Storage keyID. + x-ms-summary: Backblaze B2 Cloud Storage keyID. + backblaze_b2_application_key: + type: string + description: Backblaze B2 Cloud Storage applicationKey. + x-ms-summary: Backblaze B2 Cloud Storage applicationKey. + rackspace_api_key: + type: string + description: Rackspace API key from the Rackspace Cloud Control + Panel. + x-ms-summary: Rackspace API key from the Rackspace Cloud Control + Panel. + reset_authentication: + type: boolean + description: Reset authenticated account + x-ms-summary: Reset authenticated account + azure_blob_storage_access_key: + type: string + description: Azure Blob Storage secret key. + x-ms-summary: Azure Blob Storage secret key. + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + x-ms-summary: Hostname or IP address + name: + type: string + description: Internal name for your reference + example: My Remote server + x-ms-summary: Internal name for your reference + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + format: int32 + example: 1 + x-ms-summary: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + x-ms-summary: Port for remote server. Not needed for S3. + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + x-ms-summary: S3 bucket name + s3_region: + type: string + description: S3 region + example: us-east-1 + x-ms-summary: S3 region + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + x-ms-summary: Remote server certificate + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + example: '[public key]' + x-ms-summary: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + x-ms-summary: Remote server type. + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + x-ms-summary: Should we require SSL? + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + x-ms-summary: Remote server username. Not needed for S3 buckets. + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + x-ms-summary: Google Cloud Storage bucket name + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + x-ms-summary: Google Cloud Project ID + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + x-ms-summary: Backblaze B2 Cloud Storage Bucket name + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + x-ms-summary: Backblaze B2 Cloud Storage S3 Endpoint + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + x-ms-summary: Wasabi Bucket name + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + x-ms-summary: Wasabi region + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud + Control Panel. + example: rackspaceuser + x-ms-summary: Rackspace username used to login to the Rackspace + Cloud Control Panel. + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + example: dfw + x-ms-summary: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + rackspace_container: + type: string + description: The name of the container (top level directory) where + files will sync. + example: my-container + x-ms-summary: The name of the container (top level directory) where + files will sync. + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + x-ms-summary: Either personal or business_other account types + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + x-ms-summary: Azure Blob Storage Account name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + x-ms-summary: Azure Blob Storage Container name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + x-ms-summary: S3-compatible Bucket name + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + x-ms-summary: S3-compatible Bucket name + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + x-ms-summary: S3-compatible endpoint + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from + dedicated IPs' + example: true + x-ms-summary: '`true` if remote server only accepts connections + from dedicated IPs' + s3_compatible_access_key: + type: string + description: S3-compatible access key + x-ms-summary: S3-compatible access key + s3_compatible_secret_key: + type: string + description: S3-compatible secret key + x-ms-summary: S3-compatible secret key + multipart/form-data: + schema: + properties: + aws_access_key: + type: string + description: AWS Access Key. + x-ms-summary: AWS Access Key. + aws_secret_key: + type: string + description: AWS secret key. + x-ms-summary: AWS secret key. + password: + type: string + description: Password if needed. + x-ms-summary: Password if needed. + private_key: + type: string + description: Private key if needed. + x-ms-summary: Private key if needed. + ssl_certificate: + type: string + description: SSL client certificate. + x-ms-summary: SSL client certificate. + google_cloud_storage_credentials_json: + type: string + description: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + x-ms-summary: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + wasabi_access_key: + type: string + description: Wasabi access key. + x-ms-summary: Wasabi access key. + wasabi_secret_key: + type: string + description: Wasabi secret key. + x-ms-summary: Wasabi secret key. + backblaze_b2_key_id: + type: string + description: Backblaze B2 Cloud Storage keyID. + x-ms-summary: Backblaze B2 Cloud Storage keyID. + backblaze_b2_application_key: + type: string + description: Backblaze B2 Cloud Storage applicationKey. + x-ms-summary: Backblaze B2 Cloud Storage applicationKey. + rackspace_api_key: + type: string + description: Rackspace API key from the Rackspace Cloud Control + Panel. + x-ms-summary: Rackspace API key from the Rackspace Cloud Control + Panel. + reset_authentication: + type: boolean + description: Reset authenticated account + x-ms-summary: Reset authenticated account + azure_blob_storage_access_key: + type: string + description: Azure Blob Storage secret key. + x-ms-summary: Azure Blob Storage secret key. + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + x-ms-summary: Hostname or IP address + name: + type: string + description: Internal name for your reference + example: My Remote server + x-ms-summary: Internal name for your reference + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + format: int32 + example: 1 + x-ms-summary: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + x-ms-summary: Port for remote server. Not needed for S3. + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + x-ms-summary: S3 bucket name + s3_region: + type: string + description: S3 region + example: us-east-1 + x-ms-summary: S3 region + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + x-ms-summary: Remote server certificate + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + example: '[public key]' + x-ms-summary: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + x-ms-summary: Remote server type. + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + x-ms-summary: Should we require SSL? + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + x-ms-summary: Remote server username. Not needed for S3 buckets. + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + x-ms-summary: Google Cloud Storage bucket name + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + x-ms-summary: Google Cloud Project ID + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + x-ms-summary: Backblaze B2 Cloud Storage Bucket name + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + x-ms-summary: Backblaze B2 Cloud Storage S3 Endpoint + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + x-ms-summary: Wasabi Bucket name + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + x-ms-summary: Wasabi region + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud + Control Panel. + example: rackspaceuser + x-ms-summary: Rackspace username used to login to the Rackspace + Cloud Control Panel. + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + example: dfw + x-ms-summary: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + rackspace_container: + type: string + description: The name of the container (top level directory) where + files will sync. + example: my-container + x-ms-summary: The name of the container (top level directory) where + files will sync. + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + x-ms-summary: Either personal or business_other account types + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + x-ms-summary: Azure Blob Storage Account name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + x-ms-summary: Azure Blob Storage Container name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + x-ms-summary: S3-compatible Bucket name + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + x-ms-summary: S3-compatible Bucket name + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + x-ms-summary: S3-compatible endpoint + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from + dedicated IPs' + example: true + x-ms-summary: '`true` if remote server only accepts connections + from dedicated IPs' + s3_compatible_access_key: + type: string + description: S3-compatible access key + x-ms-summary: S3-compatible access key + s3_compatible_secret_key: + type: string + description: S3-compatible secret key + x-ms-summary: S3-compatible secret key + responses: + 201: + description: The RemoteServers object. + content: + application/json: + schema: + $ref: '#/components/schemas/RemoteServerEntity' + x-ms-summary: The RemoteServers object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /remote_servers/{id}: + get: + tags: + - remote_servers + summary: Show Remote Server + description: Show Remote Server + operationId: GetRemoteServersId + parameters: + - name: id + in: path + description: Remote Server ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Remote Server ID. + x-ms-summary: Remote Server ID. + responses: + 200: + description: The RemoteServers object. + content: + application/json: + schema: + $ref: '#/components/schemas/RemoteServerEntity' + x-ms-summary: The RemoteServers object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + delete: + tags: + - remote_servers + summary: Delete Remote Server + description: Delete Remote Server + operationId: DeleteRemoteServersId + parameters: + - name: id + in: path + description: Remote Server ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Remote Server ID. + x-ms-summary: Remote Server ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + patch: + tags: + - remote_servers + summary: Update Remote Server + description: Update Remote Server + operationId: PatchRemoteServersId + parameters: + - name: id + in: path + description: Remote Server ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Remote Server ID. + x-ms-summary: Remote Server ID. + requestBody: + content: + application/json: + schema: + properties: + aws_access_key: + type: string + description: AWS Access Key. + x-ms-summary: AWS Access Key. + aws_secret_key: + type: string + description: AWS secret key. + x-ms-summary: AWS secret key. + password: + type: string + description: Password if needed. + x-ms-summary: Password if needed. + private_key: + type: string + description: Private key if needed. + x-ms-summary: Private key if needed. + ssl_certificate: + type: string + description: SSL client certificate. + x-ms-summary: SSL client certificate. + google_cloud_storage_credentials_json: + type: string + description: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + x-ms-summary: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + wasabi_access_key: + type: string + description: Wasabi access key. + x-ms-summary: Wasabi access key. + wasabi_secret_key: + type: string + description: Wasabi secret key. + x-ms-summary: Wasabi secret key. + backblaze_b2_key_id: + type: string + description: Backblaze B2 Cloud Storage keyID. + x-ms-summary: Backblaze B2 Cloud Storage keyID. + backblaze_b2_application_key: + type: string + description: Backblaze B2 Cloud Storage applicationKey. + x-ms-summary: Backblaze B2 Cloud Storage applicationKey. + rackspace_api_key: + type: string + description: Rackspace API key from the Rackspace Cloud Control + Panel. + x-ms-summary: Rackspace API key from the Rackspace Cloud Control + Panel. + reset_authentication: + type: boolean + description: Reset authenticated account + x-ms-summary: Reset authenticated account + azure_blob_storage_access_key: + type: string + description: Azure Blob Storage secret key. + x-ms-summary: Azure Blob Storage secret key. + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + x-ms-summary: Hostname or IP address + name: + type: string + description: Internal name for your reference + example: My Remote server + x-ms-summary: Internal name for your reference + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + format: int32 + example: 1 + x-ms-summary: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + x-ms-summary: Port for remote server. Not needed for S3. + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + x-ms-summary: S3 bucket name + s3_region: + type: string + description: S3 region + example: us-east-1 + x-ms-summary: S3 region + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + x-ms-summary: Remote server certificate + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + example: '[public key]' + x-ms-summary: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + x-ms-summary: Remote server type. + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + x-ms-summary: Should we require SSL? + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + x-ms-summary: Remote server username. Not needed for S3 buckets. + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + x-ms-summary: Google Cloud Storage bucket name + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + x-ms-summary: Google Cloud Project ID + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + x-ms-summary: Backblaze B2 Cloud Storage Bucket name + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + x-ms-summary: Backblaze B2 Cloud Storage S3 Endpoint + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + x-ms-summary: Wasabi Bucket name + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + x-ms-summary: Wasabi region + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud + Control Panel. + example: rackspaceuser + x-ms-summary: Rackspace username used to login to the Rackspace + Cloud Control Panel. + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + example: dfw + x-ms-summary: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + rackspace_container: + type: string + description: The name of the container (top level directory) where + files will sync. + example: my-container + x-ms-summary: The name of the container (top level directory) where + files will sync. + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + x-ms-summary: Either personal or business_other account types + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + x-ms-summary: Azure Blob Storage Account name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + x-ms-summary: Azure Blob Storage Container name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + x-ms-summary: S3-compatible Bucket name + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + x-ms-summary: S3-compatible Bucket name + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + x-ms-summary: S3-compatible endpoint + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from + dedicated IPs' + example: true + x-ms-summary: '`true` if remote server only accepts connections + from dedicated IPs' + s3_compatible_access_key: + type: string + description: S3-compatible access key + x-ms-summary: S3-compatible access key + s3_compatible_secret_key: + type: string + description: S3-compatible secret key + x-ms-summary: S3-compatible secret key + application/x-www-form-urlencoded: + schema: + properties: + aws_access_key: + type: string + description: AWS Access Key. + x-ms-summary: AWS Access Key. + aws_secret_key: + type: string + description: AWS secret key. + x-ms-summary: AWS secret key. + password: + type: string + description: Password if needed. + x-ms-summary: Password if needed. + private_key: + type: string + description: Private key if needed. + x-ms-summary: Private key if needed. + ssl_certificate: + type: string + description: SSL client certificate. + x-ms-summary: SSL client certificate. + google_cloud_storage_credentials_json: + type: string + description: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + x-ms-summary: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + wasabi_access_key: + type: string + description: Wasabi access key. + x-ms-summary: Wasabi access key. + wasabi_secret_key: + type: string + description: Wasabi secret key. + x-ms-summary: Wasabi secret key. + backblaze_b2_key_id: + type: string + description: Backblaze B2 Cloud Storage keyID. + x-ms-summary: Backblaze B2 Cloud Storage keyID. + backblaze_b2_application_key: + type: string + description: Backblaze B2 Cloud Storage applicationKey. + x-ms-summary: Backblaze B2 Cloud Storage applicationKey. + rackspace_api_key: + type: string + description: Rackspace API key from the Rackspace Cloud Control + Panel. + x-ms-summary: Rackspace API key from the Rackspace Cloud Control + Panel. + reset_authentication: + type: boolean + description: Reset authenticated account + x-ms-summary: Reset authenticated account + azure_blob_storage_access_key: + type: string + description: Azure Blob Storage secret key. + x-ms-summary: Azure Blob Storage secret key. + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + x-ms-summary: Hostname or IP address + name: + type: string + description: Internal name for your reference + example: My Remote server + x-ms-summary: Internal name for your reference + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + format: int32 + example: 1 + x-ms-summary: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + x-ms-summary: Port for remote server. Not needed for S3. + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + x-ms-summary: S3 bucket name + s3_region: + type: string + description: S3 region + example: us-east-1 + x-ms-summary: S3 region + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + x-ms-summary: Remote server certificate + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + example: '[public key]' + x-ms-summary: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + x-ms-summary: Remote server type. + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + x-ms-summary: Should we require SSL? + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + x-ms-summary: Remote server username. Not needed for S3 buckets. + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + x-ms-summary: Google Cloud Storage bucket name + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + x-ms-summary: Google Cloud Project ID + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + x-ms-summary: Backblaze B2 Cloud Storage Bucket name + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + x-ms-summary: Backblaze B2 Cloud Storage S3 Endpoint + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + x-ms-summary: Wasabi Bucket name + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + x-ms-summary: Wasabi region + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud + Control Panel. + example: rackspaceuser + x-ms-summary: Rackspace username used to login to the Rackspace + Cloud Control Panel. + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + example: dfw + x-ms-summary: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + rackspace_container: + type: string + description: The name of the container (top level directory) where + files will sync. + example: my-container + x-ms-summary: The name of the container (top level directory) where + files will sync. + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + x-ms-summary: Either personal or business_other account types + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + x-ms-summary: Azure Blob Storage Account name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + x-ms-summary: Azure Blob Storage Container name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + x-ms-summary: S3-compatible Bucket name + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + x-ms-summary: S3-compatible Bucket name + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + x-ms-summary: S3-compatible endpoint + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from + dedicated IPs' + example: true + x-ms-summary: '`true` if remote server only accepts connections + from dedicated IPs' + s3_compatible_access_key: + type: string + description: S3-compatible access key + x-ms-summary: S3-compatible access key + s3_compatible_secret_key: + type: string + description: S3-compatible secret key + x-ms-summary: S3-compatible secret key + multipart/form-data: + schema: + properties: + aws_access_key: + type: string + description: AWS Access Key. + x-ms-summary: AWS Access Key. + aws_secret_key: + type: string + description: AWS secret key. + x-ms-summary: AWS secret key. + password: + type: string + description: Password if needed. + x-ms-summary: Password if needed. + private_key: + type: string + description: Private key if needed. + x-ms-summary: Private key if needed. + ssl_certificate: + type: string + description: SSL client certificate. + x-ms-summary: SSL client certificate. + google_cloud_storage_credentials_json: + type: string + description: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + x-ms-summary: A JSON file that contains the private key. To generate + see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey + wasabi_access_key: + type: string + description: Wasabi access key. + x-ms-summary: Wasabi access key. + wasabi_secret_key: + type: string + description: Wasabi secret key. + x-ms-summary: Wasabi secret key. + backblaze_b2_key_id: + type: string + description: Backblaze B2 Cloud Storage keyID. + x-ms-summary: Backblaze B2 Cloud Storage keyID. + backblaze_b2_application_key: + type: string + description: Backblaze B2 Cloud Storage applicationKey. + x-ms-summary: Backblaze B2 Cloud Storage applicationKey. + rackspace_api_key: + type: string + description: Rackspace API key from the Rackspace Cloud Control + Panel. + x-ms-summary: Rackspace API key from the Rackspace Cloud Control + Panel. + reset_authentication: + type: boolean + description: Reset authenticated account + x-ms-summary: Reset authenticated account + azure_blob_storage_access_key: + type: string + description: Azure Blob Storage secret key. + x-ms-summary: Azure Blob Storage secret key. + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + x-ms-summary: Hostname or IP address + name: + type: string + description: Internal name for your reference + example: My Remote server + x-ms-summary: Internal name for your reference + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + format: int32 + example: 1 + x-ms-summary: Max number of parallel connections. Ignored for S3 + connections (we will parallelize these as much as possible). + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + x-ms-summary: Port for remote server. Not needed for S3. + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + x-ms-summary: S3 bucket name + s3_region: + type: string + description: S3 region + example: us-east-1 + x-ms-summary: S3 region + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + x-ms-summary: Remote server certificate + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + example: '[public key]' + x-ms-summary: Remote server SSH Host Key. If provided, we will require + that the server host key matches the provided key. Uses OpenSSH + format similar to what would go into ~/.ssh/known_hosts + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + x-ms-summary: Remote server type. + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + x-ms-summary: Should we require SSL? + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + x-ms-summary: Remote server username. Not needed for S3 buckets. + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + x-ms-summary: Google Cloud Storage bucket name + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + x-ms-summary: Google Cloud Project ID + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + x-ms-summary: Backblaze B2 Cloud Storage Bucket name + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + x-ms-summary: Backblaze B2 Cloud Storage S3 Endpoint + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + x-ms-summary: Wasabi Bucket name + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + x-ms-summary: Wasabi region + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud + Control Panel. + example: rackspaceuser + x-ms-summary: Rackspace username used to login to the Rackspace + Cloud Control Panel. + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + example: dfw + x-ms-summary: Three letter airport code for Rackspace region. See + https://support.rackspace.com/how-to/about-regions/ + rackspace_container: + type: string + description: The name of the container (top level directory) where + files will sync. + example: my-container + x-ms-summary: The name of the container (top level directory) where + files will sync. + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + x-ms-summary: Either personal or business_other account types + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + x-ms-summary: Azure Blob Storage Account name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + x-ms-summary: Azure Blob Storage Container name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + x-ms-summary: S3-compatible Bucket name + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + x-ms-summary: S3-compatible Bucket name + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + x-ms-summary: S3-compatible endpoint + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from + dedicated IPs' + example: true + x-ms-summary: '`true` if remote server only accepts connections + from dedicated IPs' + s3_compatible_access_key: + type: string + description: S3-compatible access key + x-ms-summary: S3-compatible access key + s3_compatible_secret_key: + type: string + description: S3-compatible secret key + x-ms-summary: S3-compatible secret key + responses: + 200: + description: The RemoteServers object. + content: + application/json: + schema: + $ref: '#/components/schemas/RemoteServerEntity' + x-ms-summary: The RemoteServers object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /requests/{id}: + delete: + tags: + - requests + summary: Delete Request + description: Delete Request + operationId: DeleteRequestsId + parameters: + - name: id + in: path + description: Request ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Request ID. + x-ms-summary: Request ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /requests: + get: + tags: + - requests + summary: List Requests + description: List Requests + operationId: GetRequests + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `destination`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `destination`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `destination`. + - name: mine + in: query + description: Only show requests of the current user? (Defaults to true if + current user is not a site admin.) + schema: + type: boolean + x-ms-summary: Only show requests of the current user? (Defaults to true + if current user is not a site admin.) + x-ms-summary: Only show requests of the current user? (Defaults to true if + current user is not a site admin.) + - name: requestPath + in: query + description: Path to show requests for. If omitted, shows all paths. Send + `/` to represent the root directory. + schema: + type: string + x-ms-summary: Path to show requests for. If omitted, shows all paths. Send + `/` to represent the root directory. + x-ms-summary: Path to show requests for. If omitted, shows all paths. Send + `/` to represent the root directory. + responses: + 200: + description: A list of Requests objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RequestEntity' + x-ms-summary: A list of Requests objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - requests/folders/*path + post: + tags: + - requests + summary: Create Request + description: Create Request + operationId: PostRequests + requestBody: + content: + application/json: + schema: + required: + - destination + - path + properties: + path: + type: string + description: Folder path on which to request the file. + x-ms-summary: Folder path on which to request the file. + destination: + type: string + description: Destination filename (without extension) to request. + x-ms-summary: Destination filename (without extension) to request. + user_ids: + type: string + description: A list of user IDs to request the file from. If sent + as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs to request the file from. If sent + as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs to request the file from. If sent + as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs to request the file from. If sent + as a string, it should be comma-delimited. + application/x-www-form-urlencoded: + schema: + required: + - destination + - path + properties: + path: + type: string + description: Folder path on which to request the file. + x-ms-summary: Folder path on which to request the file. + destination: + type: string + description: Destination filename (without extension) to request. + x-ms-summary: Destination filename (without extension) to request. + user_ids: + type: string + description: A list of user IDs to request the file from. If sent + as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs to request the file from. If sent + as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs to request the file from. If sent + as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs to request the file from. If sent + as a string, it should be comma-delimited. + multipart/form-data: + schema: + required: + - destination + - path + properties: + path: + type: string + description: Folder path on which to request the file. + x-ms-summary: Folder path on which to request the file. + destination: + type: string + description: Destination filename (without extension) to request. + x-ms-summary: Destination filename (without extension) to request. + user_ids: + type: string + description: A list of user IDs to request the file from. If sent + as a string, it should be comma-delimited. + x-ms-summary: A list of user IDs to request the file from. If sent + as a string, it should be comma-delimited. + group_ids: + type: string + description: A list of group IDs to request the file from. If sent + as a string, it should be comma-delimited. + x-ms-summary: A list of group IDs to request the file from. If sent + as a string, it should be comma-delimited. + required: true + responses: + 201: + description: The Requests object. + content: + application/json: + schema: + $ref: '#/components/schemas/RequestEntity' + x-ms-summary: The Requests object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /requests/folders/{folderPath}: + get: + tags: + - requests + summary: List Requests + description: List Requests + operationId: GetRequestsFoldersPath + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `destination`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `destination`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `destination`. + - name: mine + in: query + description: Only show requests of the current user? (Defaults to true if + current user is not a site admin.) + schema: + type: boolean + x-ms-summary: Only show requests of the current user? (Defaults to true + if current user is not a site admin.) + x-ms-summary: Only show requests of the current user? (Defaults to true if + current user is not a site admin.) + - name: folderPath + in: path + description: Path to show requests for. If omitted, shows all paths. Send + `/` to represent the root directory. + required: true + schema: + type: string + x-ms-summary: Path to show requests for. If omitted, shows all paths. Send + `/` to represent the root directory. + x-ms-summary: Path to show requests for. If omitted, shows all paths. Send + `/` to represent the root directory. + responses: + 200: + description: A list of Requests objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RequestEntity' + x-ms-summary: A list of Requests objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + x-path_aliases: + - requests/folders/*path + /sessions: + post: + tags: + - sessions + summary: Create user session (log in) + description: Create user session (log in) + operationId: PostSessions + requestBody: + content: + application/json: + schema: + properties: + username: + type: string + description: Username to sign in as + example: username + x-ms-summary: Username to sign in as + password: + type: string + description: Password for sign in + example: password + x-ms-summary: Password for sign in + otp: + type: string + description: If this user has a 2FA device, provide its OTP or code + here. + example: "123456" + x-ms-summary: If this user has a 2FA device, provide its OTP or + code here. + partial_session_id: + type: string + description: Identifier for a partially-completed login + x-ms-summary: Identifier for a partially-completed login + application/x-www-form-urlencoded: + schema: + properties: + username: + type: string + description: Username to sign in as + example: username + x-ms-summary: Username to sign in as + password: + type: string + description: Password for sign in + example: password + x-ms-summary: Password for sign in + otp: + type: string + description: If this user has a 2FA device, provide its OTP or code + here. + example: "123456" + x-ms-summary: If this user has a 2FA device, provide its OTP or + code here. + partial_session_id: + type: string + description: Identifier for a partially-completed login + x-ms-summary: Identifier for a partially-completed login + multipart/form-data: + schema: + properties: + username: + type: string + description: Username to sign in as + example: username + x-ms-summary: Username to sign in as + password: + type: string + description: Password for sign in + example: password + x-ms-summary: Password for sign in + otp: + type: string + description: If this user has a 2FA device, provide its OTP or code + here. + example: "123456" + x-ms-summary: If this user has a 2FA device, provide its OTP or + code here. + partial_session_id: + type: string + description: Identifier for a partially-completed login + x-ms-summary: Identifier for a partially-completed login + responses: + 201: + description: The Sessions object. + content: + application/json: + schema: + $ref: '#/components/schemas/SessionEntity' + x-ms-summary: The Sessions object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - sessions + summary: Delete user session (log out) + description: Delete user session (log out) + operationId: DeleteSessions + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + /settings_changes: + get: + tags: + - settings_changes + summary: List Settings Changes + description: List Settings Changes + operationId: GetSettingsChanges + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `api_key_id`, + `created_at` or `user_id`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `api_key_id`, `created_at` or `user_id`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `api_key_id`, `created_at` or `user_id`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `api_key_id` and `user_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `api_key_id` and `user_id`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `api_key_id` and `user_id`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `api_key_id` and `user_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `api_key_id` and `user_id`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `api_key_id` and `user_id`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `api_key_id` and `user_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `api_key_id` and + `user_id`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `api_key_id` and `user_id`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `api_key_id` and `user_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `api_key_id` and `user_id`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `api_key_id` and `user_id`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `api_key_id` and `user_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `api_key_id` and `user_id`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `api_key_id` and `user_id`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `api_key_id` and `user_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `api_key_id` and + `user_id`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `api_key_id` and `user_id`. + responses: + 200: + description: A list of SettingsChanges objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SettingsChangeEntity' + x-ms-summary: A list of SettingsChanges objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /sso_strategies/{id}: + get: + tags: + - sso_strategies + summary: Show Sso Strategy + description: Show Sso Strategy + operationId: GetSsoStrategiesId + parameters: + - name: id + in: path + description: Sso Strategy ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: Sso Strategy ID. + x-ms-summary: Sso Strategy ID. + responses: + 200: + description: The SsoStrategies object. + content: + application/json: + schema: + $ref: '#/components/schemas/SsoStrategyEntity' + x-ms-summary: The SsoStrategies object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /sso_strategies: + get: + tags: + - sso_strategies + summary: List Sso Strategies + description: List Sso Strategies + operationId: GetSsoStrategies + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of SsoStrategies objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SsoStrategyEntity' + x-ms-summary: A list of SsoStrategies objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /styles/{stylePath}: + get: + tags: + - styles + summary: Show Style + description: Show Style + operationId: GetStylesPath + parameters: + - name: stylePath + in: path + description: Style path. + required: true + schema: + type: string + x-ms-summary: Style path. + x-ms-summary: Style path. + responses: + 200: + description: The Styles object. + content: + application/json: + schema: + $ref: '#/components/schemas/StyleEntity' + x-ms-summary: The Styles object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: [] + delete: + tags: + - styles + summary: Delete Style + description: Delete Style + operationId: DeleteStylesPath + parameters: + - name: stylePath + in: path + description: Style path. + required: true + schema: + type: string + x-ms-summary: Style path. + x-ms-summary: Style path. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + patch: + tags: + - styles + summary: Update Style + description: Update Style + operationId: PatchStylesPath + parameters: + - name: stylePath + in: path + description: Style path. + required: true + schema: + type: string + x-ms-summary: Style path. + x-ms-summary: Style path. + requestBody: + content: + application/json: + schema: + required: + - file + properties: + file: + type: string + description: Logo for custom branding. + format: binary + x-ms-summary: Logo for custom branding. + application/x-www-form-urlencoded: + schema: + required: + - file + properties: + file: + type: string + description: Logo for custom branding. + format: binary + x-ms-summary: Logo for custom branding. + multipart/form-data: + schema: + required: + - file + properties: + file: + type: string + description: Logo for custom branding. + format: binary + x-ms-summary: Logo for custom branding. + required: true + responses: + 200: + description: The Styles object. + content: + application/json: + schema: + $ref: '#/components/schemas/StyleEntity' + x-ms-summary: The Styles object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /sync_jobs: + get: + tags: + - sync_jobs + summary: List Sync Jobs + description: List Sync Jobs + operationId: GetSyncJobs + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of SyncJobs objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SyncJobEntity' + x-ms-summary: A list of SyncJobs objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /usage_snapshots: + get: + tags: + - usage_snapshots + summary: List Usage Snapshots + description: List Usage Snapshots + operationId: GetUsageSnapshots + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of UsageSnapshots objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UsageSnapshotEntity' + x-ms-summary: A list of UsageSnapshots objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /usage_daily_snapshots: + get: + tags: + - usage_daily_snapshots + summary: List Usage Daily Snapshots + description: List Usage Daily Snapshots + operationId: GetUsageDailySnapshots + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + - name: sort_by + in: query + description: If set, sort records by the specified field in either 'asc' or + 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are `date` + and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `date` and `usage_snapshot_id`. + x-ms-summary: If set, sort records by the specified field in either 'asc' + or 'desc' direction (e.g. sort_by[last_login_at]=desc). Valid fields are + `date` and `usage_snapshot_id`. + - name: filter + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `date` and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `date` and `usage_snapshot_id`. + - name: filter_gt + in: query + description: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `date` and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `date` and `usage_snapshot_id`. + x-ms-summary: If set, return records where the specifiied field is greater + than the supplied value. Valid fields are `date` and `usage_snapshot_id`. + - name: filter_gteq + in: query + description: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + x-ms-summary: If set, return records where the specifiied field is greater + than or equal to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + - name: filter_like + in: query + description: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `date` and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is equal + to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + x-ms-summary: If set, return records where the specifiied field is equal to + the supplied value. Valid fields are `date` and `usage_snapshot_id`. + - name: filter_lt + in: query + description: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `date` and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than the supplied value. Valid fields are `date` and `usage_snapshot_id`. + x-ms-summary: If set, return records where the specifiied field is less than + the supplied value. Valid fields are `date` and `usage_snapshot_id`. + - name: filter_lteq + in: query + description: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + schema: + type: object + x-ms-summary: If set, return records where the specifiied field is less + than or equal to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + x-ms-summary: If set, return records where the specifiied field is less than + or equal to the supplied value. Valid fields are `date` and `usage_snapshot_id`. + responses: + 200: + description: A list of UsageDailySnapshots objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UsageDailySnapshotEntity' + x-ms-summary: A list of UsageDailySnapshots objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /user_cipher_uses: + get: + tags: + - user_cipher_uses + summary: List User Cipher Uses + description: List User Cipher Uses + operationId: GetUserCipherUses + parameters: + - name: user_id + in: query + description: User ID. Provide a value of `0` to operate the current session's + user. + schema: + type: integer + format: int32 + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + x-ms-summary: User ID. Provide a value of `0` to operate the current session's + user. + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of UserCipherUses objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UserCipherUseEntity' + x-ms-summary: A list of UserCipherUses objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - self_managed + x-path_aliases: + - users/:user_id/cipher_uses + /user_requests: + get: + tags: + - user_requests + summary: List User Requests + description: List User Requests + operationId: GetUserRequests + parameters: + - name: cursor + in: query + description: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + schema: + type: string + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + x-ms-summary: Used for pagination. Send a cursor value to resume an existing + list from the point at which you left off. Get a cursor from an existing + list via the X-Files-Cursor-Next header. + - name: per_page + in: query + description: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + schema: + type: integer + format: int32 + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 + or less is recommended).' + x-ms-summary: 'Number of records to show per page. (Max: 10,000, 1,000 or + less is recommended).' + responses: + 200: + description: A list of UserRequests objects. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UserRequestEntity' + x-ms-summary: A list of UserRequests objects. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + post: + tags: + - user_requests + summary: Create User Request + description: Create User Request + operationId: PostUserRequests + requestBody: + content: + application/json: + schema: + required: + - details + - email + - name + properties: + name: + type: string + description: Name of user requested + x-ms-summary: Name of user requested + email: + type: string + description: Email of user requested + x-ms-summary: Email of user requested + details: + type: string + description: Details of the user request + x-ms-summary: Details of the user request + application/x-www-form-urlencoded: + schema: + required: + - details + - email + - name + properties: + name: + type: string + description: Name of user requested + x-ms-summary: Name of user requested + email: + type: string + description: Email of user requested + x-ms-summary: Email of user requested + details: + type: string + description: Details of the user request + x-ms-summary: Details of the user request + multipart/form-data: + schema: + required: + - details + - email + - name + properties: + name: + type: string + description: Name of user requested + x-ms-summary: Name of user requested + email: + type: string + description: Email of user requested + x-ms-summary: Email of user requested + details: + type: string + description: Details of the user request + x-ms-summary: Details of the user request + required: true + responses: + 201: + description: The UserRequests object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserRequestEntity' + x-ms-summary: The UserRequests object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - none + /user_requests/{id}: + get: + tags: + - user_requests + summary: Show User Request + description: Show User Request + operationId: GetUserRequestsId + parameters: + - name: id + in: path + description: User Request ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User Request ID. + x-ms-summary: User Request ID. + responses: + 200: + description: The UserRequests object. + content: + application/json: + schema: + $ref: '#/components/schemas/UserRequestEntity' + x-ms-summary: The UserRequests object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + delete: + tags: + - user_requests + summary: Delete User Request + description: Delete User Request + operationId: DeleteUserRequestsId + parameters: + - name: id + in: path + description: User Request ID. + required: true + schema: + type: integer + format: int32 + x-ms-summary: User Request ID. + x-ms-summary: User Request ID. + responses: + 204: + description: No body. + content: {} + x-ms-summary: No body. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - site + /webhook_tests: + post: + tags: + - webhook_tests + summary: Create Webhook Test + description: Create Webhook Test + operationId: PostWebhookTests + requestBody: + content: + application/json: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + raw_body: + type: string + description: raw body text + example: test body + x-ms-summary: raw body text + file_as_body: + type: boolean + description: Send the file data as the request body? + example: false + x-ms-summary: Send the file data as the request body? + file_form_field: + type: string + description: Send the file data as a named parameter in the request + POST body + example: upload_file_data + x-ms-summary: Send the file data as a named parameter in the request + POST body + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + application/x-www-form-urlencoded: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + raw_body: + type: string + description: raw body text + example: test body + x-ms-summary: raw body text + file_as_body: + type: boolean + description: Send the file data as the request body? + example: false + x-ms-summary: Send the file data as the request body? + file_form_field: + type: string + description: Send the file data as a named parameter in the request + POST body + example: upload_file_data + x-ms-summary: Send the file data as a named parameter in the request + POST body + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + multipart/form-data: + schema: + required: + - url + properties: + url: + type: string + description: URL for testing the webhook. + example: https://www.site.com/... + x-ms-summary: URL for testing the webhook. + method: + type: string + description: HTTP method(GET or POST). + example: GET + x-ms-summary: HTTP method(GET or POST). + encoding: + type: string + description: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + example: RAW + x-ms-summary: HTTP encoding method. Can be JSON, XML, or RAW (form + data). + headers: + type: object + description: Additional request headers. + example: x-test-header => testvalue + x-ms-summary: Additional request headers. + body: + type: object + description: Additional body parameters. + example: test-param => testvalue + x-ms-summary: Additional body parameters. + raw_body: + type: string + description: raw body text + example: test body + x-ms-summary: raw body text + file_as_body: + type: boolean + description: Send the file data as the request body? + example: false + x-ms-summary: Send the file data as the request body? + file_form_field: + type: string + description: Send the file data as a named parameter in the request + POST body + example: upload_file_data + x-ms-summary: Send the file data as a named parameter in the request + POST body + action: + type: string + description: action for test body + example: test + x-ms-summary: action for test body + required: true + responses: + 201: + description: The WebhookTests object. + content: + application/json: + schema: + description: Webhook test entity + $ref: '#/components/schemas/WebhookTestEntity' + x-ms-summary: The WebhookTests object. + 400: + description: Bad Request + content: {} + x-ms-summary: Bad Request + 401: + description: Unauthorized + content: {} + x-ms-summary: Unauthorized + 403: + description: Forbidden + content: {} + x-ms-summary: Forbidden + 404: + description: Not Found + content: {} + x-ms-summary: Not Found + 405: + description: Method Not Allowed + content: {} + x-ms-summary: Method Not Allowed + 409: + description: Conflict + content: {} + x-ms-summary: Conflict + 412: + description: Precondition Failed + content: {} + x-ms-summary: Precondition Failed + 422: + description: Unprocessable Entity + content: {} + x-ms-summary: Unprocessable Entity + 423: + description: Locked + content: {} + x-ms-summary: Locked + 429: + description: Too Many Requests + content: {} + x-ms-summary: Too Many Requests + x-authentication: + - folder_admin +components: + schemas: + ActionNotificationExportEntity: + type: object + properties: + id: + type: integer + description: History Export ID + format: int32 + example: 1 + export_version: + type: string + description: Version of the underlying records for the export. + example: "20201213.2" + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + status: + type: string + description: 'Status of export. Valid values: `building`, `ready`, or `failed`' + example: ready + query_path: + type: string + description: Return notifications that were triggered by actions on this + specific path. + example: MyFile.txt + query_folder: + type: string + description: Return notifications that were triggered by actions in this + folder. + example: MyFolder + query_message: + type: string + description: Error message associated with the request, if any. + example: Connection Refused + query_request_method: + type: string + description: The HTTP request method used by the webhook. + example: GET + query_request_url: + type: string + description: The target webhook URL. + example: http://example.com/webhook + query_status: + type: string + description: The HTTP status returned from the server in response to the + webhook request. + example: "200" + query_success: + type: boolean + description: true if the webhook request succeeded (i.e. returned a 200 + or 204 response status). false otherwise. + example: true + results_url: + type: string + description: If `status` is `ready`, this will be a URL where all the results + can be downloaded at once as a CSV. + example: https://files.com/action_notification_results.csv + description: Show Action Notification Export + x-docs: | + The Action Notification Export API provides access to outgoing webhook logs. Querying webhook logs is a little different than other APIs. + + All queries against the archive must be submitted as Exports. (Even our Web UI creates an Export behind the scenes.) + + In any query field in this API, you may specify multiple values separated by commas. That means that commas + cannot be searched for themselves, and neither can single quotation marks. + + Use the following steps to complete an export: + + 1. Initiate the export by using the Create Action Notification Export endpoint. Non Site Admins must query by folder or path. + 2. Using the `id` from the response to step 1, poll the Show Action Notification Export endpoint. Check the `status` field until it is `ready`. + 3. You can download the results of the export as a CSV file using the `results_url` field in the response from step 2. If you want to page through the records in JSON format, use the List Action Notification Export Results endpoint, passing the `id` that you got in step 1 as the `action_notification_export_id` parameter. Check the `X-Files-Cursor` header to see if there are more records available, and resubmit the same request with a `cursor` parameter to fetch the next page of results. + + If you intend to use this API for high volume or automated use, please contact us with more information + about your use case. + + ## Example Queries + + * History for a folder: `{ "query_folder": "path/to/folder" }` + * History for a range of time: `{ "start_at": "2021-03-18 12:00:00", "end_at": "2021-03-19 12:00:00" }` + * History of all notifications that used GET or POST: `{ "query_request_method": "GET,POST" }` + ActionNotificationExportResultEntity: + type: object + properties: + id: + type: integer + description: Notification ID + format: int32 + example: 1 + created_at: + type: integer + description: When the notification was sent. + format: int32 + example: 1 + status: + type: integer + description: HTTP status code returned in the webhook response. + format: int32 + example: 200 + message: + type: string + description: A message indicating the overall status of the webhook notification. + example: Success + success: + type: boolean + description: '`true` if the webhook succeeded by receiving a 200 or 204 + response.' + example: true + request_headers: + type: string + description: A JSON-encoded string with headers that were sent with the + webhook. + example: '{"User-Agent":"Files.com Webhook"}' + request_method: + type: string + description: The HTTP verb used to perform the webhook. + example: GET + request_url: + type: string + description: The webhook request URL. + example: www.example.com/webhook_receiver + path: + type: string + description: The path to the actual file that triggered this notification. + example: MyFolder/MyFile.txt + folder: + type: string + description: The folder associated with the triggering action for this notification. + example: MyFolder + description: List Action Notification Export Results + x-docs: null + ApiKeyEntity: + type: object + properties: + id: + type: integer + description: API Key ID + format: int32 + example: 1 + descriptive_label: + type: string + description: Unique label that describes this API key. Useful for external + systems where you may have API keys from multiple accounts and want a + human-readable label for each key. + example: 'Site-wide API key for https://site.files.com/ (key ID #1)' + created_at: + type: string + description: Time which API Key was created + format: date-time + example: 2000-01-01T01:00:00Z + expires_at: + type: string + description: API Key expiration date + format: date-time + example: 2000-01-01T01:00:00Z + key: + type: string + description: API Key actual key string + example: '[key]' + last_use_at: + type: string + description: API Key last used - note this value is only updated once per + 3 hour period, so the 'actual' time of last use may be up to 3 hours later + than this timestamp. + format: date-time + example: 2000-01-01T01:00:00Z + name: + type: string + description: Internal name for the API Key. For your use. + example: My Main API Key + path: + type: string + description: Folder path restriction for this api key. + example: shared/docs + permission_set: + type: string + description: Permissions for this API Key. Keys with the `desktop_app` + permission set only have the ability to do the functions provided in our + Desktop App (File and Share Link operations). Additional permission sets + may become available in the future, such as for a Site Admin to give a + key with no administrator privileges. If you have ideas for permission + sets, please let us know. + example: full + enum: + - none + - full + - desktop_app + - sync_app + - office_integration + - mobile_app + platform: + type: string + description: If this API key represents a Desktop app, what platform was + it created on? + example: win32 + user_id: + type: integer + description: User ID for the owner of this API Key. May be blank for Site-wide + API Keys. + format: int32 + example: 1 + description: List Api Keys + x-docs: | + API Keys allow programmatic access to your Site. + API keys confer all the permissions of the user who owns them. + If an API key is created without a user owner, it is considered a site-wide API key, which has full permissions to do anything on the Site. + UsageSnapshotEntity: + type: object + properties: + id: + type: integer + description: Site usage ID + format: int32 + example: 1 + start_at: + type: string + description: Site usage report start date/time + format: date-time + example: 2000-01-01T01:00:00Z + end_at: + type: string + description: Site usage report end date/time + format: date-time + example: 2000-01-01T01:00:00Z + created_at: + type: string + description: Site usage report created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + high_water_user_count: + type: number + description: Site usage report highest usage in time period + format: double + example: 1.0 + current_storage: + type: number + description: Current site usage as of report + format: double + example: 1.0 + high_water_storage: + type: number + description: Site usage report highest usage in time period + format: double + example: 1.0 + total_downloads: + type: integer + description: Number of downloads in report time period + format: int32 + example: 1 + total_uploads: + type: integer + description: Number of uploads in time period + format: int32 + example: 1 + updated_at: + type: string + description: The last time this site usage report was updated + format: date-time + example: 2000-01-01T01:00:00Z + usage_by_top_level_dir: + type: object + properties: {} + description: A map of root folders to their total usage + example: {} + root_storage: + type: number + description: Usage for root folder + format: double + example: 1.0 + deleted_files_counted_in_minimum: + type: number + description: Usage for files that are deleted but uploaded within last 30 + days + format: double + example: 1.0 + deleted_files_storage: + type: number + description: Usage for files that are deleted but retained as backups + format: double + example: 1.0 + description: List Usage Snapshots + x-docs: null + SiteEntity: + type: object + properties: + name: + type: string + description: Site name + example: My Site + allowed_2fa_method_sms: + type: boolean + description: Is SMS two factor authentication allowed? + example: true + allowed_2fa_method_totp: + type: boolean + description: Is TOTP two factor authentication allowed? + example: true + allowed_2fa_method_u2f: + type: boolean + description: Is U2F two factor authentication allowed? + example: true + allowed_2fa_method_yubi: + type: boolean + description: Is yubikey two factor authentication allowed? + example: true + admin_user_id: + type: integer + description: User ID for the main site administrator + format: int32 + example: 1 + allow_bundle_names: + type: boolean + description: Are manual Bundle names allowed? + example: true + allowed_countries: + type: string + description: Comma seperated list of allowed Country codes + example: US,DE + allowed_ips: + type: string + description: List of allowed IP addresses + example: "" + ask_about_overwrites: + type: boolean + description: If false, rename conflicting files instead of asking for overwrite + confirmation. Only applies to web interface. + example: true + bundle_expiration: + type: integer + description: Site-wide Bundle expiration in days + format: int32 + example: 1 + bundle_password_required: + type: boolean + description: Do Bundles require password protection? + example: true + bundle_require_share_recipient: + type: boolean + description: Do Bundles require recipients for sharing? + example: true + color2_left: + type: string + description: Page link and button color + example: '#0066a7' + color2_link: + type: string + description: Top bar link color + example: '#d34f5d' + color2_text: + type: string + description: Page link and button color + example: '#0066a7' + color2_top: + type: string + description: Top bar background color + example: '#000000' + color2_top_text: + type: string + description: Top bar text color + example: '#ffffff' + contact_name: + type: string + description: Site main contact name + example: John Doe + created_at: + type: string + description: Time this site was created + format: date-time + example: 2000-01-01T01:00:00Z + currency: + type: string + description: Preferred currency + example: USD + custom_namespace: + type: boolean + description: Is this site using a custom namespace for users? + example: true + days_to_retain_backups: + type: integer + description: Number of days to keep deleted files + format: int32 + example: 30 + default_time_zone: + type: string + description: Site default time zone + example: Pacific Time (US & Canada) + desktop_app: + type: boolean + description: Is the desktop app enabled? + example: true + desktop_app_session_ip_pinning: + type: boolean + description: Is desktop app session IP pinning enabled? + example: true + desktop_app_session_lifetime: + type: integer + description: Desktop app session lifetime (in hours) + format: int32 + example: 1 + mobile_app: + type: boolean + description: Is the mobile app enabled? + example: true + mobile_app_session_ip_pinning: + type: boolean + description: Is mobile app session IP pinning enabled? + example: true + mobile_app_session_lifetime: + type: integer + description: Mobile app session lifetime (in hours) + format: int32 + example: 1 + disallowed_countries: + type: string + description: Comma seperated list of disallowed Country codes + example: US,DE + disable_notifications: + type: boolean + description: Are notifications disabled? + example: true + disable_password_reset: + type: boolean + description: Is password reset disabled? + example: true + domain: + type: string + description: Custom domain + example: my-custom-domain.com + email: + type: string + description: Main email for this site + format: email + example: john.doe@files.com + reply_to_email: + type: string + description: Reply-to email for this site + format: email + example: jane.doe@files.com + non_sso_groups_allowed: + type: boolean + description: If true, groups can be manually created / modified / deleted + by Site Admins. Otherwise, groups can only be managed via your SSO provider. + example: true + non_sso_users_allowed: + type: boolean + description: If true, users can be manually created / modified / deleted + by Site Admins. Otherwise, users can only be managed via your SSO provider. + example: true + folder_permissions_groups_only: + type: boolean + description: If true, permissions for this site must be bound to a group + (not a user). Otherwise, permissions must be bound to a user. + example: true + hipaa: + type: boolean + description: Is there a signed HIPAA BAA between Files.com and this site? + example: true + icon128: + description: Branded icon 128x128 + $ref: '#/components/schemas/ImageEntity' + icon16: + description: Branded icon 16x16 + $ref: '#/components/schemas/ImageEntity' + icon32: + description: Branded icon 32x32 + $ref: '#/components/schemas/ImageEntity' + icon48: + description: Branded icon 48x48 + $ref: '#/components/schemas/ImageEntity' + immutable_files_set_at: + type: string + description: Can files be modified? + format: date-time + example: 2000-01-01T01:00:00Z + include_password_in_welcome_email: + type: boolean + description: Include password in emails to new users? + example: true + language: + type: string + description: Site default language + example: en + ldap_base_dn: + type: string + description: Base DN for looking up users in LDAP server + example: "" + ldap_domain: + type: string + description: Domain name that will be appended to usernames + example: mysite.com + ldap_enabled: + type: boolean + description: 'Main LDAP setting: is LDAP enabled?' + example: true + ldap_group_action: + type: string + description: Should we sync groups from LDAP server? + example: disabled + ldap_group_exclusion: + type: string + description: Comma or newline separated list of group names (with optional + wildcards) to exclude when syncing. + example: "" + ldap_group_inclusion: + type: string + description: Comma or newline separated list of group names (with optional + wildcards) to include when syncing. + example: "" + ldap_host: + type: string + description: LDAP host + example: ldap.site.com + ldap_host_2: + type: string + description: LDAP backup host + example: ldap2.site.com + ldap_host_3: + type: string + description: LDAP backup host + example: ldap3.site.com + ldap_port: + type: integer + description: LDAP port + format: int32 + example: 1 + ldap_secure: + type: boolean + description: Use secure LDAP? + example: true + ldap_type: + type: string + description: LDAP type + example: open_ldap + ldap_user_action: + type: string + description: Should we sync users from LDAP server? + example: disabled + ldap_user_include_groups: + type: string + description: Comma or newline separated list of group names (with optional + wildcards) - if provided, only users in these groups will be added or + synced. + example: "" + ldap_username: + type: string + description: Username for signing in to LDAP server. + example: '[ldap username]' + ldap_username_field: + type: string + description: LDAP username field + example: sAMAccountName + login_help_text: + type: string + description: Login help text + example: Login page help text. + logo: + $ref: '#/components/schemas/ImageEntity' + description: Branded logo + max_prior_passwords: + type: integer + description: Number of prior passwords to disallow + format: int32 + example: 1 + next_billing_amount: + type: number + description: Next billing amount + format: double + example: 1.0 + next_billing_date: + type: string + description: Next billing date + example: Apr 20 + office_integration_available: + type: boolean + description: Allow users to use Office for the web? + example: true + oncehub_link: + type: string + description: Link to scheduling a meeting with our Sales team + example: https://go.oncehub.com/files + opt_out_global: + type: boolean + description: Use servers in the USA only? + example: true + overage_notified_at: + type: string + description: Last time the site was notified about an overage + format: date-time + example: 2000-01-01T01:00:00Z + overage_notify: + type: boolean + description: Notify site email of overages? + example: true + overdue: + type: boolean + description: Is this site's billing overdue? + example: true + password_min_length: + type: integer + description: Shortest password length for users + format: int32 + example: 1 + password_require_letter: + type: boolean + description: Require a letter in passwords? + example: true + password_require_mixed: + type: boolean + description: Require lower and upper case letters in passwords? + example: true + password_require_number: + type: boolean + description: Require a number in passwords? + example: true + password_require_special: + type: boolean + description: Require special characters in password? + example: true + password_require_unbreached: + type: boolean + description: Require passwords that have not been previously breached? (see + https://haveibeenpwned.com/) + example: true + password_requirements_apply_to_bundles: + type: boolean + description: Require bundles' passwords, and passwords for other items (inboxes, + public shares, etc.) to conform to the same requirements as users' passwords? + example: true + password_validity_days: + type: integer + description: Number of days password is valid + format: int32 + example: 1 + phone: + type: string + description: Site phone number + example: 555-555-5555 + require_2fa: + type: boolean + description: Require two-factor authentication for all users? + example: true + require_2fa_stop_time: + type: string + description: If set, requirement for two-factor authentication has been + scheduled to end on this date-time. + format: date-time + example: 2000-01-01T01:00:00Z + require_2fa_user_type: + type: string + description: What type of user is required to use two-factor authentication + (when require_2fa is set to `true` for this site)? + example: '`site_admins`' + enum: + - all + - folder_and_site_admins + - site_admins + session: + $ref: '#/components/schemas/SessionEntity' + session_pinned_by_ip: + type: boolean + description: Are sessions locked to the same IP? (i.e. do users need to + log in again if they change IPs?) + example: true + sftp_user_root_enabled: + type: boolean + description: Use user FTP roots also for SFTP? + sharing_enabled: + type: boolean + description: Allow bundle creation + example: true + show_request_access_link: + type: boolean + description: Show request access link for users without access? Currently + unused. + example: true + site_footer: + type: string + description: Custom site footer text + example: "" + site_header: + type: string + description: Custom site header text + example: "" + smtp_address: + type: string + description: SMTP server hostname or IP + example: smtp.my-mail-server.com + smtp_authentication: + type: string + description: SMTP server authentication type + example: plain + smtp_from: + type: string + description: From address to use when mailing through custom SMTP + example: me@my-mail-server.com + smtp_port: + type: integer + description: SMTP server port + format: int32 + example: 25 + smtp_username: + type: string + description: SMTP server username + example: mail + session_expiry: + type: number + description: Session expiry in hours + format: double + example: 6.0 + ssl_required: + type: boolean + description: Is SSL required? Disabling this is insecure. + example: true + subdomain: + type: string + description: Site subdomain + example: mysite + switch_to_plan_date: + type: string + description: If switching plans, when does the new plan take effect? + format: date-time + example: 2000-01-01T01:00:00Z + tls_disabled: + type: boolean + description: Is TLS disabled(site setting)? + trial_days_left: + type: integer + description: Number of days left in trial + format: int32 + example: 1 + trial_until: + type: string + description: When does this Site trial expire? + format: date-time + example: 2000-01-01T01:00:00Z + updated_at: + type: string + description: Last time this Site was updated + format: date-time + example: 2000-01-01T01:00:00Z + use_provided_modified_at: + type: boolean + description: Allow uploaders to set `provided_modified_at` for uploaded + files? + example: true + user: + $ref: '#/components/schemas/UserEntity' + user_lockout: + type: boolean + description: Will users be locked out after incorrect login attempts? + example: true + user_lockout_lock_period: + type: integer + description: How many hours to lock user out for failed password? + format: int32 + example: 1 + user_lockout_tries: + type: integer + description: Number of login tries within `user_lockout_within` hours before + users are locked out + format: int32 + example: 1 + user_lockout_within: + type: integer + description: Number of hours for user lockout window + format: int32 + example: 6 + user_requests_enabled: + type: boolean + description: Enable User Requests feature + example: true + welcome_custom_text: + type: string + description: Custom text send in user welcome email + example: Welcome to my site! + welcome_email_cc: + type: string + description: Include this email in welcome emails if enabled + format: email + example: "" + welcome_email_enabled: + type: boolean + description: Will the welcome email be sent to new users? + example: true + welcome_screen: + type: string + description: Does the welcome screen appear? + example: user_controlled + enum: + - enabled + - hidden + - disabled + windows_mode_ftp: + type: boolean + description: Does FTP user Windows emulation mode? + example: true + disable_users_from_inactivity_period_days: + type: integer + description: If greater than zero, users will unable to login if they do + not show activity within this number of days. + format: int32 + example: 1 + description: Show site settings + x-docs: | + # Site + + The Site resource in the REST API allows you to operate on your Site. + This is the place you'll come to update site settings, as well as manage sitewide API keys. + + Most site settings can be set via the API. + ImageEntity: + type: object + properties: + name: + type: string + description: Image name + example: My logo + uri: + type: string + description: Image URI + example: https://mysite.files.com/.../my_image.png + x-docs: null + description: Image entity + SessionEntity: + type: object + properties: + id: + type: string + description: Session ID + example: 60525f92e859c4c3d74cb02fd176b1525901b525 + language: + type: string + description: Session language + example: en + login_token: + type: string + description: Login token. If set, this token will allow your user to log + in via browser at the domain in `login_token_domain`. + example: '@tok-randomcode' + login_token_domain: + type: string + description: Domain to use with `login_token`. + example: https://mysite.files.com + max_dir_listing_size: + type: integer + description: Maximum number of files to retrieve per folder for a directory + listing. This is based on the user's plan. + format: int32 + multiple_regions: + type: boolean + description: Can access multiple regions? + example: true + read_only: + type: boolean + description: Is this session read only? + example: true + root_path: + type: string + description: Initial root path to start the user's session in. + example: "" + site_id: + type: integer + description: Site ID + format: int32 + example: 1 + ssl_required: + type: boolean + description: Is SSL required for this user? (If so, ensure all your communications + with this user use SSL.) + example: true + tls_disabled: + type: boolean + description: Is strong TLS disabled for this user? (If this is set to true, + the site administrator has signaled that it is ok to use less secure TLS + versions for this user.) + two_factor_setup_needed: + type: boolean + description: If true, this user needs to add a Two Factor Authentication + method before performing any further actions. + allowed_2fa_method_sms: + type: boolean + description: Sent only if 2FA setup is needed. Is SMS two factor authentication + allowed? + example: true + allowed_2fa_method_totp: + type: boolean + description: Sent only if 2FA setup is needed. Is TOTP two factor authentication + allowed? + example: true + allowed_2fa_method_u2f: + type: boolean + description: Sent only if 2FA setup is needed. Is U2F two factor authentication + allowed? + example: true + allowed_2fa_method_yubi: + type: boolean + description: Sent only if 2FA setup is needed. Is Yubikey two factor authentication + allowed? + example: true + use_provided_modified_at: + type: boolean + description: Allow the user to provide file/folder modified at dates? If + false, the server will always use the current date/time. + example: true + windows_mode_ftp: + type: boolean + description: Does this user want to use Windows line-ending emulation? (CR + vs CRLF) + description: Create user session (log in) + x-docs: | + You may use a Session to make further API calls using our REST API or SDKs as a specific user. + This is the only way to use the API if you know a username/password but not an API key. + UserEntity: + type: object + properties: + id: + type: integer + description: User ID + format: int32 + example: 1 + username: + type: string + description: User's username + example: user + admin_group_ids: + type: array + description: List of group IDs of which this user is an administrator + example: + - 1 + items: + type: integer + format: int32 + allowed_ips: + type: string + description: A list of allowed IPs if applicable. Newline delimited + example: 127.0.0.1 + attachments_permission: + type: boolean + description: 'DEPRECATED: Can the user create Bundles (aka Share Links)? + Use the bundle permission instead.' + example: true + api_keys_count: + type: integer + description: Number of api keys associated with this user + format: int32 + example: 1 + authenticate_until: + type: string + description: Scheduled Date/Time at which user will be deactivated + format: date-time + example: 2000-01-01T01:00:00Z + authentication_method: + type: string + description: How is this user authenticated? + example: password + enum: + - password + - unused_former_ldap + - sso + - none + - email_signup + - password_with_imported_hash + avatar_url: + type: string + description: URL holding the user's avatar + example: "" + billing_permission: + type: boolean + description: Allow this user to perform operations on the account, payments, + and invoices? + bypass_site_allowed_ips: + type: boolean + description: Allow this user to skip site-wide IP blacklists? + bypass_inactive_disable: + type: boolean + description: Exempt this user from being disabled based on inactivity? + created_at: + type: string + description: When this user was created + format: date-time + example: 2000-01-01T01:00:00Z + dav_permission: + type: boolean + description: Can the user connect with WebDAV? + example: true + disabled: + type: boolean + description: Is user disabled? Disabled users cannot log in, and do not + count for billing purposes. Users can be automatically disabled after + an inactivity period via a Site setting. + example: true + email: + type: string + description: User email address + format: email + example: john.doe@files.com + ftp_permission: + type: boolean + description: Can the user access with FTP/FTPS? + example: true + group_ids: + type: string + description: Comma-separated list of group IDs of which this user is a member + example: "" + header_text: + type: string + description: Text to display to the user in the header of the UI + example: User-specific message. + language: + type: string + description: Preferred language + example: en + last_login_at: + type: string + description: User's last login time + format: date-time + example: 2000-01-01T01:00:00Z + last_protocol_cipher: + type: string + description: The last protocol and cipher used + example: "" + lockout_expires: + type: string + description: Time in the future that the user will no longer be locked out + if applicable + format: date-time + example: 2000-01-01T01:00:00Z + name: + type: string + description: User's full name + example: John Doe + company: + type: string + description: User's company + example: ACME Corp. + notes: + type: string + description: Any internal notes on the user + example: Internal notes on this user. + notification_daily_send_time: + type: integer + description: Hour of the day at which daily notifications should be sent. + Can be in range 0 to 23 + format: int32 + example: 18 + office_integration_enabled: + type: boolean + description: Enable integration with Office for the web? + example: true + password_set_at: + type: string + description: Last time the user's password was set + format: date-time + example: 2000-01-01T01:00:00Z + password_validity_days: + type: integer + description: Number of days to allow user to use the same password + format: int32 + example: 1 + public_keys_count: + type: integer + description: Number of public keys associated with this user + format: int32 + example: 1 + receive_admin_alerts: + type: boolean + description: Should the user receive admin alerts such a certificate expiration + notifications and overages? + example: true + require_2fa: + type: string + description: 2FA required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + active_2fa: + type: boolean + description: Is 2fa active for the user? + example: true + require_password_change: + type: boolean + description: Is a password change required upon next user login? + example: true + restapi_permission: + type: boolean + description: Can this user access the REST API? + example: true + self_managed: + type: boolean + description: Does this user manage it's own credentials or is it a shared/bot + user? + example: true + sftp_permission: + type: boolean + description: Can the user access with SFTP? + example: true + site_admin: + type: boolean + description: Is the user an administrator for this site? + example: true + skip_welcome_screen: + type: boolean + description: Skip Welcome page in the UI? + example: true + ssl_required: + type: string + description: SSL required setting + example: always_require + enum: + - use_system_setting + - always_require + - never_require + sso_strategy_id: + type: integer + description: SSO (Single Sign On) strategy ID for the user, if applicable. + format: int32 + example: 1 + subscribe_to_newsletter: + type: boolean + description: Is the user subscribed to the newsletter? + example: true + externally_managed: + type: boolean + description: Is this user managed by a SsoStrategy? + example: true + time_zone: + type: string + description: User time zone + example: Pacific Time (US & Canada) + type_of_2fa: + type: string + description: Type(s) of 2FA methods in use. Will be either `sms`, `totp`, + `u2f`, `yubi`, or multiple values sorted alphabetically and joined by + an underscore. + example: "" + default: yubi + user_root: + type: string + description: Root folder for FTP (and optionally SFTP if the appropriate + site-wide setting is set.) Note that this is not used for API, Desktop, + or Web interface. + example: "" + description: Create User + x-docs: null + IpAddressEntity: + type: object + properties: + id: + type: string + description: Unique label for list; used by Zapier and other integrations. + example: Site + associated_with: + type: string + description: The object that this public IP address list is associated with. + example: Site + group_id: + type: integer + description: Group ID + format: int32 + example: 1 + ip_addresses: + type: array + description: A list of IP addresses. + example: + - 127.0.0.1 + items: + type: string + example: "" + description: List IP Addresses associated with the current site + x-docs: | + Customers who maintain custom firewall configurations may require knowing the public IP addresses of Files.com's edge servers. + + This API resource provides an updated list of IP addresses that you can use to automate keeping your firewall's configuration up to date. + DnsRecordEntity: + type: object + properties: + id: + type: string + description: Unique label for DNS record; used by Zapier and other integrations. + example: customdomain.com-CNAME-site.files.com + domain: + type: string + description: DNS record domain name + example: my-custom-domain.com + rrtype: + type: string + description: DNS record type + example: CNAME + value: + type: string + description: DNS record value + example: mysite.files.com + description: Show site DNS configuration. + x-docs: | + This resource allows retrieving the DNS records that are needed to configure custom DNS for a Site. + StatusEntity: + type: object + properties: + code: + type: integer + description: Status HTTP code + format: int32 + example: 200 + message: + type: string + description: Error message + example: "" + status: + type: string + description: Status message + example: "" + data: + description: Auto fields. + $ref: '#/components/schemas/AutoEntity' + errors: + description: Error fields. + $ref: '#/components/schemas/ErrorsEntity' + clickwrap_id: + type: integer + description: Required Clickwrap id + format: int32 + example: 1 + clickwrap_body: + type: string + description: Required Clickwrap body + example: "" + description: Test webhook. + x-docs: null + AutoEntity: + description: Auto fields. + type: object + properties: + dynamic: + description: Dynamic properties + type: object + properties: {} + x-docs: null + ErrorsEntity: + description: Error fields. + type: object + properties: + fields: + type: array + description: A list of fields where errors occur + example: [] + items: + type: string + example: "" + messages: + type: array + description: A list of error messages + example: [] + items: + type: string + example: "" + x-docs: null + PublicKeyEntity: + type: object + properties: + id: + type: integer + description: Public key ID + format: int32 + example: 1 + title: + type: string + description: Public key title + example: My public key + created_at: + type: string + description: Public key created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + fingerprint: + type: string + description: Public key fingerprint + example: 43:51:43:a1:b5:fc:8b:b7:0a:3a:a9:b1:0f:66:73:a8 + description: List Public Keys + x-docs: | + Public keys are used by Users who want to connect via SFTP/SSH. + (Note that our SSH support is limited to file operations only, no shell is provided.) + GroupUserEntity: + type: object + properties: + group_name: + type: string + description: Group name + example: My Group + group_id: + type: integer + description: Group ID + format: int32 + example: 1 + user_id: + type: integer + description: User ID + format: int32 + example: 1 + admin: + type: boolean + description: Is this user an administrator of this group? + example: true + usernames: + type: array + description: A list of usernames for users in this group + example: + - user + items: + type: string + example: "" + description: Create Group User + x-docs: | + A GroupUser describes the membership of a User within a Group. + + ## Creating GroupUsers + GroupUsers can be created via the normal `create` action. When using the `update` action, if the + GroupUser record does not exist for the given user/group IDs it will be created. + As2KeyEntity: + type: object + properties: + id: + type: integer + description: AS2 Key ID + format: int32 + example: 1 + as2_partnership_name: + type: string + description: AS2 Partnership Name + example: Test + created_at: + type: string + description: AS2 Key created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + fingerprint: + type: string + description: Public key fingerprint + example: cf:cb:d3:26:52:6c:55:88:83:17:13:cf:e7:70:eb:1b:32:37:38:c0 + description: List As2 Keys + x-docs: | + AS2 Public keys are used by Users who want to connect an AS2 (Applicability Statement v2) compatible client. + UserCipherUseEntity: + type: object + properties: + id: + type: integer + description: UserCipherUse ID + format: int32 + example: 1 + protocol_cipher: + type: string + description: The protocol and cipher employed + example: TLSv1.2; ECDHE-RSA-AES256-GCM-SHA384 + created_at: + type: string + description: The earliest recorded use of this combination of interface + and protocol and cipher (for this user) + format: date-time + example: 2000-01-01T01:00:00Z + interface: + type: string + description: The interface accessed + example: restapi + enum: + - web + - ftp + - sftp + - dav + - desktop + - restapi + - robot + - jsapi + updated_at: + type: string + description: The most recent use of this combination of interface and protocol + and cipher (for this user) + format: date-time + example: 2000-01-01T01:00:00Z + user_id: + type: integer + description: ID of the user who performed this access + format: int32 + example: 1 + description: List User Cipher Uses + x-docs: | + This object allows you to see the exact set of encryption ciphers and protocols used by a given user. + This is most often used to support migrations from one TLS version to the next. You can query each user and determine who is still using legacy ciphers. + PermissionEntity: + type: object + properties: + id: + type: integer + description: Permission ID + format: int32 + example: 1 + path: + type: string + description: Folder path + example: "" + user_id: + type: integer + description: User ID + format: int32 + example: 1 + username: + type: string + description: User's username + example: Sser + group_id: + type: integer + description: Group ID + format: int32 + example: 0 + group_name: + type: string + description: Group name if applicable + example: "" + permission: + type: string + description: Permission type + example: full + enum: + - full + - readonly + - writeonly + - list + - history + - admin + - bundle + recursive: + type: boolean + description: Does this permission apply to subfolders? + example: true + description: List Permissions + x-docs: | + Permission objects represent the grant of permissions to a user or group. + + They are specific to a path and can be either recursive or nonrecursive into the subfolders of that path. + AppEntity: + type: object + properties: + name: + type: string + description: Name of the App + example: "" + extended_description: + type: string + description: Long form description of the App + example: "" + short_description: + type: string + description: Short description of the App + example: "" + documentation_links: + type: string + description: Collection of named links to documentation + example: Important Info => http://files.test/learn-more + icon_url: + type: string + description: App icon + example: "" + logo_url: + type: string + description: Full size logo for the App + example: "" + screenshot_list_urls: + type: string + description: Screenshots of the App + example: "" + logo_thumbnail_url: + type: string + description: Logo thumbnail for the App + example: "" + sso_strategy_type: + type: string + description: Associated SSO Strategy type, if any + example: "" + enum: + - google + - auth0 + - okta + - atlassian + - azure + - box + - dropbox + - slack + - _unused_ubuntu + - onelogin + - saml + - idaptive + - ldap + - scim + remote_server_type: + type: string + description: Associated Remote Server type, if any + example: "" + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + folder_behavior_type: + type: string + description: Associated Folder Behavior type, if any + example: "" + enum: + - webhook + - file_expiration + - auto_encrypt + - lock_subfolders + - storage_region + - serve_publicly + - create_user_folders + - remote_server_sync + - inbox + - append_timestamp + - limit_file_extensions + - limit_file_regex + - amazon_sns + - watermark + - remote_server_mount + - slack_webhook + external_homepage_url: + type: string + description: Link to external homepage + example: "" + marketing_youtube_url: + type: string + description: Marketing video page + example: "" + tutorial_youtube_url: + type: string + description: Tutorial video page + example: "" + app_type: + type: string + description: The type of the App + example: "" + enum: + - sdk + - sso + - remote_server + - folder_behavior + - client_app + - app_integration + featured: + type: boolean + description: Is featured on the App listing? + example: true + description: List Apps + x-docs: | + Apps are the API/SDK term for the various integrations provided by Files.com. + + If you have an idea for a new integration, please let us know as we are continuously adding to this list. + AutomationEntity: + type: object + properties: + id: + type: integer + description: Automation ID + format: int32 + example: 1 + automation: + type: string + description: Automation type + example: create_folder + enum: + - create_folder + - request_file + - request_move + - copy_newest_file + - delete_file + - copy_file + - move_file + trigger: + type: string + description: 'How this automation is triggered to run. One of: `realtime`, + `daily`, `custom_schedule`, `webhook`, `email`, or `action`.' + example: realtime + enum: + - realtime + - daily + - custom_schedule + - webhook + - email + - action + interval: + type: string + description: 'If trigger is `daily`, this specifies how often to run this + automation. One of: `day`, `week`, `week_end`, `month`, `month_end`, + `quarter`, `quarter_end`, `year`, `year_end`' + example: week + schedule: + type: object + properties: {} + description: If trigger is `custom_schedule`, Custom schedule description + for when the automation should be run. + example: + days_of_week: + - 0 + - 2 + - 4 + times_of_day: + - 6:30 + - 14:30 + time_zone: Eastern Time (US & Canada) + source: + type: string + description: Source Path + example: "" + destinations: + type: string + description: Destination Path + example: "" + destination_replace_from: + type: string + description: If set, this string in the destination path will be replaced + with the value in `destination_replace_to`. + example: "" + destination_replace_to: + type: string + description: If set, this string will replace the value `destination_replace_from` + in the destination filename. You can use special patterns here. + example: "" + path: + type: string + description: Path on which this Automation runs. Supports globs. + example: "" + user_id: + type: integer + description: User ID of the Automation's creator. + format: int32 + example: 1 + user_ids: + type: array + description: IDs of Users for the Automation (i.e. who to Request File from) + example: + - 1 + - 2 + items: + type: integer + format: int32 + group_ids: + type: array + description: IDs of Groups for the Automation (i.e. who to Request File + from) + example: + - 1 + - 2 + items: + type: integer + format: int32 + webhook_url: + type: string + description: If trigger is `webhook`, this is the URL of the webhook to + trigger the Automation. + example: https://app.files.com/api/webhooks/abc123 + trigger_actions: + type: string + description: If trigger is `action`, this is the list of action types on + which to trigger the automation. Valid actions are create, read, update, + destroy, move, copy + example: '[ "create" ]' + trigger_action_path: + type: string + description: If trigger is `action`, this is the path to watch for the specified + trigger actions. + example: path/to/file/or/folder + value: + type: object + properties: {} + description: A Hash of attributes specific to the automation type. + example: '{"limit": "1"}' + description: List Automations + x-docs: | + Automations allow you to automate workflows on your Files.com site. + + Automations are different from Behaviors because Behaviors are associated with a current folder, while Automations apply across your entire site. + Although Automations may have a Path specified, it can be a glob (which includes wildcards), which affects multiple folders. + Additionally, paths in Automations can refer to folders which don't yet exist. + + Automations are never removed when folders are removed, while Behaviors are removed when the associated folder is removed. + + ## Automation Triggers + Automations can be triggered in the following ways: + * `custom_schedule` : The automation will run according to the custom schedule parameters for `days_of_week` (0-based) and `times_of_day`. A time zone may be specified via `time_zone` in Rails TimeZone name format. + * `daily` : The automation will run once each day + * `realtime` : The automation will run any time a local file (not stored in a remote mount folder) is created, updated, or deleted. + * `webhook` : the automation will run when a request is sent to the corresponding webhook URL. + * `action` : The automation will run when a specific action happens, e.g. a file is created, deleted, or downloaded. + + Future enhancements will allow Automations to be triggered by an incoming email, or by other services. + + Currently, all Automation types support all triggers, with the following exceptions: The `realtime` trigger is only supported by the `Request File` and `Request Move` Automations. + We plan to add support for this trigger to all Automation types. If you have a use case for the + `realtime` trigger on an Automation that's not currently supported, please contact us and tell us more about your situation. + + + ## Automation Types + + There are currently five types of automations: Create Folder, Copy File, Delete File, Request File, and Request Move. + + + ### Create Folder + + Creates the folder with named by `destinations` in the path named by `path`. + Destination may include formatting parameters to insert the date/time into the destination name. + + Example Use case: Our business files sales tax for each division in 11 states every quarter. + I want to create the folders where those sales tax forms and data will be collected. + + I could create a Create Folder automation as follows: + + * Trigger: `daily` + * Interval: `quarter_end` + * Path: `/AccountingAndTax/SalesTax/State/*/` + * Destinations: `%Y/Quarter-ending-%m-%d` + + + ### Delete File + + Deletes the file with path matching `source` (wildcards allowed) in the path named by `path`. + + + ### Copy File + + Copies files in the folder named by `path` to the path specified in `destinations`. + If the parameter `source` exists, the automation will only fire on files matching the source (wildcards allowed). + If the parameter `limit` exists, the automation will only copy the newest `limit` files. + + + ### Move File + + Moves files in the folder named by `path` to the path specified in `destinations`. + If the parameter `source` exists, the automation will only fire on files matching the source (wildcards allowed). + If the parameter `limit` exists, the automation will only move the newest `limit` files. + + + ### Request File + + The Request File automation requests a file (optionally from a specific user) if it does not exist. + + It requests the file named in the parameter `destinations` in the path named by the parameter `path`. + If the parameter `source` exists, the automation will only fire if a file in that path exists. + Destinations may include formatting parameters that are backreferences to the path. + + Example Use case: Continuing our Sales Tax example from above, once the folders are + created for the 11 states, our Bookkeeper needs to upload a `.xlsx` file + containing the sales records for each state. + + We can create a Request File automation as follows: + + * Trigger: `realtime` + * Path: `/AccountingAndTax/SalesTax/State/*/*/*/` + * Destinations: `SalesByState-%p3-%p2-%p1` + * Group IDs: `123` (representing the Bookkeepers group) + + Note that the %p1, %p2 amd %p3 are references back into the folder hierarchy + (parent 1, parent 2, etc), so that the file will be named with the state + name and the quarter name in the file. Example: `SalesByState-NV-2017-Quarter-ending-Dec-31.xlsx` + + Now, let's say that our Tax Accountant is in charge of filing the actual + state tax return once the Excel doc is completed by the Bookkeeper. We + can create another Automation to let him know when it's his turn + to operate: + + * Trigger: `realtime` + * Path: `/AccountingAndTax/SalesTax/State/*/*/%/` + * Source: `SalesByState-%p3-%p2-%p1` + * Destinations: `StateSalesTaxReturn-Unsigned-%p3-%p2-%p1` + * Group IDs: `124` (representing the Tax Accountants group) + Group: Tax Accountants + + So the accountant will take the excel from the bookkeeper, generate the + state tax return, and then upload it as a PDF, ready for the CFO to + sign. How does the CFO know when to sign? You guessed it, another + Automation will let him know when it's ready: + + * Trigger: `realtime` + * Path: `/AccountingAndTax/**/` + * Source: `*-Unsigned-*` + * Destination Replace From: `-Unsigned-` + * Destination Replace To: `-Signed-` + * Group IDs: `125` (representing the CFO group) + + This Automation looks in every nested subfolder of `AcccountingAndTax` + (that's the `/**/` in the path). And it looks for any filename containing + the filename string `-Unsigned-`. That's the cue to the CFO that something needs his + signature. + + Rather than specifying the exact destination filename, we can specify a Destination Replace From + and To in order to generate the new filename from the old filename. + + So if `StateSalesTaxReturn-Unsigned-NV-2017-q4.pdf` is uploaded, this + Automation will trigger and expect the file `StateSalesTaxReturn-Signed-NV-2017-q4.pdf` + from the CFO. + + You could then put in place another rule for the Tax Accountant or + Bookkeeper to go do the actual filing once a signature is in place. + + + ### Request Move + + The Request Move automation requests that a file be moved. This is an alternate way to implement approval workflows. + + A variant of the Request File automation, this Automation creates requests that a + user or group move a file, presumably indicating that they've taken some action on it. + + Example Use case: Action Verb uses Files.com to collect invoices from its Contractors, who + upload new invoices into their own folder structure that only they have + permissions to. That structure looks like this: + + * `/Accounts Payable/Contractors/[contractor]/New/` + * `/Accounts Payable/Contractors/[contractor]/Paid/` + + The contractor has full permissions to the `New/` folder, but only + read-only permissions to `Paid/`. This allows them to upload and update + new invoices, but only view invoices that are already paid. (Cool!) + + But, as we grow to dozens of contractors, it becomes a tough task for + Accounts Payable to check all the New folders daily. + + To ensure Contractors get paid timely, we might set up Request Move automation: + + * Trigger: `realtime` + * Path: `/AccountsPayable/Contractors/*/New/` + * Source: `*` + * Destinations: `../Paid/` + * Group IDs: `126` (representing the Accounts Payable group) + + + ### Help us build the future of Automations + + Do you have an idea for something that would work well as a Files.com Automation? Let us know! + We are actively improving the types of automations offered on our platform. + BandwidthSnapshotEntity: + type: object + properties: + id: + type: integer + description: Site bandwidth ID + format: int32 + example: 1 + bytes_received: + type: number + description: Site bandwidth report bytes received + format: double + example: 1.0 + bytes_sent: + type: number + description: Site bandwidth report bytes sent + format: double + example: 1.0 + sync_bytes_received: + type: number + description: Site sync bandwidth report bytes received + format: double + example: 1.0 + sync_bytes_sent: + type: number + description: Site sync bandwidth report bytes sent + format: double + example: 1.0 + requests_get: + type: number + description: Site bandwidth report get requests + format: double + example: 1.0 + requests_put: + type: number + description: Site bandwidth report put requests + format: double + example: 1.0 + requests_other: + type: number + description: Site bandwidth report other requests + format: double + example: 1.0 + logged_at: + type: string + description: Time the site bandwidth report was logged + format: date-time + example: 2000-01-01T01:00:00Z + created_at: + type: string + description: Site bandwidth report created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + updated_at: + type: string + description: The last time this site bandwidth report was updated + format: date-time + example: 2000-01-01T01:00:00Z + description: List Bandwidth Snapshots + x-docs: null + BehaviorEntity: + type: object + properties: + id: + type: integer + description: Folder behavior ID + format: int32 + example: 1 + path: + type: string + description: Folder path + example: "" + attachment_url: + type: string + description: URL for attached file + example: "" + behavior: + type: string + description: Behavior type. + example: webhook + value: + type: object + properties: {} + description: Settings for this behavior. See the section above for an example + value to provide here. Formatting is different for each Behavior type. May + be sent as nested JSON or a single JSON-encoded string. If using XML + encoding for the API call, this data must be sent as a JSON-encoded string. + example: '{ "method": "GET" }' + description: List Behaviors + x-docs: | + Behaviors are the API resource for what are also known as Folder Settings. Every behavior is associated with a folder. + + Depending on the behavior, it may also operate on child folders. It may be overridable at the child folder level or maybe can be added to at the child folder level. The exact options for each behavior type are explained in the table below. + + Additionally, some behaviors are visible to non-admins, and others are even settable by non-admins. All the details are below. + + Each behavior uses a different format for storings its settings value. Next to each behavior type is an example value. Our API and SDKs currently require that the value for behaviors be sent as raw JSON within the `value` field. Our SDK generator and API documentation generator doesn't fully keep up with this requirement, so if you need any help finding the exact syntax to use for your language or use case, just reach out. + BundleEntity: + type: object + properties: + code: + type: string + description: Bundle code. This code forms the end part of the Public URL. + example: abc123 + url: + type: string + description: Public URL of Share Link + example: https://subdomain.files.com/f/12345678 + description: + type: string + description: Public description + example: The public description of the bundle. + password_protected: + type: boolean + description: Is this bundle password protected? + preview_only: + type: boolean + description: Restrict users to previewing files only? + require_registration: + type: boolean + description: Show a registration page that captures the downloader's name + and email address? + require_share_recipient: + type: boolean + description: Only allow access to recipients who have explicitly received + the share via an email sent through the Files.com UI? + clickwrap_body: + type: string + description: Legal text that must be agreed to prior to accessing Bundle. + example: '[Legal text]' + form_field_set: + $ref: '#/components/schemas/FormFieldSetEntity' + id: + type: integer + description: Bundle ID + format: int32 + example: 1 + created_at: + type: string + description: Bundle created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + expires_at: + type: string + description: Bundle expiration date/time + format: date-time + example: 2000-01-01T01:00:00Z + max_uses: + type: integer + description: Maximum number of times bundle can be accessed + format: int32 + example: 1 + note: + type: string + description: Bundle internal note + example: The internal note on the bundle. + user_id: + type: integer + description: Bundle creator user ID + format: int32 + example: 1 + username: + type: string + description: Bundle creator username + example: user + clickwrap_id: + type: integer + description: ID of the clickwrap to use with this bundle. + format: int32 + example: 1 + inbox_id: + type: integer + description: ID of the associated inbox, if available. + format: int32 + example: 1 + has_inbox: + type: boolean + description: Does this bundle have an associated inbox? + example: true + paths: + type: array + description: A list of paths in this bundle + example: + - file.txt + items: + type: string + example: "" + description: Create Bundle + x-docs: | + Bundles are the API/SDK term for the feature called Share Links in the web interface. + The API provides the full set of actions related to Share Links, including sending them via E-Mail. + + Please note that we very closely monitor the E-Mailing feature and any abuse will result in disabling of your site. + FormFieldSetEntity: + type: object + properties: + id: + type: integer + description: Form field set id + format: int32 + example: 1 + title: + type: string + description: Title to be displayed + example: Sample Form Title + form_layout: + type: integer + description: Layout of the form + format: int32 + form_fields: + description: Form fields + $ref: '#/components/schemas/FormFieldEntity' + skip_name: + type: boolean + description: Any associated InboxRegistrations or BundleRegistrations can + be saved without providing name + example: true + skip_email: + type: boolean + description: Any associated InboxRegistrations or BundleRegistrations can + be saved without providing email + example: true + skip_company: + type: boolean + description: Any associated InboxRegistrations or BundleRegistrations can + be saved without providing company + example: true + description: Create Form Field Set + x-docs: | + Form Field Sets define a custom forms to be used for bundle and inbox registrations. + + Each Form Field Set contains one or more Form Fields. A form and all of its form fields are submitted in a single create request. The order of form fields in the array is the order they will be displayed. + + Once created, a form field set can then be associated with one or more bundle(s) and/or inbox(s). Once associated, you will be required to submit well-formatted form-data when creating a bundle-registration or inbox registration. + FormFieldEntity: + description: Form fields + type: object + properties: + id: + type: integer + description: Form field id + format: int32 + example: 1 + label: + type: string + description: Label to be displayed + example: Sample Label + required: + type: boolean + description: Is this a required field? + example: true + help_text: + type: string + description: Help text to be displayed + example: Help Text + field_type: + type: string + description: Type of Field + example: text + enum: + - text + - text_area + - dropdown + - radio + options_for_select: + type: string + description: Options to display for radio and dropdown + example: "" + default_option: + type: string + description: Default option for radio and dropdown + example: red + form_field_set_id: + type: integer + description: Form field set id + format: int32 + example: 1 + x-docs: null + BundleDownloadEntity: + type: object + properties: + bundle_registration: + $ref: '#/components/schemas/BundleRegistrationEntity' + download_method: + type: string + description: Download method (file or full_zip) + example: file + enum: + - file + - full_zip + path: + type: string + description: Download path + example: a/b/test.txt + created_at: + type: string + description: Download date/time + format: date-time + description: List Bundle Downloads + x-docs: null + BundleRegistrationEntity: + type: object + properties: + code: + type: string + description: Registration cookie code + example: abc123 + name: + type: string + description: Registrant name + example: account + company: + type: string + description: Registrant company name + example: Action Verb + email: + type: string + description: Registrant email address + example: john.doe@files.com + ip: + type: string + description: Registrant IP Address + example: 10.1.1.1 + inbox_code: + type: string + description: InboxRegistration cookie code, if there is an associated InboxRegistration + example: abc123 + clickwrap_body: + type: string + description: Clickwrap text that was shown to the registrant + example: "" + form_field_set_id: + type: integer + description: Id of associated form field set + format: int32 + example: 1 + form_field_data: + type: string + description: Data for form field set with form field ids as keys and user + data as values + example: "" + description: List Bundle Registrations + x-docs: | + BundleRegistrations record when a Bundle user fills out the form to access the bundle. + BundleRecipientEntity: + type: object + properties: + company: + type: string + description: The recipient's company. + example: Acme Inc. + name: + type: string + description: The recipient's name. + example: John Doe + note: + type: string + description: A note sent to the recipient with the bundle. + example: Some note. + recipient: + type: string + description: The recipient's email address. + example: john.doe@example.com + sent_at: + type: string + description: When the Bundle was shared with this recipient. + format: date-time + example: 2000-01-01T01:00:00Z + description: List Bundle Recipients + x-docs: | + Bundle recipients are people who have had a bundle shared with them. A Bundle can be re-shared + with a BundleRecipient by sending a create request with the inbox_id, recipient email address, + and share_after_create => true. + ClickwrapEntity: + type: object + properties: + id: + type: integer + description: Clickwrap ID + format: int32 + example: 1 + name: + type: string + description: Name of the Clickwrap agreement (used when selecting from multiple + Clickwrap agreements.) + example: Example Site NDA for Files.com Use + body: + type: string + description: Body text of Clickwrap (supports Markdown formatting). + example: '[Legal body text]' + use_with_users: + type: string + description: 'Use this Clickwrap for User Registrations? Note: This only + applies to User Registrations where the User is invited to your Files.com + site using an E-Mail invitation process where they then set their own + password.' + example: "" + enum: + - none + - require + use_with_bundles: + type: string + description: Use this Clickwrap for Bundles? + example: "" + enum: + - none + - available + - require + use_with_inboxes: + type: string + description: Use this Clickwrap for Inboxes? + example: "" + enum: + - none + - available + - require + description: Create Clickwrap + x-docs: | + A Clickwrap is a legal agreement (such as an NDA or Terms of Use) that your Users and/or Bundle/Inbox participants will need to agree to via a "Clickwrap" UI before accessing the site, bundle, or inbox. + ExternalEventEntity: + type: object + properties: + id: + type: integer + description: Event ID + format: int32 + example: 1 + event_type: + type: string + description: Type of event being recorded. + example: "" + enum: + - ldap_sync + - remote_server_sync + - lockout + - ldap_login + - saml_login + - client_log + - pending_work + status: + type: string + description: Status of event. + example: "" + enum: + - success + - error + - partial_failure + body: + type: string + description: Event body + example: "" + created_at: + type: string + description: External event create date/time + format: date-time + example: 2000-01-01T01:00:00Z + body_url: + type: string + description: Link to log file. + example: "" + folder_behavior_id: + type: integer + description: Folder Behavior ID + format: int32 + example: 1 + successful_files: + type: integer + description: For sync events, the number of files handled successfully. + format: int32 + example: 1 + errored_files: + type: integer + description: For sync events, the number of files that encountered errors. + format: int32 + example: 1 + bytes_synced: + type: integer + description: For sync events, the total number of bytes synced. + format: int32 + example: 1 + remote_server_type: + type: string + description: Associated Remote Server type, if any + example: "" + description: List External Events + x-docs: | + ExternalEvents record activity such as logins, credential syncs, and lockouts. + FileEntity: + type: object + properties: + path: + type: string + description: File/Folder path + example: path/file.txt + display_name: + type: string + description: File/Folder display name + example: file.txt + type: + type: string + description: 'Type: `directory` or `file`.' + example: file + size: + type: integer + description: File/Folder size + format: int32 + example: 1024 + mtime: + type: string + description: File last modified date/time, according to the server. This + is the timestamp of the last Files.com operation of the file, regardless + of what modified timestamp was sent. + format: date-time + example: 2000-01-01T01:00:00Z + provided_mtime: + type: string + description: File last modified date/time, according to the client who set + it. Files.com allows desktop, FTP, SFTP, and WebDAV clients to set modified + at times. This allows Desktop<->Cloud syncing to preserve modified at + times. + format: date-time + example: 2000-01-01T01:00:00Z + crc32: + type: string + description: File CRC32 checksum. This is sometimes delayed, so if you get + a blank response, wait and try again. + example: "70976923" + md5: + type: string + description: File MD5 checksum. This is sometimes delayed, so if you get + a blank response, wait and try again. + example: 17c54824e9931a4688ca032d03f6663c + mime_type: + type: string + description: MIME Type. This is determined by the filename extension and + is not stored separately internally. + example: application/octet-stream + region: + type: string + description: Region location + example: us-east-1 + permissions: + type: string + description: A short string representing the current user's permissions. Can + be `r`,`w`,`p`, or any combination + example: rpw + subfolders_locked: + type: boolean + description: Are subfolders locked and unable to be modified? + example: true + download_uri: + type: string + description: Link to download file. Provided only in response to a download + request. + example: https://mysite.files.com/... + priority_color: + type: string + description: Bookmark/priority color of file/folder + example: red + preview_id: + type: integer + description: File preview ID + format: int32 + example: 1 + preview: + description: File preview + $ref: '#/components/schemas/PreviewEntity' + description: List Folders by path + x-docs: null + PreviewEntity: + description: File preview + type: object + properties: + id: + type: integer + description: Preview ID + format: int32 + example: 1 + status: + type: string + description: Preview status. Can be invalid, not_generated, generating, + complete, or file_too_large + example: complete + download_uri: + type: string + description: Link to download preview + example: https://mysite.files.com/... + type: + type: string + description: Preview status. Can be invalid, not_generated, generating, + complete, or file_too_large + example: complete + size: + type: integer + description: Preview size + format: int32 + example: 1024 + x-docs: | + Previews are image or PDF previews that are meant to be viewed within the web interface. + FileActionEntity: + type: object + properties: + status: + type: string + description: 'Status of file operation. Possible values: completed, enqueued.' + example: enqueued + file_migration_id: + type: integer + description: If status is enqueued, this is the id of the FileMigration + to check for status updates. + format: int32 + example: 123 + description: Move file/folder + x-docs: null + FileUploadPartEntity: + type: object + properties: + send: + type: object + properties: {} + description: Content-Type and File to send + example: {} + action: + type: string + description: Type of upload + example: multipart + ask_about_overwrites: + type: boolean + description: If `true`, this file exists and you may wish to ask the user + for overwrite confirmation + example: true + available_parts: + type: integer + description: Number of parts in the upload + format: int32 + example: 1 + expires: + type: string + description: Date/time of when this Upload part expires and the URL cannot + be used any more + example: "" + headers: + type: object + properties: {} + description: Additional upload headers to provide as part of the upload + example: {} + http_method: + type: string + description: HTTP Method to use for uploading the part, usually `PUT` + example: PUT + next_partsize: + type: integer + description: Size in bytes for this part + format: int32 + example: 1 + parallel_parts: + type: boolean + description: If `true`, multiple parts may be uploaded in parallel. If + `false`, be sure to only upload one part at a time, in order. + example: true + parameters: + type: object + properties: {} + description: Additional HTTP parameters to send with the upload + example: '{}' + part_number: + type: integer + description: Number of this upload part + format: int32 + example: 1 + partsize: + type: integer + description: Size in bytes for the next upload part + format: int32 + example: 1 + path: + type: string + description: New file path + example: path + ref: + type: string + description: Reference name for this upload part + example: upload-1 + upload_uri: + type: string + description: URI to upload this part to + example: "" + description: Begin file upload + x-docs: null + FileCommentEntity: + type: object + properties: + id: + type: integer + description: File Comment ID + format: int32 + example: 1 + body: + type: string + description: Comment body. + example: What a great file! + reactions: + $ref: '#/components/schemas/FileCommentReactionEntity' + description: List File Comments by path + x-docs: | + File Comments are comments attached to a file by a user. + FileCommentReactionEntity: + type: object + properties: + id: + type: integer + description: Reaction ID + format: int32 + example: 1 + emoji: + type: string + description: Emoji used in the reaction. + example: 👍 + description: Create File Comment Reaction + x-docs: | + File Comment Reactionss are reactions that are attached to a comment on a file. + FileMigrationEntity: + type: object + properties: + id: + type: integer + description: File migration ID + format: int32 + example: 1 + path: + type: string + description: Source path + example: MyFolder + dest_path: + type: string + description: Destination path + example: MyFolder + files_moved: + type: integer + description: Number of files processed + format: int32 + example: 1 + files_total: + type: integer + description: Total number of files to process + format: int32 + example: 1 + operation: + type: string + description: The type of operation + example: move + enum: + - delete + - move + - copy + region: + type: string + description: Region + example: USA + status: + type: string + description: Status + example: complete + enum: + - pending + - counting + - processing + - complete + - processing_subfolders + - finishing + - creating_dest_folder + - waiting_for_other_jobs + - waiting_for_all_files + - waiting_for_pending_subfolders + - waiting_for_all_subfolders + - failed + - waiting_for_enqueued_operations + - processing_deferred_folders + - processing_recursively + - removing_deferred_folders + log_url: + type: string + description: Link to download the log file for this migration. + example: https://www.example.com/log_file + description: Show File Migration + x-docs: | + FileMigrations represent background operations on one or more files, such as a copy or a region migration. + + If no `operation` or `dest_path` is present, then the record represents a region migration. + patchFormFieldSets: + type: object + properties: + title: + type: string + description: Title to be displayed + skip_email: + type: boolean + description: Skip validating form email + skip_name: + type: boolean + description: Skip validating form name + skip_company: + type: boolean + description: Skip validating company + form_fields: + description: Form fields + type: array + items: + type: object + properties: + id: + type: integer + description: Id of existing Form Field + format: int32 + label: + type: string + description: Label of Field + field_type: + type: string + description: 'Type of field: text, text_area, dropdown, or radio' + help_text: + type: string + description: Help text of field + required: + type: boolean + description: Is this a required field? (default true) + options_for_select: + type: string + description: List of options for dropdown or radio + default_option: + type: string + description: Default option to be preselected in the dropdown or radio. + description: Update Form Field Set + postFormFieldSets: + type: object + properties: + user_id: + type: integer + description: User ID. Provide a value of `0` to operate the current session's + user. + format: int32 + title: + type: string + description: Title to be displayed + skip_email: + type: boolean + description: Skip validating form email + skip_name: + type: boolean + description: Skip validating form name + skip_company: + type: boolean + description: Skip validating company + form_fields: + description: Form fields + type: array + items: + type: object + properties: + id: + type: integer + description: Id of existing Form Field + format: int32 + label: + type: string + description: Label of Field + field_type: + type: string + description: 'Type of field: text, text_area, dropdown, or radio' + help_text: + type: string + description: Help text of field + required: + type: boolean + description: Is this a required field? (default true) + options_for_select: + type: string + description: List of options for dropdown or radio + default_option: + type: string + description: Default option to be preselected in the dropdown or radio. + description: Create Form Field Set + GroupEntity: + type: object + properties: + id: + type: integer + description: Group ID + format: int32 + example: 1 + name: + type: string + description: Group name + example: owners + admin_ids: + type: string + description: List of user IDs who are group administrators (separated by + commas) + example: "" + notes: + type: string + description: Notes about this group + example: "" + user_ids: + type: array + description: List of user IDs who belong to this group (separated by commas) + example: + - 1 + items: + type: integer + format: int32 + usernames: + type: array + description: List of usernames who belong to this group (separated by commas) + example: + - user + items: + type: string + example: "" + description: List Groups + x-docs: | + Groups are a powerful tool for permissions and user management on Files.com. Users can belong to multiple groups. + + All permissions can be managed via Groups, and Groups can also be synced to your identity platform via LDAP or SCIM. + + Files.com's Group Admin feature allows you to define Group Admins, who then have access to add and remove users within their groups. + ActionEntity: + type: object + properties: + id: + type: integer + description: Action ID + format: int32 + example: 1 + path: + type: string + description: Path + example: path + when: + type: string + description: Action occurrence date/time + format: date-time + example: 2000-01-01T01:00:00Z + destination: + type: string + description: The destination path for this action, if applicable + example: /to_path + display: + type: string + description: Friendly displayed output + example: Actual text of the action here. + ip: + type: string + description: IP Address that performed this action + example: 192.283.128.182 + source: + type: string + description: The source path for this action, if applicable + example: /from_path + targets: + type: array + description: Targets + example: [] + items: + type: string + example: "" + user_id: + type: integer + description: User ID + format: int32 + example: 1 + username: + type: string + description: Username + example: user + action: + type: string + description: Type of action + example: create + enum: + - create + - read + - update + - destroy + - move + - login + - failedlogin + - copy + - user_create + - user_update + - user_destroy + - group_create + - group_update + - group_destroy + - permission_create + - permission_destroy + - api_key_create + - api_key_update + - api_key_destroy + failure_type: + type: string + description: Failure type. If action was a user login or session failure, + why did it fail? + example: none + enum: + - expired_trial + - account_overdue + - locked_out + - ip_mismatch + - password_mismatch + - site_mismatch + - username_not_found + - none + - no_ftp_permission + - no_web_permission + - no_directory + - errno_enoent + - no_sftp_permission + - no_dav_permission + - no_restapi_permission + - key_mismatch + - region_mismatch + - expired_access + - desktop_ip_mismatch + - desktop_api_key_not_used_quickly_enough + - disabled + - country_mismatch + interface: + type: string + description: Interface on which this action occurred. + example: web + enum: + - web + - ftp + - robot + - jsapi + - webdesktopapi + - sftp + - dav + - desktop + - restapi + - scim + - office + - mobile + description: List site full action history. + x-docs: | + All File and Login actions on Files.com are recorded and can be queried via our History API. + + This set of endpoints only provides access to recent actions (actions created within 24 hours). In most cases, + you would be better served to create a Webhook, which sends actions to your server, rather than poll this endpoint. + + The HistoryExport set of endpoints provides a richer ability to query and filter, as well as search the entire + lifetime of your history log. + HistoryExportEntity: + type: object + properties: + id: + type: integer + description: History Export ID + format: int32 + example: 1 + history_version: + type: string + description: Version of the history for the export. + example: "20201213.2" + start_at: + type: string + description: Start date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + end_at: + type: string + description: End date/time of export range. + format: date-time + example: 2000-01-01T01:00:00Z + status: + type: string + description: 'Status of export. Will be: `building`, `ready`, or `failed`' + example: ready + query_action: + type: string + description: 'Filter results by this this action type. Valid values: `create`, + `read`, `update`, `destroy`, `move`, `login`, `failedlogin`, `copy`, `user_create`, + `user_update`, `user_destroy`, `group_create`, `group_update`, `group_destroy`, + `permission_create`, `permission_destroy`, `api_key_create`, `api_key_update`, + `api_key_destroy`' + example: read + query_interface: + type: string + description: 'Filter results by this this interface type. Valid values: + `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, `dav`, `desktop`, + `restapi`, `scim`, `office`, `mobile`' + example: ftp + query_user_id: + type: string + description: Return results that are actions performed by the user indiciated + by this User ID + example: "1" + query_file_id: + type: string + description: Return results that are file actions related to the file indicated + by this File ID + example: "1" + query_parent_id: + type: string + description: Return results that are file actions inside the parent folder + specified by this folder ID + example: "1" + query_path: + type: string + description: Return results that are file actions related to this path. + example: MyFile.txt + query_folder: + type: string + description: Return results that are file actions related to files or folders + inside this folder path. + example: Folder + query_src: + type: string + description: Return results that are file moves originating from this path. + example: SrcFolder + query_destination: + type: string + description: Return results that are file moves with this path as destination. + example: DestFolder + query_ip: + type: string + description: Filter results by this IP address. + example: 127.0.0.1 + query_username: + type: string + description: Filter results by this username. + example: jerry + query_failure_type: + type: string + description: 'If searching for Histories about login failures, this parameter + restricts results to failures of this specific type. Valid values: `expired_trial`, + `account_overdue`, `locked_out`, `ip_mismatch`, `password_mismatch`, `site_mismatch`, + `username_not_found`, `none`, `no_ftp_permission`, `no_web_permission`, + `no_directory`, `errno_enoent`, `no_sftp_permission`, `no_dav_permission`, + `no_restapi_permission`, `key_mismatch`, `region_mismatch`, `expired_access`, + `desktop_ip_mismatch`, `desktop_api_key_not_used_quickly_enough`, `disabled`, + `country_mismatch`' + example: bad_password + query_target_id: + type: string + description: If searching for Histories about specific objects (such as + Users, or API Keys), this paremeter restricts results to objects that + match this ID. + example: "1" + query_target_name: + type: string + description: If searching for Histories about Users, Groups or other objects + with names, this parameter restricts results to objects with this name/username. + example: full + query_target_permission: + type: string + description: If searching for Histories about Permisisons, this parameter + restricts results to permissions of this level. + example: full + query_target_user_id: + type: string + description: If searching for Histories about API keys, this parameter restricts + results to API keys created by/for this user ID. + example: "1" + query_target_username: + type: string + description: If searching for Histories about API keys, this parameter restricts + results to API keys created by/for this username. + example: jerry + query_target_platform: + type: string + description: If searching for Histories about API keys, this parameter restricts + results to API keys associated with this platform. + example: windows + query_target_permission_set: + type: string + description: If searching for Histories about API keys, this parameter restricts + results to API keys with this permission set. + example: desktop_app + results_url: + type: string + description: If `status` is `ready`, this will be a URL where all the results + can be downloaded at once as a CSV. + example: https://files.com/history_results.csv + description: Show History Export + x-docs: | + The History Export resource on the API is used to export historical action (history) logs. + + All queries against the archive must be submitted as Exports. (Even our Web UI creates an Export behind + the scenes.) + + We use Amazon Athena behind the scenes for processing these queries, and as such, have powerful + search capabilities. We've done our best to expose search capabilities via this History Export API. + + In any query field in this API, you may specify multiple values separated by commas. That means that commas + cannot be searched for themselves, and neither can single quotation marks. + + We do not currently partition data by date on the backend, so all queries result in a full scan of the entire + data lake. This means that all queries will take about the same amount of time to complete, and we incur about + the same cost per query internally. We don't typically bill our customers for these queries, assuming + usage is occasional and manual. + + If you intend to use this API for high volume or automated use, please contact us with more information + about your use case. We may decide to change the backend data schema to match your use case more closely, and + we may also need to charge an additional cost per query. + + ## Example History Queries + + * History for a user: `{ "query_user_id": 123 }` + * History for a range of time: `{ "start_at": "2021-03-18 12:00:00", "end_at": "2021-03-19 12:00:00" }` + * History of logins and failed logins: `{ "query_action": "login,failedlogin" }` + * A Complex query: `{ "query_folder": "uploads", "query_action": "create,copy,move", "start_at": "2021-03-18 12:00:00", "end_at": "2021-03-19 12:00:00" }` + HistoryExportResultEntity: + type: object + properties: + id: + type: integer + description: Action ID + format: int32 + example: 1 + created_at: + type: integer + description: When the action happened + format: int32 + example: 1 + user_id: + type: integer + description: User ID + format: int32 + example: 1 + file_id: + type: integer + description: File ID related to the action + format: int32 + example: 1 + parent_id: + type: integer + description: ID of the parent folder + format: int32 + example: 1 + path: + type: string + description: Path of the related action + example: MyFile.txt + folder: + type: string + description: Folder in which the action occurred + example: Folder + src: + type: string + description: File move originated from this path + example: SrcFolder + destination: + type: string + description: File moved to this destination folder + example: DestFolder + ip: + type: string + description: Client IP that performed the action + example: 127.0.0.1 + username: + type: string + description: Username of the user that performed the action + example: jerry + action: + type: string + description: 'What action was taken. Valid values: `create`, `read`, `update`, + `destroy`, `move`, `login`, `failedlogin`, `copy`, `user_create`, `user_update`, + `user_destroy`, `group_create`, `group_update`, `group_destroy`, `permission_create`, + `permission_destroy`, `api_key_create`, `api_key_update`, `api_key_destroy`' + example: read + failure_type: + type: string + description: 'The type of login failure, if applicable. Valid values: `expired_trial`, + `account_overdue`, `locked_out`, `ip_mismatch`, `password_mismatch`, `site_mismatch`, + `username_not_found`, `none`, `no_ftp_permission`, `no_web_permission`, + `no_directory`, `errno_enoent`, `no_sftp_permission`, `no_dav_permission`, + `no_restapi_permission`, `key_mismatch`, `region_mismatch`, `expired_access`, + `desktop_ip_mismatch`, `desktop_api_key_not_used_quickly_enough`, `disabled`, + `country_mismatch`' + example: bad_password + interface: + type: string + description: 'Inteface through which the action was taken. Valid values: + `web`, `ftp`, `robot`, `jsapi`, `webdesktopapi`, `sftp`, `dav`, `desktop`, + `restapi`, `scim`, `office`, `mobile`' + example: ftp + target_id: + type: integer + description: ID of the object (such as Users, or API Keys) on which the + action was taken + format: int32 + example: 1 + target_name: + type: string + description: Name of the User, Group or other object with a name related + to this action + example: full + target_permission: + type: string + description: Permission level of the action + example: full + target_recursive: + type: boolean + description: Whether or not the action was recursive + example: true + target_expires_at: + type: integer + description: If searching for Histories about API keys, this is when the + API key will expire + format: int32 + example: 1 + target_permission_set: + type: string + description: If searching for Histories about API keys, this represents + the permission set of the associated API key + example: desktop_app + target_platform: + type: string + description: If searching for Histories about API keys, this is the platform + on which the action was taken + example: windows + target_username: + type: string + description: If searching for Histories about API keys, this is the username + on which the action was taken + example: jerry + target_user_id: + type: integer + description: If searching for Histories about API keys, this is the User + ID on which the action was taken + format: int32 + example: 1 + description: List History Export Results + x-docs: null + InboxRecipientEntity: + type: object + properties: + company: + type: string + description: The recipient's company. + example: Acme Inc. + name: + type: string + description: The recipient's name. + example: John Doe + note: + type: string + description: A note sent to the recipient with the inbox. + example: Some note. + recipient: + type: string + description: The recipient's email address. + example: john.doe@example.com + sent_at: + type: string + description: When the Inbox was shared with this recipient. + format: date-time + example: 2000-01-01T01:00:00Z + description: List Inbox Recipients + x-docs: | + Inbox recipients are people who have had an inbox shared with them. + InboxRegistrationEntity: + type: object + properties: + code: + type: string + description: Registration cookie code + example: abc123 + name: + type: string + description: Registrant name + example: account + company: + type: string + description: Registrant company name + example: Action Verb + email: + type: string + description: Registrant email address + example: john.doe@files.com + clickwrap_body: + type: string + description: Clickwrap text that was shown to the registrant + example: "" + form_field_set_id: + type: integer + description: Id of associated form field set + format: int32 + example: 1 + form_field_data: + type: string + description: Data for form field set with form field ids as keys and user + data as values + example: "" + description: List Inbox Registrations + x-docs: | + InboxRegistrations record when an Inbox user fills out the form to access the inbox. + InboxUploadEntity: + type: object + properties: + inbox_registration: + $ref: '#/components/schemas/InboxRegistrationEntity' + path: + type: string + description: Upload path + example: a/b/test.txt + created_at: + type: string + description: Upload date/time + format: date-time + description: List Inbox Uploads + x-docs: null + AccountLineItemEntity: + type: object + properties: + id: + type: integer + description: Line item Id + format: int32 + example: 1 + amount: + type: number + description: Line item amount + format: double + example: 1.0 + balance: + type: number + description: Line item balance + format: double + example: 1.0 + created_at: + type: string + description: Line item created at + format: date-time + example: 2000-01-01T01:00:00Z + currency: + type: string + description: Line item currency + example: USD + download_uri: + type: string + description: Line item download uri + example: https://url... + invoice_line_items: + description: Associated invoice line items + $ref: '#/components/schemas/InvoiceLineItemEntity' + method: + type: string + description: Line item payment method + example: paypal + payment_line_items: + description: Associated payment line items + $ref: '#/components/schemas/PaymentLineItemEntity' + payment_reversed_at: + type: string + description: Date/time payment was reversed if applicable + format: date-time + example: 2000-01-01T01:00:00Z + payment_type: + type: string + description: Type of payment if applicable + example: "" + site_name: + type: string + description: Site name this line item is for + example: My Site + type: + type: string + description: Type of line item, either payment or invoice + example: invoice + updated_at: + type: string + description: Line item updated at + format: date-time + example: 2000-01-01T01:00:00Z + description: List Payments + x-docs: null + InvoiceLineItemEntity: + description: Associated invoice line items + type: object + properties: + amount: + type: number + description: Invoice line item amount + format: double + example: 1.0 + created_at: + type: string + description: Invoice line item created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + description: + type: string + description: Invoice line item description + example: Service from 2019-01-01 through 2019-12-31 + type: + type: string + description: Invoice line item type + example: invoice + enum: + - invoice + - adjustment + - usage_overage + - user_overage + - addon_subscription + - misc_fee + service_end_at: + type: string + description: Invoice line item service end date/time + format: date-time + example: 2000-01-01T01:00:00Z + service_start_at: + type: string + description: Invoice line item service start date/time + format: date-time + example: 2000-01-01T01:00:00Z + updated_at: + type: string + description: Invoice line item updated date/time + format: date-time + example: 2000-01-01T01:00:00Z + plan: + type: string + description: Plan name + example: Enterprise + site: + type: string + description: Site name + example: My site + x-docs: null + PaymentLineItemEntity: + description: Associated payment line items + type: object + properties: + amount: + type: number + description: Payment line item amount + format: double + example: 1.0 + created_at: + type: string + description: Payment line item created at date/time + format: date-time + example: 2000-01-01T01:00:00Z + invoice_id: + type: integer + description: Invoice ID + format: int32 + example: 1 + payment_id: + type: integer + description: Payment ID + format: int32 + example: 1 + updated_at: + type: string + description: Payment line item updated at date/time + format: date-time + example: 2000-01-01T01:00:00Z + x-docs: null + PublicIpAddressEntity: + type: object + properties: + ip_address: + type: string + description: The public IP address. + example: 1.1.1.1 + server_name: + type: string + description: The name of the frontend server. + example: server-1 + description: List all possible public IP addresses + x-docs: These are all IP addresses that `app.files.com` (or `*.files.com`) may + potentially resolve to over the next 30 days. This list includes IP addresses + that are hot standbys not in use. + LockEntity: + type: object + properties: + path: + type: string + description: Path + example: locked_file + timeout: + type: integer + description: Lock timeout in seconds + format: int32 + example: 43200 + depth: + type: string + description: 'DEPRECATED: Lock depth' + example: infinity + recursive: + type: boolean + description: Does lock apply to subfolders? + example: true + owner: + type: string + description: Owner of the lock. This can be any arbitrary string. + example: user + scope: + type: string + description: 'DEPRECATED: Lock scope' + example: shared + exclusive: + type: boolean + description: Is lock exclusive? + token: + type: string + description: Lock token. Use to release lock. + example: 17c54824e9931a4688ca032d03f6663c + type: + type: string + description: 'DEPRECATED: Lock type' + example: write + allow_access_by_any_user: + type: boolean + description: Can lock be modified by users other than its creator? + user_id: + type: integer + description: Lock creator user ID + format: int32 + example: 1 + username: + type: string + description: Lock creator username + example: username + description: List Locks by path + x-docs: | + Locks are not used by Files.com's web interface, but can be used by your applications to + implement locking and concurrency features. Note that these locks are advisory in nature, + and creating a lock does not prevent other API requests from being fulfilled. + + Our lock feature is designed to emulate the locking feature offered by WebDAV. + You can read the WebDAV spec and understand how all of the below endpoints work. + + Files.com's WebDAV offering and desktop app does leverage this locking API. + MessageEntity: + type: object + properties: + id: + type: integer + description: Message ID + format: int32 + example: 1 + subject: + type: string + description: Message subject. + example: Files.com Account Upgrade + body: + type: string + description: Message body. + example: We should upgrade our Files.com account! + comments: + $ref: '#/components/schemas/MessageCommentEntity' + description: List Messages + x-docs: | + Messages are part of Files.com's project management features and represent a message posted by a user to a project. + MessageCommentEntity: + type: object + properties: + id: + type: integer + description: Message Comment ID + format: int32 + example: 1 + body: + type: string + description: Comment body. + example: What a great idea, thank you! + reactions: + $ref: '#/components/schemas/MessageCommentReactionEntity' + description: List Message Comments + x-docs: | + A message comment represents a comment made by a user on a message. + MessageCommentReactionEntity: + type: object + properties: + id: + type: integer + description: Reaction ID + format: int32 + example: 1 + emoji: + type: string + description: Emoji used in the reaction. + example: 👍 + description: List Message Comment Reactions + x-docs: | + A message comment reaction represents a reaction emoji made by a user on a message comment. + MessageReactionEntity: + type: object + properties: + id: + type: integer + description: Reaction ID + format: int32 + example: 1 + emoji: + type: string + description: Emoji used in the reaction. + example: 👍 + description: List Message Reactions + x-docs: | + A message reaction represents a reaction emoji made by a user on a message. + NotificationEntity: + type: object + properties: + id: + type: integer + description: Notification ID + format: int32 + example: 1 + path: + type: string + description: Folder path to notify on + example: path + group_id: + type: integer + description: Notification group id + format: int32 + example: 0 + group_name: + type: string + description: Group name if applicable + example: "" + notify_user_actions: + type: boolean + description: Trigger notification on notification user actions? + example: true + notify_on_copy: + type: boolean + description: Triggers notification when moving or copying files to this + path + example: true + recursive: + type: boolean + description: Enable notifications for each subfolder in this path + example: true + send_interval: + type: string + description: The time interval that notifications are aggregated to + example: fifteen_minutes + enum: + - five_minutes + - fifteen_minutes + - hourly + - daily + unsubscribed: + type: boolean + description: Is the user unsubscribed from this notification? + example: true + unsubscribed_reason: + type: string + description: The reason that the user unsubscribed + example: "" + enum: + - none + - unsubscribe_link_clicked + - mail_bounced + - mail_marked_as_spam + user_id: + type: integer + description: Notification user ID + format: int32 + example: 1 + username: + type: string + description: Notification username + example: User + suppressed_email: + type: boolean + description: If true, it means that the recipient at this user's email address + has manually unsubscribed from all emails, or had their email "hard bounce", + which means that we are unable to send mail to this user's current email + address. Notifications will resume if the user changes their email address. + example: false + description: List Notifications + x-docs: | + Notifications are our feature that send E-Mails when new files are uploaded into a folder. + ProjectEntity: + type: object + properties: + id: + type: integer + description: Project ID + format: int32 + example: 1 + global_access: + type: string + description: Global access settings + example: none + enum: + - none + - anyone_with_read + - anyone_with_full + description: List Projects + x-docs: | + Projects are associated with a folder and add project management features to that folder. + RemoteServerEntity: + type: object + properties: + id: + type: integer + description: Remote server ID + format: int32 + example: 1 + authentication_method: + type: string + description: Type of authentication method + example: password + hostname: + type: string + description: Hostname or IP address + example: remote-server.com + remote_home_path: + type: string + description: Initial home folder on remote server + example: /home/user1 + name: + type: string + description: Internal name for your reference + example: My Remote server + port: + type: integer + description: Port for remote server. Not needed for S3. + format: int32 + example: 1 + max_connections: + type: integer + description: Max number of parallel connections. Ignored for S3 connections + (we will parallelize these as much as possible). + format: int32 + example: 1 + s3_bucket: + type: string + description: S3 bucket name + example: my-bucket + s3_region: + type: string + description: S3 region + example: us-east-1 + server_certificate: + type: string + description: Remote server certificate + example: require_match + enum: + - require_match + - allow_any + server_host_key: + type: string + description: Remote server SSH Host Key. If provided, we will require that + the server host key matches the provided key. Uses OpenSSH format similar + to what would go into ~/.ssh/known_hosts + example: '[public key]' + server_type: + type: string + description: Remote server type. + example: s3 + enum: + - ftp + - sftp + - s3 + - google_cloud_storage + - webdav + - wasabi + - backblaze_b2 + - one_drive + - rackspace + - box + - dropbox + - google_drive + - azure + - sharepoint + - s3_compatible + ssl: + type: string + description: Should we require SSL? + example: if_available + enum: + - if_available + - require + - require_implicit + - never + username: + type: string + description: Remote server username. Not needed for S3 buckets. + example: user + google_cloud_storage_bucket: + type: string + description: Google Cloud Storage bucket name + example: my-bucket + google_cloud_storage_project_id: + type: string + description: Google Cloud Project ID + example: my-project + backblaze_b2_s3_endpoint: + type: string + description: Backblaze B2 Cloud Storage S3 Endpoint + example: s3.us-west-001.backblazeb2.com + backblaze_b2_bucket: + type: string + description: Backblaze B2 Cloud Storage Bucket name + example: my-bucket + wasabi_bucket: + type: string + description: Wasabi Bucket name + example: my-bucket + wasabi_region: + type: string + description: Wasabi region + example: us-west-1 + rackspace_username: + type: string + description: Rackspace username used to login to the Rackspace Cloud Control + Panel. + example: rackspaceuser + rackspace_region: + type: string + description: Three letter airport code for Rackspace region. See https://support.rackspace.com/how-to/about-regions/ + example: dfw + rackspace_container: + type: string + description: The name of the container (top level directory) where files + will sync. + example: my-container + auth_setup_link: + type: string + description: Returns link to login with an Oauth provider + example: auth/:provider + auth_status: + type: string + description: Either `in_setup` or `complete` + example: in_setup + enum: + - not_applicable + - in_setup + - complete + - reauthenticate + auth_account_name: + type: string + description: Describes the authorized account + example: me@example.com + one_drive_account_type: + type: string + description: Either personal or business_other account types + example: personal + enum: + - personal + - business_other + azure_blob_storage_account: + type: string + description: Azure Blob Storage Account name + example: storage-account-name + azure_blob_storage_container: + type: string + description: Azure Blob Storage Container name + example: container-name + s3_compatible_bucket: + type: string + description: S3-compatible Bucket name + example: my-bucket + s3_compatible_region: + type: string + description: S3-compatible Bucket name + example: us-east-1 + s3_compatible_endpoint: + type: string + description: S3-compatible endpoint + example: mys3platform.com + enable_dedicated_ips: + type: boolean + description: '`true` if remote server only accepts connections from dedicated + IPs' + example: true + description: Create Remote Server + x-docs: | + Remote servers are used with the `remote_server_sync` Behavior. + + Remote Servers can be either an FTP server, SFTP server, S3 bucket, Google Cloud Storage, Wasabi, Backblaze B2 Cloud Storage, Rackspace Cloud Files container, WebDAV, Box, Dropbox, OneDrive, Google Drive, or Azure Blob Storage. + + Not every attribute will apply to every remote server. + + FTP Servers require that you specify their `hostname`, `port`, `username`, `password`, and a value for `ssl`. Optionally, provide `server_certificate`. + + SFTP Servers require that you specify their `hostname`, `port`, `username`, `password` or `private_key`, and a value for `ssl`. Optionally, provide `server_certificate`. + + S3 Buckets require that you specify their `s3_bucket` name, and `s3_region`. Optionally provide a `aws_access_key`, and `aws_secret_key`. If you don't provide credentials, you will need to use AWS to grant us access to your bucket. + + S3-Compatible Buckets require that you specify `s3_compatible_bucket`, `s3_compatible_region`, `s3_compatible_endpoint`, `s3_compatible_access_key`, and `s3_compatible_secret_key`. + + Google Cloud Storage requires that you specify `google_cloud_storage_bucket`, `google_cloud_storage_project_id`, and `google_cloud_storage_credentials_json`. + + Wasabi requires `wasabi_bucket`, `wasabi_region`, `wasabi_access_key`, and `wasabi_secret_key`. + + Backblaze B2 Cloud Storage `backblaze_b2_bucket`, `backblaze_b2_s3_endpoint`, `backblaze_b2_application_key`, and `backblaze_b2_key_id`. (Requires S3 Compatible API) See https://help.backblaze.com/hc/en-us/articles/360047425453 + + Rackspace Cloud Files requires `rackspace_username`, `rackspace_api_key`, `rackspace_region`, and `rackspace_container`. + + WebDAV Servers require that you specify their `hostname`, `username`, and `password`. + + OneDrive follow the `auth_setup_link` and login with Microsoft. + + Sharepoint follow the `auth_setup_link` and login with Microsoft. + + Box follow the `auth_setup_link` and login with Box. + + Dropbox follow the `auth_setup_link` and login with Dropbox. + + Google Drive follow the `auth_setup_link` and login with Google. + + Azure `azure_blob_storage_account`, `azure_blob_storage_container`, `azure_blob_storage_access_key` + RequestEntity: + type: object + properties: + id: + type: integer + description: Request ID + format: int32 + example: 1 + path: + type: string + description: Folder path + example: "" + source: + type: string + description: Source filename, if applicable + example: "" + destination: + type: string + description: Destination filename + example: "" + automation_id: + type: string + description: ID of automation that created request + example: "" + user_display_name: + type: string + description: User making the request (if applicable) + example: "" + description: List Requests + x-docs: | + A Request represents a file that *should* be uploaded by a specific user or group. + + Requests can either be manually created and managed, or managed automatically by an Automation. + SettingsChangeEntity: + type: object + properties: + change_details: + type: object + properties: {} + description: Specifics on what changed. + example: '{ domain: ["olddomain.com'', "newdomain.com"] }' + created_at: + type: string + description: The time this change was made + format: date-time + example: 2000-01-01T01:00:00Z + user_id: + type: integer + description: The user id responsible for this change + format: int32 + example: 1 + description: List Settings Changes + x-docs: | + Settings changes caused by any user. + SsoStrategyEntity: + type: object + properties: + protocol: + type: string + description: SSO Protocol + example: oauth2 + enum: + - oauth2 + - _unused_openid2 + - saml + - active_directory + - open_ldap + - scim + provider: + type: string + description: Provider name + example: okta + enum: + - google + - auth0 + - okta + - atlassian + - azure + - box + - dropbox + - slack + - _unused_ubuntu + - onelogin + - saml + - idaptive + - ldap + - scim + label: + type: string + description: Custom label for the SSO provider on the login page. + example: My Corporate SSO Provider + logo_url: + type: string + description: URL holding a custom logo for the SSO provider on the login + page. + example: https://mysite.files.com/.../logo.png + id: + type: integer + description: ID + format: int32 + example: 1 + saml_provider_cert_fingerprint: + type: string + description: Identity provider sha256 cert fingerprint if saml_provider_metadata_url + is not available. + example: "" + saml_provider_issuer_url: + type: string + description: Identity provider issuer url + example: "" + saml_provider_metadata_content: + type: string + description: Custom identity provider metadata + example: "" + saml_provider_metadata_url: + type: string + description: Metadata URL for the SAML identity provider + example: "" + saml_provider_slo_target_url: + type: string + description: Identity provider SLO endpoint + example: "" + saml_provider_sso_target_url: + type: string + description: Identity provider SSO endpoint if saml_provider_metadata_url + is not available. + example: "" + scim_authentication_method: + type: string + description: SCIM authentication type. + example: "" + enum: + - none + - basic + - token + scim_username: + type: string + description: SCIM username. + example: "" + scim_oauth_access_token: + type: string + description: SCIM OAuth Access Token. + example: "" + scim_oauth_access_token_expires_at: + type: string + description: SCIM OAuth Access Token Expiration Time. + example: "" + subdomain: + type: string + description: Subdomain + example: my-site + provision_users: + type: boolean + description: Auto-provision users? + provision_groups: + type: boolean + description: Auto-provision group membership based on group memberships + on the SSO side? + deprovision_users: + type: boolean + description: Auto-deprovision users? + deprovision_groups: + type: boolean + description: Auto-deprovision group membership based on group memberships + on the SSO side? + deprovision_behavior: + type: string + description: Method used for deprovisioning users. + example: disable + enum: + - disable + - delete + provision_group_default: + type: string + description: Comma-separated list of group names for groups to automatically + add all auto-provisioned users to. + example: Employees + provision_group_exclusion: + type: string + description: Comma-separated list of group names for groups (with optional + wildcards) that will be excluded from auto-provisioning. + example: Employees + provision_group_inclusion: + type: string + description: Comma-separated list of group names for groups (with optional + wildcards) that will be auto-provisioned. + example: Employees + provision_group_required: + type: string + description: Comma or newline separated list of group names (with optional + wildcards) to require membership for user provisioning. + example: "" + provision_email_signup_groups: + type: string + description: Comma-separated list of group names whose members will be created + with email_signup authentication. + example: Employees + provision_site_admin_groups: + type: string + description: Comma-separated list of group names whose members will be created + as Site Admins. + example: Employees + provision_attachments_permission: + type: boolean + description: 'DEPRECATED: Auto-provisioned users get Sharing permission. + Use a Group with the Bundle permission instead.' + example: true + provision_dav_permission: + type: boolean + description: Auto-provisioned users get WebDAV permission? + example: true + provision_ftp_permission: + type: boolean + description: Auto-provisioned users get FTP permission? + example: true + provision_sftp_permission: + type: boolean + description: Auto-provisioned users get SFTP permission? + example: true + provision_time_zone: + type: string + description: Default time zone for auto provisioned users. + example: Eastern Time (US & Canada) + provision_company: + type: string + description: Default company for auto provisioned users. + example: ACME Corp. + ldap_base_dn: + type: string + description: Base DN for looking up users in LDAP server + example: "" + ldap_domain: + type: string + description: Domain name that will be appended to LDAP usernames + example: mysite.com + enabled: + type: boolean + description: Is strategy enabled? + example: true + ldap_host: + type: string + description: LDAP host + example: ldap.site.com + ldap_host_2: + type: string + description: LDAP backup host + example: ldap2.site.com + ldap_host_3: + type: string + description: LDAP backup host + example: ldap3.site.com + ldap_port: + type: integer + description: LDAP port + format: int32 + example: 1 + ldap_secure: + type: boolean + description: Use secure LDAP? + example: true + ldap_username: + type: string + description: Username for signing in to LDAP server. + example: '[ldap username]' + ldap_username_field: + type: string + description: LDAP username field + example: sAMAccountName + enum: + - sAMAccountName + - userPrincipalName + description: List Sso Strategies + x-docs: | + An SSO Strategy is a method for allowing users to sign in via another identity provider, such as Okta or Auth0. + + It is rare that you will need to use API endpoints for managing these, and we recommend instead managing these via the web interface. + Nevertheless, we share the API documentation here. + StyleEntity: + type: object + properties: + id: + type: integer + description: Style ID + format: int32 + example: 1 + path: + type: string + description: Folder path + example: "" + logo: + description: Logo + $ref: '#/components/schemas/ImageEntity' + thumbnail: + description: Logo thumbnail + $ref: '#/components/schemas/ImageEntity' + description: Show Style + x-docs: | + Styles are custom sets of branding that can be applied on a per-folder basis. + Currently these only support Logos per folder, but in the future we may extend these to also support colors. + If you want to see that, please let us know so we can add your vote to the list. + SyncJobEntity: + type: object + properties: + queued_at: + type: string + description: Job enqueued at + format: date-time + example: 2000-01-01T01:00:00Z + updated_at: + type: string + description: Job updated at + format: date-time + example: 2000-01-01T01:00:00Z + status: + type: string + description: Status of the job + example: "" + regional_worker_status: + type: string + description: Most recent reported status of sync worker + example: "" + uuid: + type: string + description: "UUID" + example: "" + folder_behavior_id: + type: integer + description: "Folder behaviour ID" + format: int32 + example: 1 + description: List Sync Jobs + x-docs: null + UsageDailySnapshotEntity: + type: object + properties: + id: + type: integer + description: ID of the usage record + format: int32 + example: 1 + date: + type: string + description: The date of this usage record + format: date + example: 2020-11-21 + current_storage: + type: integer + description: The quantity of storage held for this site + format: int32 + example: 65536 + usage_by_top_level_dir: + type: array + items: {} + description: Usage broken down by each top-level folder + example: "" + description: List Usage Daily Snapshots + x-docs: null + UserRequestEntity: + type: object + properties: + id: + type: integer + description: ID + format: int32 + example: 1 + name: + type: string + description: User's full name + example: John Doe + email: + type: string + description: User email address + format: email + example: john.doe@files.com + details: + type: string + description: Details of the user's request + example: Changed Departments + description: Create User Request + x-docs: | + User Requests allow anonymous users to place a request for access on the login screen to the site administrator. + WebhookTestEntity: + type: object + properties: + code: + type: integer + description: Status HTTP code + format: int32 + example: 200 + message: + type: string + description: Error message + example: "" + status: + type: string + description: Status message + example: "" + data: + description: Auto fields + $ref: '#/components/schemas/AutoEntity' + success: + type: boolean + description: The success status of the webhook test + example: true + description: Create Webhook Test + x-docs: null + securitySchemes: + api_key: + type: apiKey + description: API Key - supports user-based or site-wide API keys + name: X-FilesAPI-Key + in: header +x-regions: + - name: us-east-1 + description: USA, Virginia + - name: ap-southeast-2 + description: Australia, Sydney + - name: ca-central-1 + description: Canada, Toronto + - name: eu-west-2 + description: EU - UK, London + - name: eu-central-1 + description: EU - Germany, Frankfurt + - name: ap-northeast-1 + description: Japan, Tokyo + - name: ap-southeast-1 + description: Singapore +x-behaviors: + - behavior: webhook + children_can_add: true + children_can_override: false + docs: | + Sends an HTTP(S) request to a remote server whenever certain actions occur on a folder. + Webhooks are often used to integrate Files.com with other services. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'urls' => ['https://mysite.com/url...'], + 'method' => 'POST', + 'encoding' => 'RAW', + 'triggers' => [ 'create', 'read', 'update', 'destroy', 'move', 'copy' ] + })%> + ``` + + Value Hash Parameters |   + --- | --- + `urls` | Array of URLs to send the webhook to. + `method` | Default: `GET`. May also be set to `POST`. + `triggers` | Leave blank to send webhooks on any action on this folder. Or, for specific actions, you may specify an array of action types. Valid values are: `create`, `read`, `update`, `destroy`, `move`, `copy`. + `encoding` | May be `JSON`, `XML`, or `RAW`. If set to `RAW` or left blank, we will deliver the webhook using the HTTP GET params or POST body. If JSON or XML, we will encode the payload accordingly and send a matching `Content-Type` header. + `file_form_field` | A string specifying the name of a form field containing the contents of the file that triggered this webhook send. If this value is present, the webhook will submit a `multipart/form-data` POST with no request body encoding. + `file_as_body` | When sending webhook requests, submit the contents of the file that triggered this webhook send as the request body. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: false + visible_to_non_admins: false + - behavior: file_expiration + children_can_add: false + children_can_override: true + docs: | + Files in this folder will expire (be deleted) after a certain number of days. This is most often used for compliance purposes where different types of data may need different retention settings. It's also great for managing your costs. You can retain different data for less time than others. + + Value is stored as an Integer (not a hash/array) representing the number of days. + + > Example Value + + ```json + <%=JSON.pretty_generate(30)%> + ``` + requires_attachment: false + supports_mounted_folders: false + unique_per_folder: true + visible_to_non_admins: true + - behavior: auto_encrypt + children_can_add: false + children_can_override: true + docs: | + Files will be automatically encrypted after uploading using your provided GPG key. + + This Behavior is often used on our HIPAA accounts to convert data into a format unreadable by even us. + GPG is an asymmetric encryption type (which means it uses public keys and private keys). + Because you are only providing us your public key and keeping your private key, we won't be able to read anything once it has been GPG encrypted. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'algorithm' => 'PGP/GPG', + 'suffix' => '.gpg', + 'key' => '[your GPG public key]', + 'armor' => 'false' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `algorithm` | Must be set to `PGP/GPG`. If we support other options in the future (like OpenSSL), we will amend this option. + `suffix` | Suffix to apply to filenames once they've been uploaded. + `key` | Your GPG public key. Please be sure not to send your private key here. If that happens, we try to detect it and disable the behavior for your security. + `armor` | If true, encrypted files are written as ascii text. + requires_attachment: false + supports_mounted_folders: false + unique_per_folder: true + visible_to_non_admins: true + - behavior: lock_subfolders + children_can_add: false + children_can_override: true + docs: | + The subfolder structure of this folder may not be changed. + This is useful in conjunction with workflows and automations to ensure your folder structure stays as you expect. + + Children Recursive: Do not allow Create/Move/Delete on parent folder, child folders and any descendant folders. + Children: Do not allow Create/Move/Delete on parent folder or child folders but do allow on any descendant folders. + Self: Do not allow Delete or Rename of this(parent) folder. Do allow Create/Move/Delete on child folders and any descendant folders. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'level' => 'children_recursive' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `level` | URL key used for the inbox. Can be `children_recursive` (default), `children`, `self`, or `none`. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: storage_region + children_can_add: false + children_can_override: true + docs: |- + Files in this folder are stored in a certain geographical region. + If you set this Behavior on an existing folder, we will migrate existing files to the new location automatically. + + > Example Value + + ```json + <%=JSON.pretty_generate('us-east-1')%> + ``` + + Value is stored as a String. Valid region values: + + Value String | Region Description + --- | --- + `us-east-1` | USA, Virginia + `ap-southeast-2` | Australia, Sydney + `ca-central-1` | Canada, Toronto + `eu-west-2` | EU - UK, London + `eu-central-1` | EU - Germany, Frankfurt + `ap-northeast-1` | Japan, Tokyo + `ap-southeast-1` | Singapore + requires_attachment: false + supports_mounted_folders: false + unique_per_folder: true + visible_to_non_admins: true + - behavior: serve_publicly + children_can_add: true + children_can_override: false + docs: | + Files in this folder are served via a public HTTPS URL at `https://SUBDOMAIN.hosted-by-files.com/...` + + This feature works with common static site generators such as Jekyll and Middleman, and allows any static web assets or website to be hosted. + It's a great way to get extra mileage out of your Files.com account and avoid having to pay for separate web hosting. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'key' => 'public-photos', + 'show_index' => true + })%> + ``` + + Value Hash Parameters |   + --- | --- + `key` | URL path for where the stuff is publicly hosted. It will look like `https://SUBDOMAIN.hosted-by-files.com/{key}/` + `show_index` | Show an index page listing the folder contents? + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: create_user_folders + children_can_add: true + children_can_override: false + docs: | + Create a folder here for new users when they are added. + This Behavior is typically used to implement home folders for users. + It's also a good building block for more advanced automations and workflows. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'permission' => 'full', + 'existing_users' => true, + 'group_id' => 1, + 'new_folder_name' => 'username' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `permission` | What permission level to give the user on his or her new folder? Takes the same options as the Permissions endpoint. + `existing_users` | Apply this behavior to existing users or only newly added users? + `group_id` | Only apply this behavior to users who are members of this group ID. + `new_folder_name` | What to name the new folder, currently we support 'name' and 'username', name will fall back to username if not present, default value is 'name' + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: false + visible_to_non_admins: false + - behavior: remote_server_sync + children_can_add: true + children_can_override: false + docs: | + Sync this folder to a remote server on a regular basis. Remote servers can be FTP/SFTP servers, Amazon S3/GCP/Azure Blob/Wasabi/Backblaze B2 Buckets, and more. + See the RemoteServer object for a full list of the Remote Servers supported. + + One-way and two-way sync options are supported. + + With this behavior, the Sync between Files.com and the RemoteServer occurs on a schedule. Your plan level determines the frequency of the Sync schedule. + Higher plans offer faster sync intervals. + + If you want to instead "mount" your RemoteServer for real-time operations within Files.com, please see the RemoteServerMount behavior instead. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'remote_server_id' => '1', + 'direction' => 'two_way', + 'keep_after_copy' => 'keep', + 'remote_path' => '' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `direction` | One way or two way sync? Valid values: `push_to_server`, `pull_from_server`, `two_way` + `remote_server_id` | ID of the remote server to sync with. See the Remote Servers API resource for managing these. + `keep_after_copy` | If one-way syncing, should we delete or keep files after sync? + `remote_path` | Path on remote server to sync with. This should be an absolute path on the remote server. This must be slash-delimited, but it must neither start nor end with a slash. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: false + visible_to_non_admins: false + - behavior: inbox + children_can_add: true + children_can_override: false + docs: | + This folder operates as an inbox where anonymous users can upload files without logging in. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'key' => 'application-forms', + 'title' => 'Submit Your Job Applications Here', + 'description' => 'Thanks for coming to the Files.com Job Application Page', + 'show_on_login_page' => true, + 'require_registration' => true, + 'help_text' => 'If you have trouble here, please contact your recruiter.', + 'path_template' => '{{name}}_{{ip}}' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `key` | URL key used for the inbox. + `dont_separate_submissions_by_folder` | Do not create subfolders for files uploaded to this inbox. Note: there are subtle security pitfalls with allowing anonymous uploads from multiple users to live in the same folder. We strongly discourage use of this option unless absolutely required. + `show_on_login_page` | Show this inbox on the login page of your website. Only settable by admins. + `title` | Title of the Inbox + `description` | Description of the inbox shown on the actual inbox page. + `help_text` | Help text shown on the inbox page. + `require_registration` | Show a registration page that captures the uploader's name and email address? + `password` | Password to authenticate to inbox. + `path_template` | Template for creating submission subfolders. Can use the uploader's name, email address, ip, company, and any custom form data. + + ## Path Templates + + Admins can customize how submission subfolders are created by providing a path_template value. For example, an inbox can be created with the following `path_template` value: + + > {{name}}_{ip} + + This will result in submission subfolders that look like `john doe_127.0.0.1`. + + Path templates can use any of the following standard fields: + * name + * company + * email + * ip + + They can also use any fields defined on the inbox's custom form field set. An inbox with a custom form field set with a field called 'My Field' + can have a path template that looks like this: + + > {{name}}_{{My Field}} + + Note: Field names are case-sensitive. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: false + visible_to_non_admins: true + - behavior: append_timestamp + children_can_add: false + children_can_override: false + docs: | + Append a timestamp to filenames of all files uploaded to this folder. + This is often used in conjunction with Automations and remote server sync to ensure file organization. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'format' => '-YYYY-MM-DDThh:mm:ssZ', + 'time_zone' => 'Eastern Time (US & Canada)' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `format` | Format for the timestamp. You may use anything accepted by the standard UNIX `date` command or `strftime`. + `time_zone` | Accepts any valid timezone value from the web interface (e.g. "Eastern Time (US & Canada)") or a UTC offset ("-05:00"). Omit parameter for UTC time. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: limit_file_extensions + children_can_add: false + children_can_override: false + docs: | + Limit the allowed extensions of files being uploaded to this folder. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'extensions' => [ 'xls', 'csv' ], + 'mode' => 'whitelist', + })%> + ``` + + Value Hash Parameters |   + --- | --- + `extensions` | Array of whitelisted/blacklisted file extensions, depending on mode + `mode` | controls whether the behavior acts as a whitelist or as a blacklist. Default is `whitelist`. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: limit_file_regex + children_can_add: false + children_can_override: false + docs: | + Limit the filenames of files in this folder according to a regular expression. + + > Example Value + + ```json + <%=JSON.pretty_generate([ "/Document-.*/" ])%> + ``` + Value is stored as a single-element Array (not a hash) containing the regular expression, which must start and end with slashes. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: amazon_sns + children_can_add: true + children_can_override: false + docs: | + Sends a notification via Amazon SNS whenever certain actions occur on a folder. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'arns' => ['ARN...'], + 'triggers' => [ 'create', 'read', 'update', 'destroy', 'move', 'copy' ], + 'aws_credentials' => { + 'access_key_id' => 'ACCESS_KEY_ID', + 'region' => 'us-east-1', + 'secret_access_key' => 'SECRET_ACCESS_KEY' + } + })%> + ``` + + Value Hash Parameters |   + --- | --- + `arns` | Array of ARNs to send the notifications to. + `triggers` | Leave blank to send an SNS notification on any action on this folder. Or, for specific actions, you may specify an array of action types. Valid values are: `create`, `read`, `update`, `destroy`, `move`, `copy`. + `aws_credentials` | AWS IAM Credentials to use for sending SNS requests. Must include `access_key_id`, and `secret_access_key`. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: false + visible_to_non_admins: false + - behavior: watermark + children_can_add: false + children_can_override: false + docs: | + Adds a watermark to any image preview generated for an image in this folder. + + ```json + <%=JSON.pretty_generate({ + 'gravity' => 'SouthWest', + 'max_height_or_width' => 20, + 'transparency' => 25 + })%> + ``` + + Value Hash Parameters |   + --- | --- + `gravity` | Where to locate the watermark? Valid values: `Center`, `East`, `NorthEast`, `North`, `NorthWest`, `SouthEast`, `South`, `SouthWest`, `West` + `max_height_or_width` | Max width/height as percent of image preview. + `transparency` | Percentage applied to the watermark. + requires_attachment: true + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: remote_server_mount + children_can_add: false + children_can_override: false + docs: | + Mount a remote server within this folder. Remote servers can be FTP/SFTP servers, Amazon S3/GCP/Azure Blob/Wasabi/Backblaze B2 Buckets, and more. + + See the RemoteServer object for a full list of the Remote Servers supported. + + When this behavior is enabled, files in this folder will never actually be stored on Files.com. Rather, Files.com will mount the remote server and + act as a mere conduit from your clients to the remote server. + + Files.com workflow elements such as Permissions, Automations, Webhooks, Notifications, etc., will apply only to transfer activities that occur through + Files.com. We won't send Webhooks or Notifications based on activity that occurs via a direct connetion to the Remote Server other than through Files.com. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'remote_server_id' => '1', + 'remote_path' => '' + })%> + ``` + + Value Hash Parameters |   + --- | --- + `remote_server_id` | ID of the remote server to sync with. See the Remote Servers API resource for managing these. + `remote_path` | Path on remote server to treat as the root of this mount. This should be an absolute path on the remote server. This must be slash-delimited, but it must neither start nor end with a slash. + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: true + visible_to_non_admins: true + - behavior: slack_webhook + children_can_add: true + children_can_override: false + docs: | + Sends a Webhook call to Slack whenever certain actions occur on a folder. + You will need to add the "Incoming WebHooks" App to your Slack workspace. + + > Example Value + + ```json + <%=JSON.pretty_generate({ + 'url' => 'https://mysite.com/url...', + 'username' => 'Files.com', + 'channel' => 'alerts', + 'icon_emoji' => ':robot_face:', + 'triggers' => [ 'create', 'read', 'update', 'destroy', 'move', 'copy' ] + })%> + ``` + + Value Hash Parameters |   | Required + --- | --- | --- + `url` | Slack issued URL to send the webhook to. | Yes + `username` | Username to display in Slack. | No + `channel` | Channel is send the webhook to. | No + `icon_emoji` | Slack emoji to display in Slack, e.g. :robot_face: | No + `triggers` | Leave blank to send webhooks on any action on this folder. Or, for specific actions, you may specify an array of action types. Valid values are: `create`, `read`, `update`, `destroy`, `move`, `copy`. | No + requires_attachment: false + supports_mounted_folders: true + unique_per_folder: false + visible_to_non_admins: true +x-errors: + - type: bad-request + title: Bad Request + http-code: 400 + - type: bad-request/attachment-too-large + title: Attachment Too Large + http-code: 400 + - type: bad-request/cannot-download-directory + title: Cannot Download Directory + http-code: 400 + - type: bad-request/cant-move-with-multiple-locations + title: Cant Move With Multiple Locations + http-code: 400 + - type: bad-request/datetime-parse + title: Datetime Parse + http-code: 400 + - type: bad-request/destination-same + title: Destination Same + http-code: 400 + - type: bad-request/folder-must-not-be-a-file + title: Folder Must Not Be A File + http-code: 400 + - type: bad-request/invalid-body + title: Invalid Body + http-code: 400 + - type: bad-request/invalid-cursor + title: Invalid Cursor + http-code: 400 + - type: bad-request/invalid-etags + title: Invalid Etags + http-code: 400 + - type: bad-request/invalid-filter-combination + title: Invalid Filter Combination + http-code: 400 + - type: bad-request/invalid-filter-field + title: Invalid Filter Field + http-code: 400 + - type: bad-request/invalid-input-encoding + title: Invalid Input Encoding + http-code: 400 + - type: bad-request/invalid-interface + title: Invalid Interface + http-code: 400 + - type: bad-request/invalid-oauth-provider + title: Invalid Oauth Provider + http-code: 400 + - type: bad-request/invalid-return-to-url + title: Invalid Return To Url + http-code: 400 + - type: bad-request/invalid-upload-offset + title: Invalid Upload Offset + http-code: 400 + - type: bad-request/invalid-upload-part-gap + title: Invalid Upload Part Gap + http-code: 400 + - type: bad-request/invalid-upload-part-size + title: Invalid Upload Part Size + http-code: 400 + - type: bad-request/method-not-allowed + title: Method Not Allowed + http-code: 400 + - type: bad-request/no-valid-input-params + title: No Valid Input Params + http-code: 400 + - type: bad-request/operation-on-non-scim-resource + title: Operation On Non Scim Resource + http-code: 400 + - type: bad-request/part-number-too-large + title: Part Number Too Large + http-code: 400 + - type: bad-request/reauthentication-needed-fields + title: Reauthentication Needed Fields + http-code: 400 + - type: bad-request/request-param-path-cannot-have-trailing-whitespace + title: Request Param Path Cannot Have Trailing Whitespace + http-code: 400 + - type: bad-request/request-params-contain-invalid-character + title: Request Params Contain Invalid Character + http-code: 400 + - type: bad-request/request-params-invalid + title: Request Params Invalid + http-code: 400 + - type: bad-request/request-params-required + title: Request Params Required + http-code: 400 + - type: bad-request/unsupported-currency + title: Unsupported Currency + http-code: 400 + - type: bad-request/unsupported-http-response-format + title: Unsupported Http Response Format + http-code: 400 + - type: bad-request/unsupported-media-type + title: Unsupported Media Type + http-code: 400 + - type: bad-request/user-id-invalid + title: User Id Invalid + http-code: 400 + - type: bad-request/user-id-on-user-endpoint + title: User Id On User Endpoint + http-code: 400 + - type: bad-request/user-required + title: User Required + http-code: 400 + - type: not-authenticated/authentication-required + title: Authentication Required + http-code: 401 + - type: not-authenticated/bundle-registration-code-failed + title: Bundle Registration Code Failed + http-code: 401 + - type: not-authenticated/inbox-registration-code-failed + title: Inbox Registration Code Failed + http-code: 401 + - type: not-authenticated/invalid-credentials + title: Invalid Credentials + http-code: 401 + - type: not-authenticated/invalid-oauth + title: Invalid Oauth + http-code: 401 + - type: not-authenticated/invalid-or-expired-code + title: Invalid Or Expired Code + http-code: 401 + - type: not-authenticated/invalid-username-or-password + title: Invalid Username Or Password + http-code: 401 + - type: not-authenticated/locked-out + title: Locked Out + http-code: 401 + - type: not-authenticated/lockout-region-mismatch + title: Lockout Region Mismatch + http-code: 401 + - type: not-authenticated/one-time-password-incorrect + title: One Time Password Incorrect + http-code: 401 + - type: not-authenticated/two-factor-authentication-error + title: Two Factor Authentication Error + http-code: 401 + - type: not-authenticated/two-factor-authentication-setup-expired + title: Two Factor Authentication Setup Expired + http-code: 401 + - type: not-authorized/api-key-is-disabled + title: Api Key Is Disabled + http-code: 403 + - type: not-authorized/api-key-is-path-restricted + title: Api Key Is Path Restricted + http-code: 403 + - type: not-authorized/api-key-only-for-desktop-app + title: Api Key Only For Desktop App + http-code: 403 + - type: not-authorized/api-key-only-for-mobile-app + title: Api Key Only For Mobile App + http-code: 403 + - type: not-authorized/api-key-only-for-office-integration + title: Api Key Only For Office Integration + http-code: 403 + - type: not-authorized/billing-permission-required + title: Billing Permission Required + http-code: 403 + - type: not-authorized/bundle-maximum-uses-reached + title: Bundle Maximum Uses Reached + http-code: 403 + - type: not-authorized/cannot-login-while-using-key + title: Cannot Login While Using Key + http-code: 403 + - type: not-authorized/cant-act-for-other-user + title: Cant Act For Other User + http-code: 403 + - type: not-authorized/contact-admin-for-password-change-help + title: Contact Admin For Password Change Help + http-code: 403 + - type: not-authorized/folder-admin-or-billing-permission-required + title: Folder Admin Or Billing Permission Required + http-code: 403 + - type: not-authorized/folder-admin-permission-required + title: Folder Admin Permission Required + http-code: 403 + - type: not-authorized/full-permission-required + title: Full Permission Required + http-code: 403 + - type: not-authorized/history-permission-required + title: History Permission Required + http-code: 403 + - type: not-authorized/insufficient-permission-for-params + title: Insufficient Permission For Params + http-code: 403 + - type: not-authorized/must-authenticate-with-api-key + title: Must Authenticate With Api Key + http-code: 403 + - type: not-authorized/need-admin-permission-for-inbox + title: Need Admin Permission For Inbox + http-code: 403 + - type: not-authorized/non-admins-must-query-by-folder-or-path + title: Non Admins Must Query By Folder Or Path + http-code: 403 + - type: not-authorized/not-allowed-to-create-bundle + title: Not Allowed To Create Bundle + http-code: 403 + - type: not-authorized/password-change-not-required + title: Password Change Not Required + http-code: 403 + - type: not-authorized/password-change-required + title: Password Change Required + http-code: 403 + - type: not-authorized/read-only-session + title: Read Only Session + http-code: 403 + - type: not-authorized/read-permission-required + title: Read Permission Required + http-code: 403 + - type: not-authorized/reauthentication-failed + title: Reauthentication Failed + http-code: 403 + - type: not-authorized/reauthentication-failed-final + title: Reauthentication Failed Final + http-code: 403 + - type: not-authorized/reauthentication-needed-action + title: Reauthentication Needed Action + http-code: 403 + - type: not-authorized/self-managed-required + title: Self Managed Required + http-code: 403 + - type: not-authorized/site-admin-required + title: Site Admin Required + http-code: 403 + - type: not-authorized/site-files-are-immutable + title: Site Files Are Immutable + http-code: 403 + - type: not-authorized/two-factor-authentication-required + title: Two Factor Authentication Required + http-code: 403 + - type: not-authorized/user-id-without-site-admin + title: User Id Without Site Admin + http-code: 403 + - type: not-authorized/write-permission-required + title: Write Permission Required + http-code: 403 + - type: not-authorized/zip-download-ip-mismatch + title: Zip Download Ip Mismatch + http-code: 403 + - type: not-found + title: Not Found + http-code: 404 + - type: not-found/api-key-not-found + title: Api Key Not Found + http-code: 404 + - type: not-found/bundle-path-not-found + title: Bundle Path Not Found + http-code: 404 + - type: not-found/code-not-found + title: Code Not Found + http-code: 404 + - type: not-found/file-not-found + title: File Not Found + http-code: 404 + - type: not-found/file-upload-not-found + title: File Upload Not Found + http-code: 404 + - type: not-found/folder-not-found + title: Folder Not Found + http-code: 404 + - type: not-found/group-not-found + title: Group Not Found + http-code: 404 + - type: not-found/inbox-not-found + title: Inbox Not Found + http-code: 404 + - type: not-found/nested-not-found + title: Nested Not Found + http-code: 404 + - type: not-found/plan-not-found + title: Plan Not Found + http-code: 404 + - type: not-found/site-not-found + title: Site Not Found + http-code: 404 + - type: not-found/user-not-found + title: User Not Found + http-code: 404 + - type: processing-failure/bundle-only-allows-previews + title: Bundle Only Allows Previews + http-code: 422 + - type: processing-failure/destination-exists + title: Destination Exists + http-code: 422 + - type: processing-failure/destination-folder-limited + title: Destination Folder Limited + http-code: 422 + - type: processing-failure/destination-parent-conflict + title: Destination Parent Conflict + http-code: 422 + - type: processing-failure/destination-parent-does-not-exist + title: Destination Parent Does Not Exist + http-code: 409 + - type: processing-failure/expired-public-key + title: Expired Public Key + http-code: 422 + - type: processing-failure/export-failure + title: Export Failure + http-code: 422 + - type: processing-failure/export-not-ready + title: Export Not Ready + http-code: 422 + - type: processing-failure/failed-to-change-password + title: Failed To Change Password + http-code: 422 + - type: processing-failure/file-locked + title: File Locked + http-code: 422 + - type: processing-failure/file-not-uploaded + title: File Not Uploaded + http-code: 422 + - type: processing-failure/file-pending-processing + title: File Pending Processing + http-code: 422 + - type: processing-failure/file-uploaded-to-wrong-region + title: File Uploaded To Wrong Region + http-code: 422 + - type: processing-failure/folder-locked + title: Folder Locked + http-code: 403 + - type: processing-failure/folder-not-empty + title: Folder Not Empty + http-code: 422 + - type: processing-failure/history-unavailable + title: History Unavailable + http-code: 422 + - type: processing-failure/invalid-bundle-code + title: Invalid Bundle Code + http-code: 422 + - type: processing-failure/invalid-file-type + title: Invalid File Type + http-code: 422 + - type: processing-failure/invalid-filename + title: Invalid Filename + http-code: 422 + - type: processing-failure/invalid-range + title: Invalid Range + http-code: 422 + - type: processing-failure/model-save-error + title: Model Save Error + http-code: 422 + - type: processing-failure/multipart-uploads-required-for-remotes + title: Multipart Uploads Required For Remotes + http-code: 422 + - type: processing-failure/multiple-processing-errors + title: Multiple Processing Errors + http-code: 422 + - type: processing-failure/recipient-already-shared + title: Recipient Already Shared + http-code: 422 + - type: processing-failure/remote-server-error + title: Remote Server Error + http-code: 422 + - type: processing-failure/resource-locked + title: Resource Locked + http-code: 422 + - type: processing-failure/subfolder-locked + title: Subfolder Locked + http-code: 422 + - type: processing-failure/two-factor-authentication-code-already-sent + title: Two Factor Authentication Code Already Sent + http-code: 422 + - type: processing-failure/updates-not-allowed-for-remotes + title: Updates Not Allowed For Remotes + http-code: 422 + - type: rate-limited/reauthentication-rate-limited + title: Reauthentication Rate Limited + http-code: 429 + - type: rate-limited/too-many-login-attempts + title: Too Many Login Attempts + http-code: 429 + - type: rate-limited/too-many-requests + title: Too Many Requests + http-code: 429 + - type: site-configuration/account-already-exists + title: Account Already Exists + http-code: 403 + - type: site-configuration/account-overdue + title: Account Overdue + http-code: 403 + - type: site-configuration/no-account-for-site + title: No Account For Site + http-code: 403 + - type: site-configuration/site-was-removed + title: Site Was Removed + http-code: 403 + - type: site-configuration/trial-expired + title: Trial Expired + http-code: 403 + - type: site-configuration/trial-locked + title: Trial Locked + http-code: 403 + - type: site-configuration/user-requests-enabled-required + title: User Requests Enabled Required + http-code: 403 +x-site_attribute_requirements: + allowed_countries: feature_bundle_power + bundle_password_required: feature_bundle_power + bundle_require_share_recipient: feature_bundle_power + disallowed_countries: feature_bundle_power + domain: feature_bundle_power + folder_permissions_groups_only: feature_bundle_power + custom_namespace: feature_bundle_power + require_2fa: feature_bundle_power + smtp_address: feature_bundle_power + smtp_authentication: feature_bundle_power + smtp_from: feature_bundle_power + smtp_username: feature_bundle_power + smtp_password: feature_bundle_power + smtp_port: feature_bundle_power + tls_disabled: feature_bundle_power + user_requests_enabled: feature_bundle_power diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/openweathermap.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/openweathermap.yaml new file mode 100644 index 000000000..523874c7e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/openweathermap.yaml @@ -0,0 +1,704 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: > + This is a generated connector from [Open Weather Map API version 2.5](https://openweathermap.org/) OpenAPI Specification. + + The Open Weather Map API provides access to current weather data and weather forecast of any location worldwide including 200,000 cities by consuming the [`Current Weather Data`](https://openweathermap.org/current) and [`One Call`](https://openweathermap.org/api/one-call-api) API endpoints. + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + x-ballerina-display: + label: OpenWeatherMap + iconPath: "icon.png" + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Please create an account at https://openweathermap.org and an API key following [this guide](https://openweathermap.org/appid). Choose a subscription that matches with your requirements. +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Access current weather data for any location. **Note**: All parameters are optional, but you must provide at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + description: "Access current weather data for any location. **Note**: All parameters are optional, but you must provide at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + operationId: getCurretWeatherData + parameters: + - $ref: '#/components/parameters/cityName' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + x-ballerina-display: + label: "Current Weather" + responses: + 200: + description: Current weather data of the given location + content: + application/json: + schema: + $ref: '#/components/schemas/CurrentWeatherData' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found + /onecall: + get: + tags: + - Weather Forecast + summary: "Access to current weather, minute forecast for 1 hour, hourly forecast for 48 hours, daily forecast for 7 days and government weather alerts." + description: "Access to current weather, minute forecast for 1 hour, hourly forecast for 48 hours, daily forecast for 7 days and government weather alerts." + operationId: getWeatherForecast + parameters: + - description: "Latitude" + in: query + name: lat + required: true + schema: + type: string + x-ballerina-display: + label: Latitude + - description: "Longtitude" + in: query + name: lon + required: true + schema: + type: string + x-ballerina-display: + label: Longtitude + - description: "Exclude parts of the weather data from the API response. It should be a comma-delimited list (without spaces)." + in: query + name: exclude + required: false + schema: + enum: + - 'current' + - 'minutely' + - 'hourly' + - 'daily' + - 'alerts' + type: string + x-ballerina-display: + label: Exclude + - description: "For temperature in Fahrenheit and wind speed in miles/hour, use `units=imperial`. For temperature in Celsius and wind speed in meter/sec, use `units=metric`. Temperature in Kelvin and wind speed in meter/sec is used by default, so there is no need to use the units parameter in the API call if you want this." + in: query + name: units + required: false + schema: + type: string + x-ballerina-display: + label: Units + - description: 'Language' + in: query + name: lang + required: false + schema: + type: string + x-ballerina-display: + label: Language + x-ballerina-display: + label: "Weather Forecast" + responses: + 200: + description: Weather forecast of the given location + content: + application/json: + schema: + $ref: '#/components/schemas/WeatherForecast' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found + +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + - name: Weather Forecast + description: "Get data related to weather forecast" + +externalDocs: + description: API Documentation + url: https://openweathermap.org/api + +components: + parameters: + cityName: + name: q + in: query + description: "City name, or city name and country code. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + x-ballerina-display: + label: "CityName or StateCode or CountryCode" + id: + name: id + in: query + description: "City ID. Example: `2172797`. The List of city IDs can be downloaded [here](http://bulk.openweathermap.o/sample/)." + schema: + type: string + x-ballerina-display: + label: "City Id" + lat: + name: lat + in: query + description: "Latitude" + schema: + type: string + x-ballerina-display: + label: "Latitude" + + lon: + name: lon + in: query + description: "Longtitude" + schema: + type: string + x-ballerina-display: + label: "Longitude" + + zip: + name: zip + in: query + description: "Zip code. Search by zip code. Example: 95050,us." + schema: + type: string + x-ballerina-display: + label: "Zip Code" + + units: + name: units + in: query + description: 'Temperature in Fahrenheit use `units=imperial`, temperature in Celsius use `units=metric`, temperature in `Kelvin` is used by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + x-ballerina-display: + label: "Units" + + lang: + name: lang + in: query + description: 'Language' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + x-ballerina-display: + label: "Language" + + mode: + name: mode + in: query + description: "Format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + x-ballerina-display: + label: "Mode" + schemas: + WeatherForecast: + type: object + description: "Weather forecast data" + properties: + lat: + type: number + description: Latitude + lon: + type: number + description: Longtitude + timezone: + type: string + description: Timezone name for the requested location + timezone_offset: + type: number + description: Shift in seconds from UTC + current: + $ref: '#/components/schemas/ForecastCurrent' + description: Current weather data + minutely: + type: array + items: + $ref: '#/components/schemas/Minutely' + description: Minutely weather forecast + hourly: + type: array + items: + $ref: '#/components/schemas/Hourly' + description: Hourly weather forecast + daily: + type: array + items: + $ref: '#/components/schemas/Daily' + description: Daily weather forecast + alerts: + type: array + items: + $ref: '#/components/schemas/Alerts' + description: Government weather alerts + Alerts: + description: Government weather alerts + type: object + properties: + sender_name: + type: string + description: Name of the alert source. + event: + type: string + description: Alert event name + description: + type: string + description: Description of the alert + start: + type: number + description: Date and time of the start of the alert, Unix, UTC + end: + type: number + description: Date and time of the end of the alert, Unix, UTC + tags: + type: array + items: + type: string + description: Tags related to alerts + Temp: + type: object + description: Temperature data + properties: + day: + type: number + description: Day temperature. + min: + type: number + description: Min daily temperature. + max: + type: number + description: Max daily temperature. + night: + type: number + description: Night temperature. + eve: + type: number + description: Evening temperature. + morn: + type: number + description: Morning temperature + FeelsLike: + type: object + description: "Human perception of temperature each time of the day" + properties: + day: + type: number + description: Day temperature. + night: + type: number + description: Night temperature. + eve: + type: number + description: Evening temperature. + morn: + type: number + description: Morning temperature. + Daily: + type: object + description: "Daily forecast weather data API response" + properties: + dt: + type: number + description: Time of the forecasted data, Unix, UTC + temp: + $ref: '#/components/schemas/Temp' + description: Temperature data + feels_like: + $ref: '#/components/schemas/FeelsLike' + description: "Temperature. This accounts for the human perception of weather." + moonrise: + type: number + description: The time of when the moon rises for this day, Unix, UTC + moonset: + type: number + description: The time of when the moon sets for this day, Unix, UTC + moon_phase: + type: number + description: "Moon phase. 0 and 1 are 'new moon', 0.25 is 'first quarter moon', 0.5 is 'full moon' and 0.75 is 'last quarter moon." + pressure: + type: number + description: "Atmospheric pressure on the sea level, hPa" + humidity: + type: number + description: Humidity, % + dew_point: + type: number + description: "Atmospheric temperature below which water droplets begin to condense and dew can form." + uvi: + type: number + description: The maximum value of UV index for the day + clouds: + type: number + description: Cloudiness, % + visibility: + type: number + description: Visibility of the atmosphere + wind_deg: + type: number + description: Wind direction, degrees (meteorological) + wind_gust: + type: number + description: "(where available) Wind gust. Units – default: metre/sec, metric: metre/sec, imperial: miles/hour." + pop: + type: number + description: Probability of precipitation + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: More info Weather condition codes + rain: + type: number + description: where available) Precipitation volume, mm + Hourly: + type: object + description: "Hourly forecast weather data API response" + properties: + dt: + type: number + description: Time of the forecasted data, Unix, UTC + temp: + type: number + description: "Temperature. Units – default: kelvin, metric: Celsius, imperial: Fahrenheit." + feels_like: + type: number + description: "Temperature. This accounts for the human perception of weather." + pressure: + type: number + description: "Atmospheric pressure on the sea level, hPa" + humidity: + type: number + description: "Humidity, %" + dew_point: + type: number + description: "Atmospheric temperature below which water droplets begin to condense and dew can form." + uvi: + type: number + description: "UV index" + clouds: + type: number + description: "Cloudiness, %" + visibility: + type: number + description: "Average visibility, metres" + wind_deg: + type: number + description: "Wind direction, degrees (meteorological)" + wind_gust: + type: number + description: "(where available) Wind gust. Units – default: metre/sec, metric: metre/sec, imperial: miles/hour." + pop: + type: number + description: "Probability of precipitatio" + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: More info Weather condition codes + rain: + $ref: '#/components/schemas/Rain' + description: Nature of the rain + Minutely: + type: object + properties: + dt: + type: number + description: Time of the forecasted data, unix, UTC + precipitation: + type: number + description: Precipitation volume, mm + description: "Minute forecast weather data API response" + ForecastCurrent: + type: object + description: Current weather data API response + properties: + dt: + type: number + description: Current time, Unix, UTC + sunrise: + type: number + description: Sunrise time, Unix, UTC + sunset: + type: number + description: Sunset time, Unix, UTC + temp: + type: number + description: "Temperature. Units - default: kelvin, metric: Celsius, imperial: Fahrenheit." + feels_like: + type: number + description: "Temperature. This temperature parameter accounts for the human perception of weather." + pressure: + type: number + description: "Atmospheric pressure on the sea level, hPa" + humidity: + type: number + description: "Humidity, %" + dew_point: + type: number + description: "Atmospheric temperature below which water droplets begin to condense and dew can form." + uvi: + type: number + description: "Current UV index" + clouds: + type: number + description: "Cloudiness, %" + visibility: + type: number + description: Average visibility, metres + wind_speed: + type: number + description: "Wind speed. Wind speed. Units – default: metre/sec, metric: metre/sec, imperial: miles/hour." + wind_deg: + type: number + description: Wind direction, degrees (meteorological) + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: More info Weather condition codes + rain: + $ref: '#/components/schemas/Rain' + description: Nature of the rain + snow: + $ref: '#/components/schemas/Snow' + description: Nature of the Snow + CurrentWeatherData: + title: Successful response + description: Current weather data + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + description: City geo location + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: More info Weather condition codes + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + description: Basic weather data + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + description: Nature of the wind + clouds: + $ref: '#/components/schemas/Clouds' + description: Nature of the clouds + rain: + $ref: '#/components/schemas/Rain' + description: Nature of the rain + snow: + $ref: '#/components/schemas/Snow' + description: Nature of the snow + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + description: Internal data + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + description: City name + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + description: City geo location + properties: + lon: + type: number + description: Longitude + example: 145.77000000000001 + lat: + type: number + description: Latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + description: Weather metadata + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + description: Basic weather data + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + description: Nature of the wind + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + description: Nature of the clouds + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + description: Nature of the rain + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + description: Snow volume information + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + description: System data + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: Represents API Key `appid` + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/soundcloud.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/soundcloud.yaml new file mode 100644 index 000000000..73152229e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/soundcloud.yaml @@ -0,0 +1,3266 @@ +openapi: 3.0.1 +servers: + - url: "https://api.soundcloud.com" +info: + x-ballerina-display: + label: SoundCloud + iconPath: "icon.png" + contact: + name: API issue tracker + url: "https://github.com/soundcloud/api" + termsOfService: "https://developers.soundcloud.com/docs/api/terms-of-use" + title: SoundCloud Public API Specification + version: 1.0.0 + x-apisguru-categories: + - media + x-logo: + url: "https://a-v2.sndcdn.com/assets/images/sc-icons/ios-a62dfc8fe7.png" + x-providerName: soundcloud.com + x-ballerina-init-description: >- + The connector initialization requires setting the API credentials. + + Create an [SoundCloud account](https://soundcloud.com/) + and obtain tokens following [this guide](https://developers.soundcloud.com/docs/api/guide). + description: >- + This is a generated connector for [SoundCloud API v1.0.0](https://developers.soundcloud.com/) OpenAPI Specification. + + SoundCloud API provides capability to access the online audio distribution platform and music sharing website that enables + you to upload,promote, and share audio, as well as a digital signal processor enabling listeners to stream audio. +tags: + - description: Authentication and Authorization Endpoints. + name: oauth + - description: Own User Endpoints. + name: me + - description: Search Endpoints. + name: search + - description: Playlists Endpoints. + name: playlists + - description: Tracks Endpoints. + name: tracks + - description: SoundCloud Users Endpoints. + name: users + - description: Liking Tracks & Playlists. + name: likes + - description: Reposting Tracks & Playlists. + name: reposts + - description: Miscellaneous Endpoints. + name: miscellaneous +paths: + "/likes/playlists/{playlist_id}": + delete: + operationId: unlikePlaylist + parameters: + - $ref: "#/components/parameters/playlist_id" + responses: + "200": + $ref: "#/components/responses/Success" + "400": + $ref: "#/components/responses/BadRequest" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + summary: Unlikes a playlist. + tags: + - likes + post: + operationId: likePlaylist + parameters: + - $ref: "#/components/parameters/playlist_id" + responses: + "200": + $ref: "#/components/responses/Success" + "201": + $ref: "#/components/responses/Created" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + security: + - AuthHeader: [] + + summary: Likes a playlist. + tags: + - likes + "/likes/tracks/{track_id}": + delete: + operationId: unlikeTrack + parameters: + - $ref: "#/components/parameters/test_track_id" + responses: + "200": + $ref: "#/components/responses/Success" + "400": + $ref: "#/components/responses/BadRequest" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Unlikes a track. + tags: + - likes + post: + operationId: likeTrack + parameters: + - $ref: "#/components/parameters/test_track_id" + responses: + "200": + $ref: "#/components/responses/Success" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "429": + $ref: "#/components/responses/TooManyRequests" + security: + - AuthHeader: [] + + summary: Likes a track. + tags: + - likes + /me: + get: + operationId: getUserDetail + responses: + "200": + $ref: "#/components/responses/CompleteUser" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns the authenticated user’s information. + tags: + - me + /me/activities: + get: + operationId: getActivities + parameters: + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/Activities" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns the authenticated user's activities. + tags: + - me + /me/activities/all/own: + get: + operationId: getOwnActivities + parameters: + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/Activities" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Recent the authenticated user's activities. + tags: + - me + /me/activities/tracks: + get: + operationId: getRecentTrackRelatedActivities + parameters: + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/Activities" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns the authenticated user's recent track related activities. + tags: + - me + /me/connections: + get: + operationId: listConnectedSocialAccounts + parameters: + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Connections" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of the authenticated user's connected social accounts. + tags: + - me + "/me/connections/{connection_id}": + get: + operationId: getConnectionByID + parameters: + - $ref: "#/components/parameters/connection_id" + responses: + "200": + $ref: "#/components/responses/Connection" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns the authenticated user's connected social account. + tags: + - me + /me/followers: + get: + operationId: getFollowers + parameters: + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/Users" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of users who are following the authenticated user. + tags: + - me + /me/followings: + get: + operationId: listFollowings + parameters: + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Users" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of users who are followed by the authenticated user. + tags: + - me + /me/followings/tracks: + get: + operationId: listRecentTracks + parameters: + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/TracksList" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: >- + Returns a list of recent tracks from users followed by the authenticated + user. + tags: + - me + "/me/followings/{user_id}": + delete: + operationId: deleteFollowing + parameters: + - $ref: "#/components/parameters/user_id_to_follow" + responses: + "200": + content: + application/json; charset=utf-8: + examples: + "200": + $ref: "#/components/examples/OK" + description: Success + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + "422": + $ref: "#/components/responses/UnprocessableEntity" + security: + - AuthHeader: [] + + summary: Deletes a user who is followed by the authenticated user. + tags: + - me + put: + operationId: followUser + parameters: + - $ref: "#/components/parameters/user_id_to_follow" + responses: + "200": + $ref: "#/components/responses/Successful" + "201": + $ref: "#/components/responses/User" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Follows a user. + tags: + - me + /me/likes/tracks: + get: + operationId: listLikedTracks + parameters: + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + responses: + "200": + $ref: "#/components/responses/Tracks" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of favorites or liked tracks of the authenticated user. + tags: + - me + /me/playlists: + get: + operationId: listPlaylist + description: "Returns playlist info, playlist tracks and tracks owner info." + parameters: + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/PlaylistsArray" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns user’s playlists (sets). + tags: + - me + /me/tracks: + get: + operationId: listTracks + parameters: + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + responses: + "200": + $ref: "#/components/responses/Tracks" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of user's tracks. + tags: + - me + /playlists: + get: + operationId: searchPlaylist + parameters: + - $ref: "#/components/parameters/q" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Playlists" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Performs a playlist search based on a query + tags: + - search + post: + operationId: createPlaylist + requestBody: + content: + application/json: + examples: + default: + $ref: "#/components/examples/CreateUpdatePlaylistRequest" + schema: + $ref: "#/components/schemas/CreateUpdatePlaylistRequest" + description: Create Playlist request + responses: + "201": + $ref: "#/components/responses/LegacyPlaylist" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Creates a playlist. + tags: + - playlists + "/playlists/{playlist_id}": + delete: + operationId: deletePlaylist + parameters: + - $ref: "#/components/parameters/fake_playlist_id" + responses: + "200": + description: Success + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Deletes a playlist. + tags: + - playlists + get: + operationId: getPlaylist + parameters: + - $ref: "#/components/parameters/playlist_id" + - $ref: "#/components/parameters/secret_token" + - $ref: "#/components/parameters/access" + responses: + "200": + $ref: "#/components/responses/Playlist" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a playlist. + tags: + - playlists + put: + operationId: updatePlaylist + parameters: + - $ref: "#/components/parameters/fake_playlist_id" + requestBody: + content: + application/json: + examples: + default: + $ref: "#/components/examples/CreateUpdatePlaylistRequest" + schema: + $ref: "#/components/schemas/CreateUpdatePlaylistRequest" + description: Playlist payload + responses: + "200": + $ref: "#/components/responses/LegacyPlaylist" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Updates a playlist. + tags: + - playlists + "/playlists/{playlist_id}/reposters": + get: + operationId: listReposts + parameters: + - $ref: "#/components/parameters/playlist_id" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/MetaUsers" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + summary: Returns a collection of playlist's reposters. + tags: + - playlists + "/playlists/{playlist_id}/tracks": + get: + operationId: getTracksUnderPlaylist + parameters: + - $ref: "#/components/parameters/playlist_id" + - $ref: "#/components/parameters/secret_token" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/linked_partitioning" + responses: + "200": + $ref: "#/components/responses/Tracks" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns tracks under a playlist. + tags: + - playlists + "/reposts/playlists/{playlist_id}": + delete: + operationId: deleteRepost + parameters: + - $ref: "#/components/parameters/repost_playlist_id" + responses: + "200": + description: Success + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Removes a repost on a playlist as the authenticated user + tags: + - reposts + post: + operationId: repostPlaylist + parameters: + - $ref: "#/components/parameters/repost_playlist_id" + responses: + "201": + description: Created + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Reposts a playlist as the authenticated user + tags: + - reposts + "/reposts/tracks/{track_id}": + delete: + operationId: deleteRepostOnTrack + parameters: + - $ref: "#/components/parameters/test_track_id" + responses: + "200": + description: Success + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Removes a repost on a track as the authenticated user + tags: + - reposts + post: + operationId: repostTrackByTrackID + parameters: + - $ref: "#/components/parameters/test_track_id" + responses: + "201": + description: Created + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Reposts a track as the authenticated user + tags: + - reposts + /resolve: + get: + operationId: resolveSoundCloudURLToResourceURL + parameters: + - $ref: "#/components/parameters/url" + responses: + "302": + $ref: "#/components/responses/Found" + security: + - AuthHeader: [] + + summary: Resolves soundcloud.com URLs to Resource URLs to use with the API. + tags: + - miscellaneous + /tracks: + get: + operationId: searchTracks + parameters: + - $ref: "#/components/parameters/q" + - $ref: "#/components/parameters/ids" + - $ref: "#/components/parameters/genres" + - $ref: "#/components/parameters/tags" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Tracks" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "500": + description: Internal Server Error + security: + - AuthHeader: [] + + summary: Performs a track search based on a query + tags: + - search + # post: + # operationId: uploadNewTrack + # requestBody: + # content: + # multipart/form-data: + # examples: + # default: + # $ref: "#/components/examples/TrackDataRequest" + # schema: + # $ref: "#/components/schemas/TrackDataRequest" + # multipart/x-www-form-urlencoded: + # schema: + # $ref: "#/components/schemas/TrackDataRequest" + # responses: + # "201": + # $ref: "#/components/responses/Track" + # "400": + # $ref: "#/components/responses/BadRequest" + # "401": + # $ref: "#/components/responses/Unauthorized" + # security: + # - AuthHeader: [] + + # summary: Uploads a new track. + # tags: + # - tracks + "/tracks/{track_id}": + delete: + operationId: deleteTrack + parameters: + - $ref: "#/components/parameters/track_id" + responses: + "200": + description: Success + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Deletes a track. + tags: + - tracks + get: + operationId: getTrackByID + parameters: + - $ref: "#/components/parameters/track_id" + - $ref: "#/components/parameters/secret_token" + responses: + "200": + $ref: "#/components/responses/Track" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a track. + tags: + - tracks + # put: + # operationId: updateTrack + # parameters: + # - $ref: "#/components/parameters/track_id" + # requestBody: + # content: + # application/json: + # schema: + # $ref: "#/components/schemas/TrackMetadataRequest" + # multipart/form-data: + # schema: + # $ref: "#/components/schemas/TrackDataRequest" + # multipart/x-www-form-urlencoded: + # schema: + # $ref: "#/components/schemas/TrackDataRequest" + # description: Track payload + # responses: + # "200": + # $ref: "#/components/responses/Track" + # "400": + # $ref: "#/components/responses/BadRequest" + # "401": + # $ref: "#/components/responses/Unauthorized" + # security: + # - AuthHeader: [] + + # summary: Updates a track's information. + # tags: + # - tracks + "/tracks/{track_id}/comments": + get: + operationId: getCommentsOnTrack + parameters: + - $ref: "#/components/parameters/track_id" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Comments" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns the comments posted on the track(track_id). + tags: + - tracks + post: + operationId: addComment + parameters: + - $ref: "#/components/parameters/track_id" + requestBody: + content: + application/json; charset=utf-8: + schema: + properties: + comment: + properties: + body: + description: Comment's content + example: test comment + type: string + timestamp: + description: >- + Timestamp of a comment. String or float representation + is supported + oneOf: + - type: string + - type: number + required: + - body + type: object + type: object + description: | + Body of a comment + required: true + responses: + "201": + $ref: "#/components/responses/Comment" + "422": + $ref: "#/components/responses/UnprocessableEntity" + "429": + $ref: "#/components/responses/TooManyRequests" + security: + - AuthHeader: [] + + summary: Returns the newly created comment on success + tags: + - tracks + "/tracks/{track_id}/favoriters": + get: + operationId: getLikedUsersOfTrack + parameters: + - $ref: "#/components/parameters/track_id" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/UsersList" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a list of users who have favorited or liked the track. + tags: + - tracks + "/tracks/{track_id}/related": + get: + operationId: listRelatedTracksOfTrack + parameters: + - $ref: "#/components/parameters/track_id" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Tracks" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns all related tracks of track on SoundCloud. + tags: + - tracks + "/tracks/{track_id}/reposters": + get: + operationId: getRepostCollection + parameters: + - $ref: "#/components/parameters/track_id" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/MetaUsers" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a collection of track's reposters. + tags: + - tracks + "/tracks/{track_id}/streams": + get: + operationId: getStreambleURL + parameters: + - $ref: "#/components/parameters/track_id" + - $ref: "#/components/parameters/secret_token" + responses: + "200": + $ref: "#/components/responses/Streams" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a track's streamable URLs + tags: + - tracks + /users: + get: + operationId: searchUser + parameters: + - $ref: "#/components/parameters/q" + - $ref: "#/components/parameters/ids" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/Users" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Performs a user search based on a query + tags: + - search + "/users/{user_id}": + get: + operationId: getUserByID + parameters: + - $ref: "#/components/parameters/user_id" + responses: + "200": + $ref: "#/components/responses/CompleteUser" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a user. + tags: + - users + "/users/{user_id}/comments": + get: + operationId: listUserComments + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/offset" + responses: + "200": + $ref: "#/components/responses/CommentsList" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a list of user's comments. + tags: + - users + "/users/{user_id}/followers": + get: + operationId: listFollowers + description: Returns a list of users that follows (user_id). + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/Users" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of user’s followers. + tags: + - users + "/users/{user_id}/followings": + get: + operationId: listUserFollowings + description: Returns list of users that (user_id) follows. + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/Users" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of user’s followings. + tags: + - users + "/users/{user_id}/likes/tracks": + get: + operationId: listUserLikedTracks + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + responses: + "200": + $ref: "#/components/responses/Tracks" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: Returns a list of user's liked tracks. + tags: + - users + "/users/{user_id}/playlists": + get: + operationId: listUserPlaylist + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + responses: + "200": + $ref: "#/components/responses/Playlists" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of user's playlists. + tags: + - users + "/users/{user_id}/tracks": + get: + operationId: listUserTracks + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/access" + - $ref: "#/components/parameters/limit" + - $ref: "#/components/parameters/linked_partitioning" + responses: + "200": + $ref: "#/components/responses/Tracks" + "401": + $ref: "#/components/responses/Unauthorized" + security: + - AuthHeader: [] + + summary: Returns a list of user's tracks. + tags: + - users + "/users/{user_id}/web-profiles": + get: + operationId: listUserLinks + parameters: + - $ref: "#/components/parameters/user_id" + - $ref: "#/components/parameters/limit" + responses: + "200": + $ref: "#/components/responses/WebProfiles" + "401": + $ref: "#/components/responses/Unauthorized" + "404": + $ref: "#/components/responses/NotFound" + security: + - AuthHeader: [] + + summary: >- + Returns list of user's links added to their profile (website, facebook, + instagram). + tags: + - users +components: + examples: + Accepted: + value: + status: 202 - Accepted + Activities: + value: + collection: + - created_at: "2020/10/12 12:02:44 +0000" + origin: + allOf: + - $ref: "#/components/examples/Track/value" + type: "track:repost" + - created_at: "2020/10/12 12:02:44 +0000" + origin: + allOf: + - $ref: "#/components/examples/Playlist/value" + type: playlist + future_href: "https://api.soundcloud.com/me/activities?limit=10&cursor=000001" + next_href: "https://api.soundcloud.com/me/activities?limit=10&cursor=00000" + AuthorizationCode: + value: + client_id: CLIENT_ID + client_secret: CLIENT_SECRET + code: 1-123456-12345678-FAbcfbe9ir2wdj0 + grant_type: authorization_code + redirect_uri: "https://mywebsite/auth/soundcloud" + BadRequest: + value: + code: 400 + link: "https://developers.soundcloud.com/docs/api/explorer/open-api" + message: "Detailed message of errors, when available" + ClientCredentials: + value: + client_id: CLIENT_ID + client_secret: CLIENT_SECRET + grant_type: client_credentials + Comment: + value: + body: comment body + created_at: "2007/09/11 15:40:24 +0000" + id: 1234 + kind: comment + timestamp: 4960 + track_id: 123456 + uri: "https://api.soundcloud.com/comments/1234" + user: + avatar_url: "https://i1.sndcdn.com/avatars-large.jpg" + followers_count: 138 + followings_count: 172 + id: 12345 + kind: user + last_modified: "2017/04/10 14:48:03 +0000" + permalink: permalink + permalink_url: "https://soundcloud.com/permalink" + public_favorites_count: 5 + reposts_count: 0 + uri: "https://api.soundcloud.com/users/12345" + username: user name + user_id: 12345 + Comments: + value: + collection: + $ref: "#/components/examples/Comment/value" + next_href: >- + https://api.soundcloud.com/collection?client_id=client_id&page_size=10&cursor=1234567 + CommentsList: + description: "Deprecated, use Comments instead." + value: + $ref: "#/components/examples/Comment/value" + CompleteUser: + value: + avatar_url: "https://i1.sndcdn.com/avatars.jpg" + city: City + country: Country + description: null + discogs_name: null + first_name: First_name + followers_count: 0 + followings_count: 0 + full_name: Full Name + id: 12345 + kind: user + last_modified: "2020/01/03 12:08:25 +0000" + last_name: Last_name + locale: en + myspace_name: null + permalink: permalink + permalink_url: "https://soundcloud.com/permalink" + plan: Free + playlist_count: 3 + primary_email_confirmed: true + private_playlists_count: 0 + private_tracks_count: 0 + public_favorites_count: 20 + quota: + unlimited_upload_quota: false + upload_seconds_left: 10800 + upload_seconds_used: 0 + reposts_count: 0 + subscriptions: + - product: + id: some-id + name: some.name + track_count: 0 + upload_seconds_left: 10800 + uri: "https://api.soundcloud.com/users/1234" + username: some.user + website: null + website_title: null + Connection: + value: + created_at: "1995/07/24 08:55:02 +0000" + display_name: Full Name + id: 123456 + kind: connection + post_favorite: true + post_publish: true + service: google_plus + type: google_plus + uri: "https://api.soundcloud.com/connections/123456" + Connections: + value: + $ref: "#/components/examples/Connection/value" + CreateUpdatePlaylistRequest: + value: + playlist: + description: Playlist for test purposes + sharing: private + title: Test Auto-created Playlist + tracks: + - id: 219787221 + - id: 783019264 + - id: 870073492 + Created: + value: + status: 201 - Created + ErrorInvalidGrant: + value: + code: 400 + link: "https://developers.soundcloud.com/docs/api/guide#authentication" + message: invalid_grant + ErrorUnsupportedGrant: + value: + code: 400 + link: "https://developers.soundcloud.com/docs/api/guide#authentication" + message: unsupported_grant + ExpiringToken: + value: + access_token: some string + expires_in: 21599 + refresh_token: some string + scope: "" + Forbidden: + value: + code: 403 + link: "https://developers.soundcloud.com/docs/api/explorer/open-api" + message: "Detailed message of errors, when available" + MetaUsers: + value: + collection: + $ref: "#/components/examples/UserOf/value" + next_href: >- + https://api.soundcloud.com/collection?client_id=client_id&page_size=10&cursor=1234567 + NonExpiringToken: + value: + access_token: some string + scope: non-expiring + NotFound: + value: + code: 404 + link: "https://developers.soundcloud.com/docs/api/explorer/open-api" + message: "Detailed message of errors, when available" + OK: + value: + status: Status(200) - OK + Password: + value: + client_id: CLIENT_ID + client_secret: CLIENT_SECRET + password: my-password + username: my-user-name + Playlist: + value: + artwork_url: "" + created_at: "2020/07/16 16:09:54 +0000" + description: null + downloadable: true + duration: 11000 + ean: null + embeddable_by: all + genre: "" + id: 12345 + kind: playlist + label: null + label_id: null + label_name: null + last_modified: "2020/09/08 09:13:00 +0000" + license: all-rights-reserved + likes_count: 0 + permalink: permalink + permalink_url: "https://soundcloud.com/userPermalink/sets/permalink" + playlist_type: "" + purchase_title: null + purchase_url: null + release: null + release_day: null + release_month: null + release_year: null + sharing: public + streamable: true + tag_list: "" + tags: "" + title: permalink + track_count: 2 + tracks: + $ref: "#/components/examples/Track/value" + tracks_uri: "https://api.soundcloud.com/playlists/12345/tracks" + type: "" + uri: "https://api.soundcloud.com/playlists/12345" + user: + $ref: "#/components/examples/UserOf/value" + user_id: 1234 + Playlists: + value: + collection: + $ref: "#/components/examples/Playlist/value" + next_href: >- + https://api.soundcloud.com/collection?client_id=client_id&page_size=10&cursor=1234567 + PlaylistsArray: + description: "Deprecated, use Playlists instead." + value: + $ref: "#/components/examples/Playlist/value" + RefreshToken: + value: + client_id: CLIENT_ID + client_secret: CLIENT_SECRET + grant_type: refresh_token + refresh_token: 1234c331329477150e7b6056ff212345 + Streams: + value: + hls_mp3_128_url: "https://cf-media.sndcdn.com/" + hls_opus_64_url: "https://cf-media.sndcdn.com/" + http_mp3_128_url: "https://cf-media.sndcdn.com/" + preview_mp3_128_url: "https://cf-media.sndcdn.com/" + Success: + value: + status: 200 - OK + Successful: + value: + status: 200 - Successful + TooManyRequests: + value: + code: 429 + link: "https://developers.soundcloud.com/docs/api/rate-limits#errors" + message: "Detailed message of errors, when available" + spam_warning_urn: "soundcloud:spam-warnings:1" + Track: + value: + access: playable + artwork_url: "https://i1.sndcdn.com/artworks-large.jpg" + available_country_codes: null + bpm: null + comment_count: 4 + commentable: true + created_at: "2019/01/15 15:40:49 +0000" + description: null + download_count: 0 + download_url: "https://api.soundcloud.com/tracks/1234/download" + downloadable: false + duration: 40000 + embeddable_by: all + favoritings_count: 271 + genre: Rock + id: 1234 + isrc: null + key_signature: null + kind: track + label_name: some label + license: all-rights-reserved + permalink_url: "https://soundcloud.com/userPermalink/trackPermalink" + playback_count: 8027 + purchase_title: null + purchase_url: null + release: null + release_day: 22 + release_month: 8 + release_year: 2019 + reposts_count: 18 + secret_uri: null + sharing: public + stream_url: "https://api.soundcloud.com/tracks/1234/stream" + streamable: true + tag_list: "" + title: Some title + uri: "https://api.soundcloud.com/tracks/1234" + user: + $ref: "#/components/examples/UserOf/value" + user_favorite: true + user_playback_count: 1 + waveform_url: "https://wave.sndcdn.com/someString.png" + TrackDataRequest: + value: + "track[artwork_data]": null + "track[asset_data]": + "track[commentable]": true + "track[description]": Public-api test sample upload + "track[downloadable]": false + "track[embeddable_by]": me + "track[genre]": Pop + "track[isrc]": null + "track[label_name]": null + "track[license]": no-rights-reserved + "track[permalink]": test-drum-sample + "track[purchase_url]": null + "track[release]": null + "track[release_date]": 2021-02-18T00:00:00.000Z + "track[sharing]": private + "track[streamable]": true + "track[tag_list]": null + "track[title]": Test drum sample + TrackMetadataRequest: + value: + "track[title]": Updated Test Track + Tracks: + value: + collection: + $ref: "#/components/examples/Track/value" + next_href: >- + https://api.soundcloud.com/collection?client_id=client_id&page_size=10&cursor=1234567 + TracksList: + description: "Deprecated, use Tracks instead." + value: + $ref: "#/components/examples/Track/value" + Unauthorized: + value: + code: 401 + link: "https://developers.soundcloud.com/docs/api/explorer/open-api" + message: "Detailed message of errors, when available" + UnprocessableEntity: + value: + code: 422 + link: "https://developers.soundcloud.com/docs/api/explorer/open-api" + message: "Detailed message of errors, when available" + User: + value: + avatar_url: "https://i1.sndcdn.com/avatars.jpg" + city: City + country: Country + created_at: "2018/01/01 12:08:25 +0000" + description: null + discogs_name: null + first_name: First_name + followers_count: 0 + followings_count: 0 + full_name: Full Name + id: 12345 + kind: user + last_modified: "2020/01/03 12:08:25 +0000" + last_name: Last_name + myspace_name: null + permalink: permalink + permalink_url: "https://soundcloud.com/permalink" + plan: Free + playlist_count: 3 + public_favorites_count: 20 + reposts_count: 0 + subscriptions: + - product: + id: some-id + name: some.name + track_count: 0 + upload_seconds_left: 10800 + uri: "https://api.soundcloud.com/users/1234" + username: some.user + website: null + website_title: null + UserOf: + value: + avatar_url: "https://i1.sndcdn.com/avatars-large.jpg" + id: 12345 + kind: user + last_modified: "2020/09/03 14:08:25 +0000" + permalink: permalink + permalink_url: "https://soundcloud.com/permalink" + uri: "https://api.soundcloud.com/users/12345" + username: user.name + Users: + value: + collection: + $ref: "#/components/examples/User/value" + next_href: >- + https://api.soundcloud.com/collection?client_id=client_id&page_size=10&cursor=1234567 + UsersList: + description: "Deprecated, use Users instead." + value: + $ref: "#/components/examples/User/value" + WebProfiles: + value: + - created_at: "1995/10/20 12:10:39 +0000" + id: 1234 + kind: web-profile + service: facebook + title: my facebook + url: "http://facebook.com" + username: username + parameters: + access: + description: > + Filters content by level of access the user (logged in or anonymous) has + to the track. The result list will include only tracks with the + specified access. Include all options if you'd like to see all possible + tracks. See `Track#access` schema for more details. + explode: false + in: query + name: access + schema: + items: + enum: + - playable + - preview + - blocked + type: string + type: array + style: form + client_id: + description: The client id belonging to your application + example: some client + in: query + name: client_id + required: true + schema: + type: string + comment_id: + description: SoundCloud comment id + example: 123456 + in: path + name: comment_id + required: true + schema: + type: integer + connection_id: + description: SoundCloud connection id + example: 123456 + in: path + name: connection_id + required: true + schema: + type: integer + fake_playlist_id: + description: SoundCloud playlist id + example: 10 + in: path + name: playlist_id + required: true + schema: + type: integer + follower_id: + description: SoundCloud User id to denote a Follower + example: 743372812 + in: path + name: follower_id + required: true + schema: + type: integer + following_id: + description: SoundCloud User id to denote a Following of a user + example: 25219981 + in: path + name: following_id + required: true + schema: + type: integer + genres: + description: A comma separated list of genres + example: "Pop,House" + in: query + name: genres + required: false + schema: + type: string + ids: + description: A comma separated list of track ids to filter on + example: "1,2,3" + in: query + name: ids + required: false + schema: + type: string + limit: + description: Number of results to return in the collection. + example: 2 + in: query + name: limit + required: false + schema: + default: 50 + maximum: 200 + minimum: 1 + type: integer + linked_partitioning: + description: >- + Returns paginated collection of items (recommended, returning a list + without pagination is deprecated and should not be used) + example: true + in: query + name: linked_partitioning + required: false + schema: + type: boolean + offset: + deprecated: true + description: "Offset of first result. Deprecated, use `linked_partitioning` instead." + example: 0 + in: query + name: offset + required: false + schema: + default: 0 + type: integer + playlist_id: + description: SoundCloud playlist id + example: 1212781357 + in: path + name: playlist_id + required: true + schema: + type: integer + q: + description: search + example: hello + in: query + name: q + required: true + schema: + type: string + redirect_uri: + description: The redirect uri you have configured for your application + example: "https://soundcloud.com" + in: query + name: redirect_uri + required: true + schema: + type: string + repost_playlist_id: + description: SoundCloud playlist id + example: 1205584273 + in: path + name: playlist_id + required: true + schema: + type: integer + response_type: + description: It's recommended to use "code" here + example: code + in: query + name: response_type + required: true + schema: + enum: + - code + - token + - code_and_token + type: string + scope: + description: Scope + example: default + in: query + name: scope + required: true + schema: + type: string + secret_token: + description: A secret token to fetch private playlists/tracks + in: query + name: secret_token + required: false + schema: + type: string + state: + description: >- + Any value included here will be appended to the redirect URI. Use this + for CSRF protection. + example: encrypted_session_info + in: query + name: state + required: false + schema: + type: string + tag: + description: tag + example: some tag + in: path + name: tag + required: true + schema: + type: string + tags: + description: A comma separated list of tags + example: test + in: query + name: tags + required: false + schema: + type: string + test_track_id: + description: SoundCloud Track id + example: 1015448728 + in: path + name: track_id + required: true + schema: + type: integer + track_id: + description: SoundCloud Track id + example: 308946187 + in: path + name: track_id + required: true + schema: + type: integer + url: + description: SoundCloud URL + example: "https://soundcloud.com/user-434241656" + in: query + name: url + required: true + schema: + type: string + user_id: + description: SoundCloud User id + example: 948745750 + in: path + name: user_id + required: true + schema: + type: integer + user_id_to_follow: + description: SoundCloud User id + example: 743372812 + in: path + name: user_id + required: true + schema: + type: integer + responses: + Accepted: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Accepted" + description: Accepted + Activities: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Activities" + schema: + $ref: "#/components/schemas/Activities" + description: Success + BadRequest: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/BadRequest" + schema: + $ref: "#/components/schemas/Error" + description: Bad Request + Comment: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Comment" + schema: + $ref: "#/components/schemas/Comment" + description: Success + Comments: + content: + application/json; charset=utf-8: + examples: + commentsList: + $ref: "#/components/examples/CommentsList" + default: + $ref: "#/components/examples/Comments" + schema: + oneOf: + - $ref: "#/components/schemas/Comments" + - $ref: "#/components/schemas/CommentsList" + description: Success + CommentsList: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/CommentsList" + schema: + $ref: "#/components/schemas/CommentsList" + description: Success + CompleteUser: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/CompleteUser" + schema: + $ref: "#/components/schemas/CompleteUser" + description: Success + Connection: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Connection" + schema: + $ref: "#/components/schemas/Connection" + description: Success + Connections: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Connections" + schema: + $ref: "#/components/schemas/Connections" + description: Success + Created: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Created" + description: Created + Forbidden: + content: + application/json: + examples: + default: + $ref: "#/components/examples/Forbidden" + schema: + $ref: "#/components/schemas/Error" + description: Forbidden + Found: + content: + application/json; charset=utf-8: + schema: + $ref: "#/components/schemas/Found" + description: Found + FoundHtml: + content: + application/json; charset=utf-8: + schema: + type: string + description: Found + LegacyPlaylist: + content: + application/json; charset=utf-8: + schema: + description: Soundcloud Playlist Object + properties: + artwork_url: + description: URL to a JPEG image. + type: string + created_at: + description: Created timestamp. + type: string + description: + description: Playlist description. + type: string + downloadable: + description: is downloadable. + type: boolean + duration: + description: Playlist duration. + type: integer + ean: + description: European Article Number. + type: string + embeddable_by: + description: Embeddable by. + type: string + genre: + description: Playlist genre. + type: string + id: + description: Playlist identifier. + type: integer + kind: + description: Type of Soundcloud object (playlist). + type: string + label_id: + description: Label user identifier. + type: integer + label_name: + description: Label name. + type: string + last_modified: + description: Last modified timestamp. + type: string + license: + description: License. + type: string + permalink: + description: Playlist permalink. + type: string + permalink_url: + description: Playlist permalink URL. + type: string + playlist_type: + description: Type of playlist. + type: string + purchase_title: + description: Purchase title. + type: string + purchase_url: + description: Purchase URL. + type: string + release: + description: Release. + type: string + release_day: + description: Day of release. + type: integer + release_month: + description: Month of release. + type: integer + release_year: + description: Year of release. + type: integer + sharing: + description: Type of sharing (private/public). + type: string + streamable: + description: Is streamable. + type: boolean + tag_list: + description: Tags. + type: string + title: + description: Playlist title. + type: string + track_count: + description: Count of tracks. + type: integer + tracks: + description: List of tracks. + items: + description: Soundcloud Track object. + properties: + artwork_url: + description: URL to a JPEG image. + type: string + bpm: + description: Tempo. + type: integer + comment_count: + description: Number of comments. + type: integer + commentable: + description: Is commentable. + type: boolean + created_at: + description: Created timestamp. + type: string + description: + description: Track description. + type: string + download_count: + description: NUmber of downloads. + type: integer + downloadable: + description: Is downloadable. + type: string + duration: + description: Track duration. + type: integer + embeddable_by: + deprecated: true + description: Embeddable by. + type: string + favoritings_count: + description: Number of favoritings. + type: integer + genre: + description: Genre + type: string + id: + description: Track identifier. + type: integer + isrc: + description: ISRC code. + type: string + key_signature: + description: Key signature. + type: string + kind: + description: Type of object (track). + type: string + label_name: + description: Label user name. + type: string + license: + description: License + type: string + permalink_url: + description: Permalink URL. + type: string + playback_count: + description: Number of plays. + type: integer + purchase_title: + description: Purchase title. + type: string + purchase_url: + description: Purchase URL. + type: string + release: + description: Release. + type: string + release_day: + description: Day of release. + type: integer + release_month: + description: Month of release. + type: integer + release_year: + description: Year of release. + type: integer + sharing: + description: Type of sharing (public/private). + type: string + stream_url: + description: URL to stream. + type: string + streamable: + description: Is streamable. + type: boolean + tag_list: + description: Tags. + type: string + title: + description: Track title. + type: string + uri: + description: Track URI. + type: string + user: + $ref: "#/components/schemas/MetaUser" + user_favorite: + description: Is user's favourite. + type: boolean + user_playback_count: + description: Number of plays by a user. + type: integer + waveform_url: + description: Waveform URL. + type: string + type: object + type: array + type: + description: Playlist type. + type: string + uri: + description: Playlist URI. + type: string + user: + $ref: "#/components/schemas/MetaUser" + user_id: + description: User identifier. + type: integer + type: object + description: Success + MetaUser: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/UserOf" + schema: + $ref: "#/components/schemas/MetaUser" + description: Success + MetaUsers: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/MetaUsers" + schema: + $ref: "#/components/schemas/MetaUsers" + description: Success + NotFound: + content: + application/json: + examples: + default: + $ref: "#/components/examples/NotFound" + schema: + $ref: "#/components/schemas/Error" + description: Not Found + Playlist: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Playlist" + schema: + $ref: "#/components/schemas/Playlist" + description: Success + Playlists: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Playlists" + playlistsArray: + $ref: "#/components/examples/PlaylistsArray" + schema: + oneOf: + - $ref: "#/components/schemas/Playlists" + - $ref: "#/components/schemas/PlaylistsArray" + description: Success + PlaylistsArray: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/PlaylistsArray" + schema: + $ref: "#/components/schemas/PlaylistsArray" + description: Success + Streams: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Streams" + schema: + $ref: "#/components/schemas/Streams" + description: Success + Success: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Success" + description: Success + Successful: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Successful" + description: Success + TooManyRequests: + content: + application/json: + examples: + default: + $ref: "#/components/examples/TooManyRequests" + schema: + $ref: "#/components/schemas/TooManyRequests" + description: Too Many Requests + Track: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Track" + schema: + $ref: "#/components/schemas/Track" + description: Success + Tracks: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Tracks" + tracksList: + $ref: "#/components/examples/TracksList" + schema: + oneOf: + - $ref: "#/components/schemas/Tracks" + - $ref: "#/components/schemas/TracksList" + description: Success + TracksList: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/TracksList" + schema: + $ref: "#/components/schemas/TracksList" + description: Success + Unauthorized: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Unauthorized" + schema: + $ref: "#/components/schemas/Error" + description: Unauthorized + UnprocessableEntity: + content: + application/json: + examples: + default: + $ref: "#/components/examples/UnprocessableEntity" + schema: + $ref: "#/components/schemas/Error" + description: Unprocessable Entity + User: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/User" + schema: + $ref: "#/components/schemas/User" + description: Success + Users: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/Users" + usersList: + $ref: "#/components/examples/UsersList" + schema: + oneOf: + - $ref: "#/components/schemas/Users" + - $ref: "#/components/schemas/UsersList" + description: Success + UsersList: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/UsersList" + schema: + $ref: "#/components/schemas/UsersList" + description: Success + WebProfiles: + content: + application/json; charset=utf-8: + examples: + default: + $ref: "#/components/examples/WebProfiles" + schema: + $ref: "#/components/schemas/WebProfiles" + description: Success + schemas: + Activities: + description: User's activities. + properties: + collection: + items: + properties: + created_at: + description: Created timestamp. + type: string + origin: + anyOf: + - $ref: "#/components/schemas/Track" + - $ref: "#/components/schemas/Playlist" + description: Origin. + type: object + type: + description: Type of activity (track). + type: string + type: object + type: array + future_href: + type: string + next_href: + type: string + type: object + Comment: + description: User's Comment + properties: + body: + description: Comment body. + type: string + created_at: + description: Created timestamp. + type: string + id: + description: Identifier. + type: integer + kind: + description: Kind (comment). + type: string + timestamp: + description: Timestamp. + type: string + track_id: + description: Track's identifier. + type: integer + uri: + description: Comment's URL. + type: string + user: + description: SoundCloud User object + properties: + avatar_url: + description: URL to a JPEG image. + type: string + followers_count: + description: number of followers. + type: integer + followings_count: + description: number of followed users. + type: integer + id: + description: unique identifier + type: integer + kind: + description: kind of resource. + type: string + last_modified: + description: last modified timestamp. + type: string + permalink: + description: permalink of the resource. + type: string + permalink_url: + description: URL to the SoundCloud.com page. + type: string + reposts_count: + description: number of reposts from user + type: integer + uri: + description: API resource URL. + type: string + username: + description: username + type: string + type: object + user_id: + description: User's identifier. + type: integer + type: object + Comments: + properties: + collection: + items: + $ref: "#/components/schemas/Comment" + type: array + next_href: + nullable: true + type: string + type: object + CommentsList: + deprecated: true + items: + $ref: "#/components/schemas/Comment" + type: array + CompleteUser: + description: SoundCloud Complete User object + properties: + avatar_url: + description: URL to a JPEG image. + type: string + city: + description: city. + type: string + country: + description: country. + type: string + description: + description: description. + type: string + discogs_name: + description: discogs name. + type: string + first_name: + description: first name. + type: string + followers_count: + description: number of followers. + type: integer + followings_count: + description: number of followed users. + type: integer + full_name: + description: first and last name. + type: string + id: + description: unique identifier + type: integer + kind: + description: kind of resource. + type: string + last_modified: + description: last modified timestamp. + type: string + last_name: + description: last name. + type: string + locale: + description: locale. + type: string + myspace_name: + deprecated: true + description: myspace name + type: string + permalink: + description: permalink of the resource. + type: string + permalink_url: + description: URL to the SoundCloud.com page. + type: string + plan: + description: subscription plan of the user. + type: string + playlist_count: + description: number of public playlists. + type: integer + primary_email_confirmed: + description: boolean if email is confirmed. + type: boolean + private_playlists_count: + description: number of private playlists. + type: integer + private_tracks_count: + description: number of private tracks. + type: integer + public_favorites_count: + description: number of favorited public tracks + type: integer + quota: + description: user's upload quota + properties: + unlimited_upload_quota: + description: unlimited upload quota. + type: boolean + upload_seconds_used: + description: upload seconds used. + type: integer + type: object + reposts_count: + description: number of reposts from user + type: integer + subscriptions: + description: a list subscriptions associated with the user + items: + anyOf: + - description: subscription + properties: + product: + description: product + properties: + id: + description: subscription id instance. + type: string + name: + description: subscription name instance. + type: string + type: object + recurring: + description: if the subscription is recurring or not + type: boolean + type: object + items: {} + type: array + track_count: + description: number of public tracks. + type: integer + uri: + description: API resource URL. + type: string + username: + description: username + type: string + website: + description: a URL to the website. + type: string + website_title: + description: a custom title for the website. + type: string + type: object + Connection: + properties: + created_at: + description: Created timestamp. + type: string + display_name: + description: Full Name. + type: string + id: + description: Unique identifier + type: integer + kind: + description: Kind of resource. + type: string + post_favorite: + deprecated: true + type: boolean + post_publish: + deprecated: true + type: boolean + service: + description: Service. + type: string + type: + description: Type. + type: string + uri: + description: The external link URI. + type: string + type: object + Connections: + items: + $ref: "#/components/schemas/Connection" + type: array + CreateUpdatePlaylistRequest: + properties: + playlist: + properties: + description: + description: Description of the playlist + type: string + sharing: + description: public or private + enum: + - public + - private + type: string + title: + description: Title of the playlist + type: string + tracks: + description: List of tracks to add to playlist + items: + properties: + id: + description: SoundCloud track id + type: string + required: + - id + type: object + type: array + type: object + type: object + Error: + properties: + code: + type: integer + error: + deprecated: true + nullable: true + type: string + errors: + deprecated: true + items: {} + type: array + link: + type: string + message: + type: string + status: + deprecated: true + type: string + type: object + Found: + properties: + location: + description: Location URL of the resource. + type: string + status: + description: Status code. + type: string + type: object + MetaUser: + description: SoundCloud User object. + nullable: true + properties: + avatar_url: + description: URL to a JPEG image + type: string + created_at: + description: profile creation datetime + format: date-time + type: string + id: + description: unique identifier + type: integer + kind: + description: kind of resource + type: string + last_modified: + description: last modified datetime + format: date-time + type: string + permalink: + description: permalink of the resource + type: string + permalink_url: + description: URL to the SoundCloud.com page + type: string + uri: + description: API resource URL + type: string + username: + description: username + type: string + type: object + MetaUsers: + properties: + collection: + items: + $ref: "#/components/schemas/MetaUser" + type: array + next_href: + type: string + type: object + Playlist: + description: Soundcloud Playlist Object + properties: + artwork_url: + description: URL to a JPEG image. + type: string + created_at: + description: Created timestamp. + type: string + description: + description: Playlist description. + type: string + downloadable: + description: is downloadable. + type: boolean + duration: + description: Playlist duration. + type: integer + ean: + description: European Article Number. + type: string + embeddable_by: + description: Embeddable by. + type: string + genre: + description: Playlist genre. + type: string + id: + description: Playlist identifier. + type: integer + kind: + description: Type of Soundcloud object (playlist). + type: string + label: + $ref: "#/components/schemas/MetaUser" + label_id: + description: Label user identifier. + type: integer + label_name: + description: Label name. + type: string + last_modified: + description: Last modified timestamp. + type: string + license: + description: License. + type: string + likes_count: + description: Count of playlist likes. + type: integer + permalink: + description: Playlist permalink. + type: string + permalink_url: + description: Playlist permalink URL. + type: string + playlist_type: + description: Type of playlist. + type: string + purchase_title: + description: Purchase title. + type: string + purchase_url: + description: Purchase URL. + type: string + release: + description: Release. + type: string + release_day: + description: Day of release. + type: integer + release_month: + description: Month of release. + type: integer + release_year: + description: Year of release. + type: integer + sharing: + description: Type of sharing (private/public). + type: string + streamable: + description: Is streamable. + type: boolean + tag_list: + description: Tags. + type: string + tags: + description: Tags. + nullable: true + type: string + title: + description: Playlist title. + type: string + track_count: + description: Count of tracks. + type: integer + tracks: + description: List of tracks. + items: + $ref: "#/components/schemas/Track" + type: array + tracks_uri: + description: tracks URI. + nullable: true + type: string + type: + description: Playlist type. + type: string + uri: + description: Playlist URI. + type: string + user: + $ref: "#/components/schemas/MetaUser" + user_id: + description: User identifier. + type: integer + type: object + Playlists: + properties: + collection: + items: + $ref: "#/components/schemas/Playlist" + type: array + next_href: + type: string + type: object + PlaylistsArray: + deprecated: true + items: + $ref: "#/components/schemas/Playlist" + type: array + Streams: + properties: + hls_mp3_128_url: + type: string + hls_opus_64_url: + type: string + http_mp3_128_url: + type: string + preview_mp3_128_url: + type: string + type: object + TooManyRequests: + allOf: + - $ref: "#/components/schemas/Error" + - properties: + spam_warning_urn: + type: string + type: object + Track: + description: Soundcloud Track object. + properties: + access: + description: | + Level of access the user (logged in or anonymous) has to the track. + * `playable` - user is allowed to listen to a full track. + * `preview` - user is allowed to preview a track, meaning a snippet is available + * `blocked` - user can only see the metadata of a track, no streaming is possible + enum: + - playable + - preview + - blocked + - null + nullable: true + type: string + artwork_url: + description: URL to a JPEG image. + type: string + available_country_codes: + description: List of countries where track is available. + type: string + bpm: + description: Tempo. + type: integer + comment_count: + description: Number of comments. + type: integer + commentable: + description: Is commentable. + type: boolean + created_at: + description: Created timestamp. + type: string + description: + description: Track description. + type: string + download_count: + description: NUmber of downloads. + type: integer + download_url: + description: URL to download a track. + type: string + downloadable: + description: Is downloadable. + type: string + duration: + description: Track duration. + type: integer + embeddable_by: + deprecated: true + description: Embeddable by. + type: string + favoritings_count: + description: Number of favoritings. + type: integer + genre: + description: Genre + type: string + id: + description: Track identifier. + type: integer + isrc: + description: ISRC code. + type: string + key_signature: + description: Key signature. + type: string + kind: + description: Type of object (track). + type: string + label_name: + description: Label user name. + type: string + license: + description: License + type: string + permalink_url: + description: Permalink URL. + type: string + playback_count: + description: Number of plays. + type: integer + purchase_title: + description: Purchase title. + type: string + purchase_url: + description: Purchase URL. + type: string + release: + description: Release. + type: string + release_day: + description: Day of release. + type: integer + release_month: + description: Month of release. + type: integer + release_year: + description: Year of release. + type: integer + reposts_count: + description: Number of reposts. + type: integer + secret_uri: + description: Secret URL. + type: string + sharing: + description: Type of sharing (public/private). + type: string + stream_url: + description: URL to stream. + type: string + streamable: + description: Is streamable. + type: boolean + tag_list: + description: Tags. + type: string + title: + description: Track title. + type: string + uri: + description: Track URI. + type: string + user: + $ref: "#/components/schemas/MetaUser" + user_favorite: + description: Is user's favourite. + type: boolean + user_playback_count: + description: Number of plays by a user. + type: integer + waveform_url: + description: Waveform URL. + type: string + type: object + TrackDataRequest: + properties: + "track[artwork_data]": + format: binary + title: "Only for uploading, for PRO users" + type: string + "track[asset_data]": + format: binary + title: Only for uploading + type: string + "track[commentable]": + default: true + type: boolean + "track[description]": + type: string + "track[downloadable]": + default: true + type: boolean + "track[embeddable_by]": + description: 'who can embed this track "all", "me", or "none"' + enum: + - all + - me + - none + type: string + "track[genre]": + type: string + "track[isrc]": + type: string + "track[label_name]": + type: string + "track[license]": + description: >- + Possible values: no-rights-reserved, all-rights-reserved, cc-by, + cc-by-nc, cc-by-nd, cc-by-sa, cc-by-nc-nd, cc-by-nc-sa + enum: + - no-rights-reserved + - all-rights-reserved + - cc-by + - cc-by-nc + - cc-by-nd + - cc-by-sa + - cc-by-nc-nd + - cc-by-nc-sa + type: string + "track[permalink]": + type: string + "track[purchase_url]": + type: string + "track[release]": + type: string + "track[release_date]": + description: "string, formatted as yyyy-mm-dd, representing release date" + title: write only! + type: string + "track[sharing]": + default: public + enum: + - public + - private + type: string + "track[streamable]": + default: true + type: boolean + "track[tag_list]": + description: >- + The tag_list property contains a list of tags separated by spaces. + Multiword tags are quoted in double quotes. We also support machine + tags that follow the pattern NAMESPACE:KEY=VALUE. For example: + geo:lat=43.555 camel:size=medium “machine:tag=with space” Machine + tags are not revealed to the user on the track pages. + type: string + "track[title]": + type: string + type: object + TrackMetadataRequest: + properties: + track: + properties: + commentable: + default: true + type: boolean + description: + type: string + downloadable: + default: true + type: boolean + embeddable_by: + description: 'who can embed this track "all", "me", or "none"' + enum: + - all + - me + - none + type: string + genre: + type: string + isrc: + type: string + label_name: + type: string + license: + description: >- + Possible values: no-rights-reserved, all-rights-reserved, cc-by, + cc-by-nc, cc-by-nd, cc-by-sa, cc-by-nc-nd, cc-by-nc-sa + enum: + - no-rights-reserved + - all-rights-reserved + - cc-by + - cc-by-nc + - cc-by-nd + - cc-by-sa + - cc-by-nc-nd + - cc-by-nc-sa + type: string + permalink: + type: string + purchase_url: + type: string + release: + type: string + release_date: + description: "string, formatted as yyyy-mm-dd, representing release date" + title: write only! + type: string + sharing: + default: public + enum: + - public + - private + type: string + streamable: + default: true + type: boolean + tag_list: + description: >- + The tag_list property contains a list of tags separated by + spaces. Multiword tags are quoted in double quotes. We also + support machine tags that follow the pattern + NAMESPACE:KEY=VALUE. For example: geo:lat=43.555 + camel:size=medium “machine:tag=with space” Machine tags are not + revealed to the user on the track pages. + type: string + title: + type: string + type: object + type: object + Tracks: + properties: + collection: + items: + $ref: "#/components/schemas/Track" + type: array + next_href: + type: string + type: object + TracksList: + deprecated: true + items: + $ref: "#/components/schemas/Track" + type: array + User: + description: SoundCloud User object + properties: + avatar_url: + description: URL to a JPEG image + type: string + city: + description: city + type: string + country: + description: country + type: string + created_at: + description: profile creation datetime + format: date-time + type: string + description: + description: description + type: string + discogs_name: + description: discogs name + type: string + first_name: + description: first name + type: string + followers_count: + description: number of followers + type: integer + followings_count: + description: number of followed users + type: integer + full_name: + description: first and last name + type: string + id: + description: unique identifier + type: integer + kind: + description: kind of resource + type: string + last_modified: + description: last modified datetime + format: date-time + type: string + last_name: + description: last name + type: string + myspace_name: + deprecated: true + description: myspace name + type: string + permalink: + description: permalink of the resource + type: string + permalink_url: + description: URL to the SoundCloud.com page + type: string + plan: + description: subscription plan of the user + type: string + playlist_count: + description: number of public playlists + type: integer + public_favorites_count: + description: number of favorited public tracks + type: integer + reposts_count: + description: number of reposts from user + type: integer + subscriptions: + deprecated: true + description: a list subscriptions associated with the user + items: + anyOf: + - description: subscription + properties: + product: + description: product + properties: + id: + description: subscription id instance. + type: string + name: + description: subscription name instance. + type: string + type: object + recurring: + description: if the subscription is recurring or not + type: boolean + type: object + items: {} + type: array + track_count: + description: number of public tracks + type: integer + uri: + description: API resource URL + type: string + username: + description: username + type: string + website: + description: a URL to the website + type: string + website_title: + description: a custom title for the website + type: string + type: object + Users: + properties: + collection: + items: + $ref: "#/components/schemas/User" + type: array + next_href: + type: string + type: object + UsersList: + deprecated: true + items: + description: SoundCloud User object + properties: + avatar_url: + description: URL to a JPEG image + type: string + city: + description: city + type: string + country: + description: country + type: string + description: + description: description + type: string + discogs_name: + description: discogs name + type: string + first_name: + description: first name + type: string + followers_count: + description: number of followers + type: integer + followings_count: + description: number of followed users + type: integer + full_name: + description: first and last name + type: string + id: + description: unique identifier + type: integer + kind: + description: kind of resource + type: string + last_modified: + description: last modified datetime + format: date-time + type: string + last_name: + description: last name + type: string + myspace_name: + deprecated: true + description: myspace name + type: string + permalink: + description: permalink of the resource + type: string + permalink_url: + description: URL to the SoundCloud.com page + type: string + plan: + description: subscription plan of the user + type: string + playlist_count: + description: number of public playlists + type: integer + public_favorites_count: + description: number of favorited public tracks + type: integer + reposts_count: + description: number of reposts from user + type: integer + subscriptions: + deprecated: true + description: a list subscriptions associated with the user + items: + anyOf: + - description: subscription + properties: + product: + description: product + properties: + id: + description: subscription id instance. + type: string + name: + description: subscription name instance. + type: string + type: object + recurring: + description: if the subscription is recurring or not + type: boolean + type: object + items: {} + type: array + track_count: + description: number of public tracks + type: integer + uri: + description: API resource URL + type: string + username: + description: username + type: string + website: + description: a URL to the website + type: string + website_title: + description: a custom title for the website + type: string + type: object + type: array + WebProfiles: + description: User's links added to their profile + items: + properties: + created_at: + description: Timestamp of when the link was added to the profile. + type: string + id: + description: Id + type: integer + kind: + description: Kind + type: string + service: + description: Service or platform + type: string + title: + description: Link's title + type: string + url: + description: URL of the external link + type: string + username: + description: Username extracted from the external link + type: string + type: object + type: array + securitySchemes: + AuthHeader: + type: apiKey + in: header + name: Authorization + description: Represents API Key `Authorization` \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/stripe.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/stripe.yaml new file mode 100644 index 000000000..35f1c93aa --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/stripe.yaml @@ -0,0 +1,31001 @@ +components: + schemas: + getInvoicesUpcomingRequestBody: + properties: + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/item_billing_thresholds_param" + - enum: + - '' + type: string + clear_usage: + type: boolean + deleted: + type: boolean + id: + maxLength: 5000 + type: string + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + recurring: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: recurring_adhoc + type: object + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + - recurring + title: recurring_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: subscription_item_update_params + type: object + transfer_data_specs: + properties: + amount_percent: + type: number + destination: + type: string + required: + - destination + title: transfer_data_specs + type: object + discounts_data_param: + items: + properties: + coupon: + maxLength: 5000 + type: string + discount: + maxLength: 5000 + type: string + title: discounts_data_param + type: object + type: array + invoice_item_preview_params: + properties: + amount: + type: integer + currency: + type: string + description: + maxLength: 5000 + type: string + discountable: + type: boolean + discounts: + anyOf: + - $ref: "#/components/schemas/discounts_data_param" + - enum: + - '' + type: string + invoiceitem: + maxLength: 5000 + type: string + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + period: + properties: + end: + format: unix-time + type: integer + start: + format: unix-time + type: integer + required: + - end + - start + title: period + type: object + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + title: one_time_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + title: invoice_item_preview_params + type: object + CreatedDetails: + anyOf: + - $ref: '#/components/schemas/CreatedFilterOptions' + - type: integer + CreatedFilterOptions: + properties: + gt: + type: integer + gte: + type: integer + lt: + type: integer + lte: + type: integer + title: range_query_specs + type: object + customer_adresss: + properties: + city: + maxLength: 5000 + type: string + country: + maxLength: 5000 + type: string + line1: + maxLength: 5000 + type: string + line2: + maxLength: 5000 + type: string + postal_code: + maxLength: 5000 + type: string + state: + maxLength: 5000 + type: string + title: optional_fields_address + type: object + customer_address_with_name: + properties: + address: + properties: + city: + maxLength: 5000 + type: string + country: + maxLength: 5000 + type: string + line1: + maxLength: 5000 + type: string + line2: + maxLength: 5000 + type: string + postal_code: + maxLength: 5000 + type: string + state: + maxLength: 5000 + type: string + title: optional_fields_address + type: object + name: + maxLength: 5000 + type: string + phone: + maxLength: 5000 + type: string + required: + - address + - name + title: customer_shipping + type: object + customer_bank_account_details: + properties: + account_holder_name: + maxLength: 5000 + type: string + account_holder_type: + enum: + - company + - individual + maxLength: 5000 + type: string + account_number: + maxLength: 5000 + type: string + country: + maxLength: 5000 + type: string + currency: + type: string + object: + enum: + - bank_account + maxLength: 5000 + type: string + routing_number: + maxLength: 5000 + type: string + required: + - account_number + - country + title: customer_payment_source_bank_account + type: object + customer_card_details: + properties: + address_city: + maxLength: 5000 + type: string + address_country: + maxLength: 5000 + type: string + address_line1: + maxLength: 5000 + type: string + address_line2: + maxLength: 5000 + type: string + address_state: + maxLength: 5000 + type: string + address_zip: + maxLength: 5000 + type: string + cvc: + maxLength: 5000 + type: string + exp_month: + type: integer + exp_year: + type: integer + metadata: + additionalProperties: + type: string + type: object + name: + maxLength: 5000 + type: string + number: + maxLength: 5000 + type: string + object: + enum: + - card + maxLength: 5000 + type: string + required: + - exp_month + - exp_year + - number + title: customer_payment_source_card + type: object + invoice_settings_custom_fields: + items: + properties: + name: + maxLength: 30 + type: string + value: + maxLength: 30 + type: string + required: + - name + - value + title: custom_field_params + type: object + type: array + customer_shipping_address: + properties: + address: + properties: + city: + maxLength: 5000 + type: string + country: + maxLength: 5000 + type: string + line1: + maxLength: 5000 + type: string + line2: + maxLength: 5000 + type: string + postal_code: + maxLength: 5000 + type: string + state: + maxLength: 5000 + type: string + title: optional_fields_address + type: object + name: + maxLength: 5000 + type: string + phone: + maxLength: 5000 + type: string + required: + - address + - name + title: customer_shipping + type: object + billing_details_address: + properties: + city: + maxLength: 5000 + type: string + country: + maxLength: 5000 + type: string + line1: + maxLength: 5000 + type: string + line2: + maxLength: 5000 + type: string + postal_code: + maxLength: 5000 + type: string + state: + maxLength: 5000 + type: string + title: billing_details_address + type: object + card_details_params: + properties: + cvc: + maxLength: 5000 + type: string + exp_month: + type: integer + exp_year: + type: integer + number: + maxLength: 5000 + type: string + required: + - exp_month + - exp_year + - number + title: card_details_params + type: object + token_paramas: + properties: + token: + maxLength: 5000 + type: string + required: + - token + title: token_params + type: object + range_query_specs: + properties: + gt: + type: integer + gte: + type: integer + lt: + type: integer + lte: + type: integer + title: range_query_specs + type: object + tax_rate_array: + items: + maxLength: 5000 + type: string + type: array + billing_threshold_params: + properties: + amount_gte: + type: integer + reset_billing_cycle_anchor: + type: boolean + title: billing_thresholds_param + type: object + item_billing_thresholds_param: + properties: + usage_gte: + type: integer + required: + - usage_gte + title: item_billing_thresholds_param + type: object + additional_properties: + additionalProperties: + type: string + type: object + bancontact_invoice_payment_method_options_param: + properties: + preferred_language: + enum: + - de + - en + - fr + - nl + type: string + title: invoice_payment_method_options_param + type: object + card_invoice_payment_method_options_param: + properties: + request_three_d_secure: + enum: + - any + - automatic + type: string + title: invoice_payment_method_options_param + type: object + payment_method_types_array: + items: + enum: + - ach_credit_transfer + - ach_debit + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - fpx + - giropay + - ideal + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + type: array + pending_invoice_item_interval_params: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: pending_invoice_item_interval_params + type: object + billing_thresholds: + properties: + usage_gte: + type: integer + required: + - usage_gte + title: item_billing_thresholds_param + type: object + package_dimentions_specs: + properties: + height: + type: number + length: + type: number + weight: + type: number + width: + type: number + required: + - height + - length + - weight + - width + title: package_dimensions_specs + type: object + + ################################################################################################################################### + account: + description: |- + This is an object representing a Stripe account. You can retrieve it to see + properties on the account like its current e-mail address or if the account is + enabled yet to make live charges. + + Some properties, marked below, are available only to platforms that want to + [create and manage Express or Custom accounts](https://stripe.com/docs/connect/accounts). + properties: + business_profile: + anyOf: + - "$ref": "#/components/schemas/account_business_profile" + description: Business information about the account. + nullable: true + business_type: + description: The business type. + enum: + - company + - government_entity + - individual + - non_profit + nullable: true + type: string + x-stripeBypassValidation: true + capabilities: + "$ref": "#/components/schemas/account_capabilities" + charges_enabled: + description: Whether the account can create live charges. + type: boolean + company: + "$ref": "#/components/schemas/legal_entity_company" + controller: + "$ref": "#/components/schemas/account_controller" + country: + description: The account's country. + maxLength: 5000 + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + default_currency: + description: Three-letter ISO currency code representing the default currency + for the account. This must be a currency that [Stripe supports in the + account's country](https://stripe.com/docs/payouts). + maxLength: 5000 + type: string + details_submitted: + description: Whether account details have been submitted. Standard accounts + cannot receive payouts before this is true. + type: boolean + email: + description: 'An email address associated with the account. You can treat + this as metadata: it is not used for authentication or messaging account + holders.' + maxLength: 5000 + nullable: true + type: string + external_accounts: + description: External accounts (bank accounts and debit cards) currently + attached to this account + properties: + data: + description: The list contains all external accounts that have been + attached to the Stripe account. These may be bank accounts or cards. + items: + anyOf: + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/card" + title: Polymorphic + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: ExternalAccountList + type: object + x-expandableFields: + - data + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + individual: + "$ref": "#/components/schemas/person" + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - account + type: string + payouts_enabled: + description: Whether Stripe can send payouts to this account. + type: boolean + requirements: + "$ref": "#/components/schemas/account_requirements" + settings: + anyOf: + - "$ref": "#/components/schemas/account_settings" + description: Options for customizing how the account functions within Stripe. + nullable: true + tos_acceptance: + "$ref": "#/components/schemas/account_tos_acceptance" + type: + description: The Stripe account type. Can be `standard`, `express`, or `custom`. + enum: + - custom + - express + - standard + type: string + required: + - id + - object + title: Account + type: object + x-expandableFields: + - business_profile + - capabilities + - company + - controller + - external_accounts + - individual + - requirements + - settings + - tos_acceptance + x-resourceId: account + account_bacs_debit_payments_settings: + description: '' + properties: + display_name: + description: The Bacs Direct Debit Display Name for this account. For payments + made with Bacs Direct Debit, this will appear on the mandate, and as the + statement descriptor. + maxLength: 5000 + type: string + title: AccountBacsDebitPaymentsSettings + type: object + x-expandableFields: [] + account_branding_settings: + description: '' + properties: + icon: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + An icon for the account. Must be square and at least 128px x 128px." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + logo: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + A logo for the account that will be used in Checkout instead of the icon + and without the account's name next to it if provided. Must be at least + 128px x 128px." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + primary_color: + description: A CSS hex color value representing the primary branding color + for this account + maxLength: 5000 + nullable: true + type: string + secondary_color: + description: A CSS hex color value representing the secondary branding color + for this account + maxLength: 5000 + nullable: true + type: string + title: AccountBrandingSettings + type: object + x-expandableFields: + - icon + - logo + account_business_profile: + description: '' + properties: + mcc: + description: "[The merchant category code for the account](https://stripe.com/docs/connect/setting-mcc). + MCCs are used to classify businesses based on the goods or services they + provide." + maxLength: 5000 + nullable: true + type: string + name: + description: The customer-facing business name. + maxLength: 5000 + nullable: true + type: string + product_description: + description: Internal-only description of the product sold or service provided + by the business. It's used by Stripe for risk and underwriting purposes. + maxLength: 40000 + nullable: true + type: string + support_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: A publicly available mailing address for sending support issues + to. + nullable: true + support_email: + description: A publicly available email address for sending support issues + to. + maxLength: 5000 + nullable: true + type: string + support_phone: + description: A publicly available phone number to call with support issues. + maxLength: 5000 + nullable: true + type: string + support_url: + description: A publicly available website for handling support issues. + maxLength: 5000 + nullable: true + type: string + url: + description: The business's publicly available website. + maxLength: 5000 + nullable: true + type: string + title: AccountBusinessProfile + type: object + x-expandableFields: + - support_address + account_capabilities: + description: '' + properties: + acss_debit_payments: + description: The status of the ACSS Direct Debits payments capability of + the account, or whether the account can directly process ACSS Direct Debits + charges. + enum: + - active + - inactive + - pending + type: string + afterpay_clearpay_payments: + description: The status of the Afterpay Clearpay capability of the account, + or whether the account can directly process Afterpay Clearpay charges. + enum: + - active + - inactive + - pending + type: string + au_becs_debit_payments: + description: The status of the BECS Direct Debit (AU) payments capability + of the account, or whether the account can directly process BECS Direct + Debit (AU) charges. + enum: + - active + - inactive + - pending + type: string + bacs_debit_payments: + description: The status of the Bacs Direct Debits payments capability of + the account, or whether the account can directly process Bacs Direct Debits + charges. + enum: + - active + - inactive + - pending + type: string + bancontact_payments: + description: The status of the Bancontact payments capability of the account, + or whether the account can directly process Bancontact charges. + enum: + - active + - inactive + - pending + type: string + boleto_payments: + description: The status of the boleto payments capability of the account, + or whether the account can directly process boleto charges. + enum: + - active + - inactive + - pending + type: string + card_issuing: + description: The status of the card issuing capability of the account, or + whether you can use Issuing to distribute funds on cards + enum: + - active + - inactive + - pending + type: string + card_payments: + description: The status of the card payments capability of the account, + or whether the account can directly process credit and debit card charges. + enum: + - active + - inactive + - pending + type: string + cartes_bancaires_payments: + description: The status of the Cartes Bancaires payments capability of the + account, or whether the account can directly process Cartes Bancaires + card charges in EUR currency. + enum: + - active + - inactive + - pending + type: string + eps_payments: + description: The status of the EPS payments capability of the account, or + whether the account can directly process EPS charges. + enum: + - active + - inactive + - pending + type: string + fpx_payments: + description: The status of the FPX payments capability of the account, or + whether the account can directly process FPX charges. + enum: + - active + - inactive + - pending + type: string + giropay_payments: + description: The status of the giropay payments capability of the account, + or whether the account can directly process giropay charges. + enum: + - active + - inactive + - pending + type: string + grabpay_payments: + description: The status of the GrabPay payments capability of the account, + or whether the account can directly process GrabPay charges. + enum: + - active + - inactive + - pending + type: string + ideal_payments: + description: The status of the iDEAL payments capability of the account, + or whether the account can directly process iDEAL charges. + enum: + - active + - inactive + - pending + type: string + jcb_payments: + description: The status of the JCB payments capability of the account, or + whether the account (Japan only) can directly process JCB credit card + charges in JPY currency. + enum: + - active + - inactive + - pending + type: string + legacy_payments: + description: The status of the legacy payments capability of the account. + enum: + - active + - inactive + - pending + type: string + oxxo_payments: + description: The status of the OXXO payments capability of the account, + or whether the account can directly process OXXO charges. + enum: + - active + - inactive + - pending + type: string + p24_payments: + description: The status of the P24 payments capability of the account, or + whether the account can directly process P24 charges. + enum: + - active + - inactive + - pending + type: string + sepa_debit_payments: + description: The status of the SEPA Direct Debits payments capability of + the account, or whether the account can directly process SEPA Direct Debits + charges. + enum: + - active + - inactive + - pending + type: string + sofort_payments: + description: The status of the Sofort payments capability of the account, + or whether the account can directly process Sofort charges. + enum: + - active + - inactive + - pending + type: string + tax_reporting_us_1099_k: + description: The status of the tax reporting 1099-K (US) capability of the + account. + enum: + - active + - inactive + - pending + type: string + tax_reporting_us_1099_misc: + description: The status of the tax reporting 1099-MISC (US) capability of + the account. + enum: + - active + - inactive + - pending + type: string + transfers: + description: The status of the transfers capability of the account, or whether + your platform can transfer funds to the account. + enum: + - active + - inactive + - pending + type: string + title: AccountCapabilities + type: object + x-expandableFields: [] + account_capability_requirements: + description: '' + properties: + current_deadline: + description: Date by which the fields in `currently_due` must be collected + to keep the capability enabled for the account. These fields may disable + the capability sooner if the next threshold is reached before they are + collected. + format: unix-time + nullable: true + type: integer + currently_due: + description: Fields that need to be collected to keep the capability enabled. + If not collected by `current_deadline`, these fields appear in `past_due` + as well, and the capability is disabled. + items: + maxLength: 5000 + type: string + type: array + disabled_reason: + description: |- + If the capability is disabled, this string describes why. Can be `requirements.past_due`, `requirements.pending_verification`, `listed`, `platform_paused`, `rejected.fraud`, `rejected.listed`, `rejected.terms_of_service`, `rejected.other`, `under_review`, or `other`. + + `rejected.unsupported_business` means that the account's business is not supported by the capability. For example, payment methods may restrict the businesses they support in their terms of service: + + - [Afterpay Clearpay's terms of service](/afterpay-clearpay/legal#restricted-businesses) + + If you believe that the rejection is in error, please contact support@stripe.com for assistance. + maxLength: 5000 + nullable: true + type: string + errors: + description: Fields that are `currently_due` and need to be collected again + because validation or verification failed. + items: + "$ref": "#/components/schemas/account_requirements_error" + type: array + eventually_due: + description: Fields that need to be collected assuming all volume thresholds + are reached. As they become required, they appear in `currently_due` as + well, and `current_deadline` becomes set. + items: + maxLength: 5000 + type: string + type: array + past_due: + description: Fields that weren't collected by `current_deadline`. These + fields need to be collected to enable the capability on the account. + items: + maxLength: 5000 + type: string + type: array + pending_verification: + description: Fields that may become required depending on the results of + verification or review. Will be an empty array unless an asynchronous + verification is pending. If verification fails, these fields move to `eventually_due`, + `currently_due`, or `past_due`. + items: + maxLength: 5000 + type: string + type: array + required: + - currently_due + - errors + - eventually_due + - past_due + - pending_verification + title: AccountCapabilityRequirements + type: object + x-expandableFields: + - errors + account_card_issuing_settings: + description: '' + properties: + tos_acceptance: + "$ref": "#/components/schemas/card_issuing_account_terms_of_service" + title: AccountCardIssuingSettings + type: object + x-expandableFields: + - tos_acceptance + account_card_payments_settings: + description: '' + properties: + decline_on: + "$ref": "#/components/schemas/account_decline_charge_on" + statement_descriptor_prefix: + description: The default text that appears on credit card statements when + a charge is made. This field prefixes any dynamic `statement_descriptor` + specified on the charge. `statement_descriptor_prefix` is useful for maximizing + descriptor space for the dynamic portion. + maxLength: 5000 + nullable: true + type: string + title: AccountCardPaymentsSettings + type: object + x-expandableFields: + - decline_on + account_controller: + description: '' + properties: + is_controller: + description: "`true` if the Connect application retrieving the resource + controls the account and can therefore exercise [platform controls](https://stripe.com/docs/connect/platform-controls-for-standard-accounts). + Otherwise, this field is null." + type: boolean + type: + description: The controller type. Can be `application`, if a Connect application + controls the account, or `account`, if the account controls itself. + enum: + - account + - application + type: string + title: AccountController + type: object + x-expandableFields: [] + account_dashboard_settings: + description: '' + properties: + display_name: + description: The display name for this account. This is used on the Stripe + Dashboard to differentiate between accounts. + maxLength: 5000 + nullable: true + type: string + timezone: + description: The timezone used in the Stripe Dashboard for this account. + A list of possible time zone values is maintained at the [IANA Time Zone + Database](http://www.iana.org/time-zones). + maxLength: 5000 + nullable: true + type: string + title: AccountDashboardSettings + type: object + x-expandableFields: [] + account_decline_charge_on: + description: '' + properties: + avs_failure: + description: Whether Stripe automatically declines charges with an incorrect + ZIP or postal code. This setting only applies when a ZIP or postal code + is provided and they fail bank verification. + type: boolean + cvc_failure: + description: Whether Stripe automatically declines charges with an incorrect + CVC. This setting only applies when a CVC is provided and it fails bank + verification. + type: boolean + required: + - avs_failure + - cvc_failure + title: AccountDeclineChargeOn + type: object + x-expandableFields: [] + account_link: + description: |- + Account Links are the means by which a Connect platform grants a connected account permission to access + Stripe-hosted applications, such as Connect Onboarding. + + Related guide: [Connect Onboarding](https://stripe.com/docs/connect/connect-onboarding). + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + expires_at: + description: The timestamp at which this account link will expire. + format: unix-time + type: integer + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - account_link + type: string + url: + description: The URL for the account link. + maxLength: 5000 + type: string + required: + - created + - expires_at + - object + - url + title: AccountLink + type: object + x-expandableFields: [] + x-resourceId: account_link + account_payments_settings: + description: '' + properties: + statement_descriptor: + description: The default text that appears on credit card statements when + a charge is made. This field prefixes any dynamic `statement_descriptor` + specified on the charge. + maxLength: 5000 + nullable: true + type: string + statement_descriptor_kana: + description: The Kana variation of the default text that appears on credit + card statements when a charge is made (Japan only) + maxLength: 5000 + nullable: true + type: string + statement_descriptor_kanji: + description: The Kanji variation of the default text that appears on credit + card statements when a charge is made (Japan only) + maxLength: 5000 + nullable: true + type: string + title: AccountPaymentsSettings + type: object + x-expandableFields: [] + account_payout_settings: + description: '' + properties: + debit_negative_balances: + description: A Boolean indicating if Stripe should try to reclaim negative + balances from an attached bank account. See our [Understanding Connect + Account Balances](https://stripe.com/docs/connect/account-balances) documentation + for details. Default value is `true` for Express accounts and `false` + for Custom accounts. + type: boolean + schedule: + "$ref": "#/components/schemas/transfer_schedule" + statement_descriptor: + description: The text that appears on the bank account statement for payouts. + If not set, this defaults to the platform's bank descriptor as set in + the Dashboard. + maxLength: 5000 + nullable: true + type: string + required: + - debit_negative_balances + - schedule + title: AccountPayoutSettings + type: object + x-expandableFields: + - schedule + account_requirements: + description: '' + properties: + current_deadline: + description: Date by which the fields in `currently_due` must be collected + to keep the account enabled. These fields may disable the account sooner + if the next threshold is reached before they are collected. + format: unix-time + nullable: true + type: integer + currently_due: + description: Fields that need to be collected to keep the account enabled. + If not collected by `current_deadline`, these fields appear in `past_due` + as well, and the account is disabled. + items: + maxLength: 5000 + type: string + nullable: true + type: array + disabled_reason: + description: If the account is disabled, this string describes why. Can + be `requirements.past_due`, `requirements.pending_verification`, `listed`, + `platform_paused`, `rejected.fraud`, `rejected.listed`, `rejected.terms_of_service`, + `rejected.other`, `under_review`, or `other`. + maxLength: 5000 + nullable: true + type: string + errors: + description: Fields that are `currently_due` and need to be collected again + because validation or verification failed. + items: + "$ref": "#/components/schemas/account_requirements_error" + nullable: true + type: array + eventually_due: + description: Fields that need to be collected assuming all volume thresholds + are reached. As they become required, they appear in `currently_due` as + well, and `current_deadline` becomes set. + items: + maxLength: 5000 + type: string + nullable: true + type: array + past_due: + description: Fields that weren't collected by `current_deadline`. These + fields need to be collected to enable the account. + items: + maxLength: 5000 + type: string + nullable: true + type: array + pending_verification: + description: Fields that may become required depending on the results of + verification or review. Will be an empty array unless an asynchronous + verification is pending. If verification fails, these fields move to `eventually_due`, + `currently_due`, or `past_due`. + items: + maxLength: 5000 + type: string + nullable: true + type: array + title: AccountRequirements + type: object + x-expandableFields: + - errors + account_requirements_error: + description: '' + properties: + code: + description: The code for the type of error. + enum: + - invalid_address_city_state_postal_code + - invalid_street_address + - invalid_value_other + - verification_document_address_mismatch + - verification_document_address_missing + - verification_document_corrupt + - verification_document_country_not_supported + - verification_document_dob_mismatch + - verification_document_duplicate_type + - verification_document_expired + - verification_document_failed_copy + - verification_document_failed_greyscale + - verification_document_failed_other + - verification_document_failed_test_mode + - verification_document_fraudulent + - verification_document_id_number_mismatch + - verification_document_id_number_missing + - verification_document_incomplete + - verification_document_invalid + - verification_document_issue_or_expiry_date_missing + - verification_document_manipulated + - verification_document_missing_back + - verification_document_missing_front + - verification_document_name_mismatch + - verification_document_name_missing + - verification_document_nationality_mismatch + - verification_document_not_readable + - verification_document_not_signed + - verification_document_not_uploaded + - verification_document_photo_mismatch + - verification_document_too_large + - verification_document_type_not_supported + - verification_failed_address_match + - verification_failed_business_iec_number + - verification_failed_document_match + - verification_failed_id_number_match + - verification_failed_keyed_identity + - verification_failed_keyed_match + - verification_failed_name_match + - verification_failed_other + - verification_failed_tax_id_match + - verification_failed_tax_id_not_issued + - verification_missing_executives + - verification_missing_owners + - verification_requires_additional_memorandum_of_associations + type: string + x-stripeBypassValidation: true + reason: + description: An informative message that indicates the error type and provides + additional details about the error. + maxLength: 5000 + type: string + requirement: + description: The specific user onboarding requirement field (in the requirements + hash) that needs to be resolved. + maxLength: 5000 + type: string + required: + - code + - reason + - requirement + title: AccountRequirementsError + type: object + x-expandableFields: [] + account_sepa_debit_payments_settings: + description: '' + properties: + creditor_id: + description: SEPA creditor identifier that identifies the company making + the payment. + maxLength: 5000 + type: string + title: AccountSepaDebitPaymentsSettings + type: object + x-expandableFields: [] + account_settings: + description: '' + properties: + bacs_debit_payments: + "$ref": "#/components/schemas/account_bacs_debit_payments_settings" + branding: + "$ref": "#/components/schemas/account_branding_settings" + card_issuing: + "$ref": "#/components/schemas/account_card_issuing_settings" + card_payments: + "$ref": "#/components/schemas/account_card_payments_settings" + dashboard: + "$ref": "#/components/schemas/account_dashboard_settings" + payments: + "$ref": "#/components/schemas/account_payments_settings" + payouts: + "$ref": "#/components/schemas/account_payout_settings" + sepa_debit_payments: + "$ref": "#/components/schemas/account_sepa_debit_payments_settings" + required: + - branding + - card_payments + - dashboard + - payments + title: AccountSettings + type: object + x-expandableFields: + - bacs_debit_payments + - branding + - card_issuing + - card_payments + - dashboard + - payments + - payouts + - sepa_debit_payments + account_tos_acceptance: + description: '' + properties: + date: + description: The Unix timestamp marking when the account representative + accepted their service agreement + format: unix-time + nullable: true + type: integer + ip: + description: The IP address from which the account representative accepted + their service agreement + maxLength: 5000 + nullable: true + type: string + service_agreement: + description: The user's service agreement type + maxLength: 5000 + type: string + user_agent: + description: The user agent of the browser from which the account representative + accepted their service agreement + maxLength: 5000 + nullable: true + type: string + title: AccountTOSAcceptance + type: object + x-expandableFields: [] + address: + description: '' + properties: + city: + description: City, district, suburb, town, or village. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + maxLength: 5000 + nullable: true + type: string + line1: + description: Address line 1 (e.g., street, PO Box, or company name). + maxLength: 5000 + nullable: true + type: string + line2: + description: Address line 2 (e.g., apartment, suite, unit, or building). + maxLength: 5000 + nullable: true + type: string + postal_code: + description: ZIP or postal code. + maxLength: 5000 + nullable: true + type: string + state: + description: State, county, province, or region. + maxLength: 5000 + nullable: true + type: string + title: Address + type: object + x-expandableFields: [] + alipay_account: + description: '' + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The ID of the customer associated with this Alipay Account. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + fingerprint: + description: Uniquely identifies the account and will be the same across + all Alipay account objects that are linked to the same Alipay account. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - alipay_account + type: string + payment_amount: + description: If the Alipay account object is not reusable, the exact amount + that you can create a charge for. + nullable: true + type: integer + payment_currency: + description: If the Alipay account object is not reusable, the exact currency + that you can create a charge for. + nullable: true + type: string + reusable: + description: True if you can create multiple payments using this account. + If the account is reusable, then you can freely choose the amount of each + payment. + type: boolean + used: + description: Whether this Alipay account object has ever been used for a + payment. + type: boolean + username: + description: The username for the Alipay account. + maxLength: 5000 + type: string + required: + - created + - fingerprint + - id + - livemode + - object + - reusable + - used + - username + title: AlipayAccount + type: object + x-expandableFields: + - customer + x-resourceId: alipay_account + api_errors: + description: '' + properties: + charge: + description: For card errors, the ID of the failed charge. + maxLength: 5000 + type: string + code: + description: For some errors that could be handled programmatically, a short + string indicating the [error code](https://stripe.com/docs/error-codes) + reported. + maxLength: 5000 + type: string + decline_code: + description: For card errors resulting from a card issuer decline, a short + string indicating the [card issuer's reason for the decline](https://stripe.com/docs/declines#issuer-declines) + if they provide one. + maxLength: 5000 + type: string + doc_url: + description: A URL to more information about the [error code](https://stripe.com/docs/error-codes) + reported. + maxLength: 5000 + type: string + message: + description: A human-readable message providing more details about the error. + For card errors, these messages can be shown to your users. + maxLength: 40000 + type: string + param: + description: If the error is parameter-specific, the parameter related to + the error. For example, you can use this to display a message near the + correct form field. + maxLength: 5000 + type: string + payment_intent: + "$ref": "#/components/schemas/payment_intent" + payment_method: + "$ref": "#/components/schemas/payment_method" + payment_method_type: + description: If the error is specific to the type of payment method, the + payment method type that had a problem. This field is only populated for + invoice-related errors. + maxLength: 5000 + type: string + setup_intent: + "$ref": "#/components/schemas/setup_intent" + source: + anyOf: + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + description: The source object for errors returned on a request involving + a source. + type: + description: The type of error returned. One of `api_error`, `card_error`, + `idempotency_error`, or `invalid_request_error` + enum: + - api_error + - card_error + - idempotency_error + - invalid_request_error + type: string + required: + - type + title: APIErrors + type: object + x-expandableFields: + - payment_intent + - payment_method + - setup_intent + - source + apple_pay_domain: + description: '' + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + domain_name: + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - apple_pay_domain + type: string + required: + - created + - domain_name + - id + - livemode + - object + title: ApplePayDomain + type: object + x-expandableFields: [] + x-resourceId: apple_pay_domain + application: + description: '' + properties: + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + name: + description: The name of the application. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - application + type: string + required: + - id + - object + title: Application + type: object + x-expandableFields: [] + application_fee: + description: '' + properties: + account: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: ID of the Stripe account this fee was taken from. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + amount: + description: Amount earned, in %s. + type: integer + amount_refunded: + description: Amount in %s refunded (can be less than the amount attribute + on the fee if a partial refund was issued) + type: integer + application: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application" + description: ID of the Connect application that earned the fee. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application" + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: Balance transaction that describes the impact of this collected + application fee on your account balance (not including refunds). + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the charge that the application fee was taken from. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - application_fee + type: string + originating_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the corresponding charge on the platform account, if + this fee was the result of a charge using the `destination` parameter. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + refunded: + description: Whether the fee has been fully refunded. If the fee is only + partially refunded, this attribute will still be false. + type: boolean + refunds: + description: A list of refunds that have been applied to the fee. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/fee_refund" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: FeeRefundList + type: object + x-expandableFields: + - data + required: + - account + - amount + - amount_refunded + - application + - charge + - created + - currency + - id + - livemode + - object + - refunded + - refunds + title: PlatformFee + type: object + x-expandableFields: + - account + - application + - balance_transaction + - charge + - originating_transaction + - refunds + x-resourceId: application_fee + automatic_tax: + description: '' + properties: + enabled: + description: Whether Stripe automatically computes tax on this invoice. + type: boolean + status: + description: The status of the most recent automated tax calculation for + this invoice. + enum: + - complete + - failed + - requires_location_inputs + nullable: true + type: string + required: + - enabled + title: AutomaticTax + type: object + x-expandableFields: [] + balance: + description: |- + This is an object representing your Stripe balance. You can retrieve it to see + the balance currently on your Stripe account. + + You can also retrieve the balance history, which contains a list of + [transactions](https://stripe.com/docs/reporting/balance-transaction-types) that contributed to the balance + (charges, payouts, and so forth). + + The available and pending amounts for each currency are broken down further by + payment source types. + + Related guide: [Understanding Connect Account Balances](https://stripe.com/docs/connect/account-balances). + properties: + available: + description: Funds that are available to be transferred or paid out, whether + automatically by Stripe or explicitly via the [Transfers API](https://stripe.com/docs/api#transfers) + or [Payouts API](https://stripe.com/docs/api#payouts). The available balance + for each currency and payment type can be found in the `source_types` + property. + items: + "$ref": "#/components/schemas/balance_amount" + type: array + connect_reserved: + description: Funds held due to negative balances on connected Custom accounts. + The connect reserve balance for each currency and payment type can be + found in the `source_types` property. + items: + "$ref": "#/components/schemas/balance_amount" + type: array + instant_available: + description: Funds that can be paid out using Instant Payouts. + items: + "$ref": "#/components/schemas/balance_amount" + type: array + issuing: + "$ref": "#/components/schemas/balance_detail" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - balance + type: string + pending: + description: Funds that are not yet available in the balance, due to the + 7-day rolling pay cycle. The pending balance for each currency, and for + each payment type, can be found in the `source_types` property. + items: + "$ref": "#/components/schemas/balance_amount" + type: array + required: + - available + - livemode + - object + - pending + title: Balance + type: object + x-expandableFields: + - available + - connect_reserved + - instant_available + - issuing + - pending + x-resourceId: balance + balance_amount: + description: '' + properties: + amount: + description: Balance amount. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + source_types: + "$ref": "#/components/schemas/balance_amount_by_source_type" + required: + - amount + - currency + title: BalanceAmount + type: object + x-expandableFields: + - source_types + balance_amount_by_source_type: + description: '' + properties: + bank_account: + description: Amount for bank account. + type: integer + card: + description: Amount for card. + type: integer + fpx: + description: Amount for FPX. + type: integer + title: BalanceAmountBySourceType + type: object + x-expandableFields: [] + balance_detail: + description: '' + properties: + available: + description: Funds that are available for use. + items: + "$ref": "#/components/schemas/balance_amount" + type: array + required: + - available + title: BalanceDetail + type: object + x-expandableFields: + - available + balance_transaction: + description: |- + Balance transactions represent funds moving through your Stripe account. + They're created for every type of transaction that comes into or flows out of your Stripe account balance. + + Related guide: [Balance Transaction Types](https://stripe.com/docs/reports/balance-transaction-types). + properties: + amount: + description: Gross amount of the transaction, in %s. + type: integer + available_on: + description: The date the transaction's net funds will become available + in the Stripe balance. + format: unix-time + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + exchange_rate: + description: The exchange rate used, if applicable, for this transaction. + Specifically, if money was converted from currency A to currency B, then + the `amount` in currency A, times `exchange_rate`, would be the `amount` + in currency B. For example, suppose you charged a customer 10.00 EUR. + Then the PaymentIntent's `amount` would be `1000` and `currency` would + be `eur`. Suppose this was converted into 12.34 USD in your Stripe account. + Then the BalanceTransaction's `amount` would be `1234`, `currency` would + be `usd`, and `exchange_rate` would be `1.234`. + nullable: true + type: number + fee: + description: Fees (in %s) paid for this transaction. + type: integer + fee_details: + description: Detailed breakdown of fees (in %s) paid for this transaction. + items: + "$ref": "#/components/schemas/fee" + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + net: + description: Net amount of the transaction, in %s. + type: integer + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - balance_transaction + type: string + reporting_category: + description: "[Learn more](https://stripe.com/docs/reports/reporting-categories) + about how reporting categories can help you understand balance transactions + from an accounting perspective." + maxLength: 5000 + type: string + source: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application_fee" + - "$ref": "#/components/schemas/charge" + - "$ref": "#/components/schemas/connect_collection_transfer" + - "$ref": "#/components/schemas/dispute" + - "$ref": "#/components/schemas/fee_refund" + - "$ref": "#/components/schemas/issuing.authorization" + - "$ref": "#/components/schemas/issuing.dispute" + - "$ref": "#/components/schemas/issuing.transaction" + - "$ref": "#/components/schemas/payout" + - "$ref": "#/components/schemas/platform_tax_fee" + - "$ref": "#/components/schemas/refund" + - "$ref": "#/components/schemas/reserve_transaction" + - "$ref": "#/components/schemas/tax_deducted_at_source" + - "$ref": "#/components/schemas/topup" + - "$ref": "#/components/schemas/transfer" + - "$ref": "#/components/schemas/transfer_reversal" + description: The Stripe object to which this transaction is related. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application_fee" + - "$ref": "#/components/schemas/charge" + - "$ref": "#/components/schemas/connect_collection_transfer" + - "$ref": "#/components/schemas/dispute" + - "$ref": "#/components/schemas/fee_refund" + - "$ref": "#/components/schemas/issuing.authorization" + - "$ref": "#/components/schemas/issuing.dispute" + - "$ref": "#/components/schemas/issuing.transaction" + - "$ref": "#/components/schemas/payout" + - "$ref": "#/components/schemas/platform_tax_fee" + - "$ref": "#/components/schemas/refund" + - "$ref": "#/components/schemas/reserve_transaction" + - "$ref": "#/components/schemas/tax_deducted_at_source" + - "$ref": "#/components/schemas/topup" + - "$ref": "#/components/schemas/transfer" + - "$ref": "#/components/schemas/transfer_reversal" + status: + description: If the transaction's net funds are available in the Stripe + balance yet. Either `available` or `pending`. + maxLength: 5000 + type: string + type: + description: 'Transaction type: `adjustment`, `advance`, `advance_funding`, + `anticipation_repayment`, `application_fee`, `application_fee_refund`, + `charge`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, + `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, + `payment`, `payment_failure_refund`, `payment_refund`, `payout`, `payout_cancel`, + `payout_failure`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, + `stripe_fee`, `stripe_fx_fee`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, + `transfer_cancel`, `transfer_failure`, or `transfer_refund`. [Learn more](https://stripe.com/docs/reports/balance-transaction-types) + about balance transaction types and what they represent. If you are looking + to classify transactions for accounting purposes, you might want to consider + `reporting_category` instead.' + enum: + - adjustment + - advance + - advance_funding + - anticipation_repayment + - application_fee + - application_fee_refund + - charge + - connect_collection_transfer + - contribution + - issuing_authorization_hold + - issuing_authorization_release + - issuing_dispute + - issuing_transaction + - payment + - payment_failure_refund + - payment_refund + - payout + - payout_cancel + - payout_failure + - refund + - refund_failure + - reserve_transaction + - reserved_funds + - stripe_fee + - stripe_fx_fee + - tax_fee + - topup + - topup_reversal + - transfer + - transfer_cancel + - transfer_failure + - transfer_refund + type: string + required: + - amount + - available_on + - created + - currency + - fee + - fee_details + - id + - net + - object + - reporting_category + - status + - type + title: BalanceTransaction + type: object + x-expandableFields: + - fee_details + - source + x-resourceId: balance_transaction + bank_account: + description: |- + These bank accounts are payment methods on `Customer` objects. + + On the other hand [External Accounts](https://stripe.com/docs/api#external_accounts) are transfer + destinations on `Account` objects for [Custom accounts](https://stripe.com/docs/connect/custom-accounts). + They can be bank accounts or debit cards as well, and are documented in the links above. + + Related guide: [Bank Debits and Transfers](https://stripe.com/docs/payments/bank-debits-transfers). + properties: + account: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The ID of the account that the bank account is associated with. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + account_holder_name: + description: The name of the person or business that owns the bank account. + maxLength: 5000 + nullable: true + type: string + account_holder_type: + description: The type of entity that holds the account. This can be either + `individual` or `company`. + maxLength: 5000 + nullable: true + type: string + account_type: + description: The bank account type. This can only be `checking` or `savings` + in most countries. In Japan, this can only be `futsu` or `toza`. + maxLength: 5000 + nullable: true + type: string + available_payout_methods: + description: A set of available payout methods for this bank account. Only + values from this set should be passed as the `method` when creating a + payout. + items: + enum: + - instant + - standard + type: string + nullable: true + type: array + bank_name: + description: Name of the bank associated with the routing number (e.g., + `WELLS FARGO`). + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country the bank account + is located in. + maxLength: 5000 + type: string + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) + paid out to the bank account. + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The ID of the customer that the bank account is associated + with. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + default_for_currency: + description: Whether this bank account is the default external account for + its currency. + nullable: true + type: boolean + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + last4: + description: The last four digits of the bank account number. + maxLength: 5000 + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - bank_account + type: string + routing_number: + description: The routing transit number for the bank account. + maxLength: 5000 + nullable: true + type: string + status: + description: |- + For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. A bank account that hasn't had any activity or validation performed is `new`. If Stripe can determine that the bank account exists, its status will be `validated`. Note that there often isn’t enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be `verified`. If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. If a transfer sent to this bank account fails, we'll set the status to `errored` and will not continue to send transfers until the bank details are updated. + + For external accounts, possible values are `new` and `errored`. Validations aren't run against external accounts because they're only used for payouts. This means the other statuses don't apply. If a transfer fails, the status is set to `errored` and transfers are stopped until account details are updated. + maxLength: 5000 + type: string + required: + - country + - currency + - id + - last4 + - object + - status + title: BankAccount + type: object + x-expandableFields: + - account + - customer + x-resourceId: bank_account + billing_details: + description: '' + properties: + address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Billing address. + nullable: true + email: + description: Email address. + maxLength: 5000 + nullable: true + type: string + name: + description: Full name. + maxLength: 5000 + nullable: true + type: string + phone: + description: Billing phone number (including extension). + maxLength: 5000 + nullable: true + type: string + title: billing_details + type: object + x-expandableFields: + - address + billing_portal.configuration: + description: A portal configuration describes the functionality and behavior + of a portal session. + properties: + active: + description: Whether the configuration is active and can be used to create + portal sessions. + type: boolean + application: + description: ID of the Connect Application that created the configuration. + maxLength: 5000 + nullable: true + type: string + business_profile: + "$ref": "#/components/schemas/portal_business_profile" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + default_return_url: + description: The default URL to redirect customers to when they click on + the portal's link to return to your website. This can be [overriden](https://stripe.com/docs/api/customer_portal/sessions/create#create_portal_session-return_url) + when creating the session. + maxLength: 5000 + nullable: true + type: string + features: + "$ref": "#/components/schemas/portal_features" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + is_default: + description: Whether the configuration is the default. If `true`, this configuration + can be managed in the Dashboard and portal sessions will use this configuration + unless it is overriden when creating the session. + type: boolean + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - billing_portal.configuration + type: string + updated: + description: Time at which the object was last updated. Measured in seconds + since the Unix epoch. + format: unix-time + type: integer + required: + - active + - business_profile + - created + - features + - id + - is_default + - livemode + - object + - updated + title: PortalConfiguration + type: object + x-expandableFields: + - business_profile + - features + x-resourceId: billing_portal.configuration + billing_portal.session: + description: |- + The Billing customer portal is a Stripe-hosted UI for subscription and + billing management. + + A portal configuration describes the functionality and features that you + want to provide to your customers through the portal. + + A portal session describes the instantiation of the customer portal for + a particular customer. By visiting the session's URL, the customer + can manage their subscriptions and billing details. For security reasons, + sessions are short-lived and will expire if the customer does not visit the URL. + Create sessions on-demand when customers intend to manage their subscriptions + and billing details. + + Learn more in the [product overview](https://stripe.com/docs/billing/subscriptions/customer-portal) + and [integration guide](https://stripe.com/docs/billing/subscriptions/integrating-customer-portal). + properties: + configuration: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/billing_portal.configuration" + description: The configuration used by this session, describing the features + available. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/billing_portal.configuration" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + description: The ID of the customer for this session. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + locale: + description: The IETF language tag of the locale Customer Portal is displayed + in. If blank or auto, the customer’s `preferred_locales` or browser’s + locale is used. + enum: + - auto + - bg + - cs + - da + - de + - el + - en + - en-AU + - en-CA + - en-GB + - en-IE + - en-IN + - en-NZ + - en-SG + - es + - es-419 + - et + - fi + - fil + - fr + - fr-CA + - hr + - hu + - id + - it + - ja + - ko + - lt + - lv + - ms + - mt + - nb + - nl + - pl + - pt + - pt-BR + - ro + - ru + - sk + - sl + - sv + - th + - tr + - vi + - zh + - zh-HK + - zh-TW + nullable: true + type: string + x-stripeBypassValidation: true + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - billing_portal.session + type: string + on_behalf_of: + description: The account for which the session was created on behalf of. + When specified, only subscriptions and invoices with this `on_behalf_of` + account appear in the portal. For more information, see the [docs](https://stripe.com/docs/connect/charges-transfers#on-behalf-of). + Use the [Accounts API](https://stripe.com/docs/api/accounts/object#account_object-settings-branding) + to modify the `on_behalf_of` account's branding settings, which the portal + displays. + maxLength: 5000 + nullable: true + type: string + return_url: + description: The URL to redirect customers to when they click on the portal's + link to return to your website. + maxLength: 5000 + type: string + url: + description: The short-lived URL of the session that gives customers access + to the customer portal. + maxLength: 5000 + type: string + required: + - configuration + - created + - customer + - id + - livemode + - object + - return_url + - url + title: PortalSession + type: object + x-expandableFields: + - configuration + x-resourceId: billing_portal.session + bitcoin_receiver: + description: '' + properties: + active: + description: True when this bitcoin receiver has received a non-zero amount + of bitcoin. + type: boolean + amount: + description: The amount of `currency` that you are collecting as payment. + type: integer + amount_received: + description: The amount of `currency` to which `bitcoin_amount_received` + has been converted. + type: integer + bitcoin_amount: + description: 'The amount of bitcoin that the customer should send to fill + the receiver. The `bitcoin_amount` is denominated in Satoshi: there are + 10^8 Satoshi in one bitcoin.' + type: integer + bitcoin_amount_received: + description: The amount of bitcoin that has been sent by the customer to + this receiver. + type: integer + bitcoin_uri: + description: This URI can be displayed to the customer as a clickable link + (to activate their bitcoin client) or as a QR code (for mobile wallets). + maxLength: 5000 + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) + to which the bitcoin will be converted. + type: string + customer: + description: The customer ID of the bitcoin receiver. + maxLength: 5000 + nullable: true + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + email: + description: The customer's email address, set by the API call that creates + the receiver. + maxLength: 5000 + nullable: true + type: string + filled: + description: This flag is initially false and updates to true when the customer + sends the `bitcoin_amount` to this receiver. + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + inbound_address: + description: A bitcoin address that is specific to this receiver. The customer + can send bitcoin to this address to fill the receiver. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - bitcoin_receiver + type: string + payment: + description: The ID of the payment created from the receiver, if any. Hidden + when viewing the receiver with a publishable key. + maxLength: 5000 + nullable: true + type: string + refund_address: + description: The refund address of this bitcoin receiver. + maxLength: 5000 + nullable: true + type: string + transactions: + description: A list with one entry for each time that the customer sent + bitcoin to the receiver. Hidden when viewing the receiver with a publishable + key. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/bitcoin_transaction" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: BitcoinTransactionList + type: object + x-expandableFields: + - data + uncaptured_funds: + description: This receiver contains uncaptured funds that can be used for + a payment or refunded. + type: boolean + used_for_payment: + description: Indicate if this source is used for payment. + nullable: true + type: boolean + required: + - active + - amount + - amount_received + - bitcoin_amount + - bitcoin_amount_received + - bitcoin_uri + - created + - currency + - filled + - id + - inbound_address + - livemode + - object + - uncaptured_funds + title: BitcoinReceiver + type: object + x-expandableFields: + - transactions + x-resourceId: bitcoin_receiver + bitcoin_transaction: + description: '' + properties: + amount: + description: The amount of `currency` that the transaction was converted + to in real-time. + type: integer + bitcoin_amount: + description: The amount of bitcoin contained in the transaction. + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) + to which this transaction was converted. + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - bitcoin_transaction + type: string + receiver: + description: The receiver to which this transaction was sent. + maxLength: 5000 + type: string + required: + - amount + - bitcoin_amount + - created + - currency + - id + - object + - receiver + title: BitcoinTransaction + type: object + x-expandableFields: [] + x-resourceId: bitcoin_transaction + capability: + description: |- + This is an object representing a capability for a Stripe account. + + Related guide: [Account capabilities](https://stripe.com/docs/connect/account-capabilities). + properties: + account: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account for which the capability enables functionality. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + id: + description: The identifier for the capability. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - capability + type: string + requested: + description: Whether the capability has been requested. + type: boolean + requested_at: + description: Time at which the capability was requested. Measured in seconds + since the Unix epoch. + format: unix-time + nullable: true + type: integer + requirements: + "$ref": "#/components/schemas/account_capability_requirements" + status: + description: The status of the capability. Can be `active`, `inactive`, + `pending`, or `unrequested`. + enum: + - active + - disabled + - inactive + - pending + - unrequested + type: string + required: + - account + - id + - object + - requested + - status + title: AccountCapability + type: object + x-expandableFields: + - account + - requirements + x-resourceId: capability + card: + description: |- + You can store multiple cards on a customer in order to charge the customer + later. You can also store multiple debit cards on a recipient in order to + transfer to those cards later. + + Related guide: [Card Payments with Sources](https://stripe.com/docs/sources/cards). + properties: + account: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account this card belongs to. This attribute will not be + in the card object if the card belongs to a customer or recipient instead. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + address_city: + description: City/District/Suburb/Town/Village. + maxLength: 5000 + nullable: true + type: string + address_country: + description: Billing address country, if provided when creating card. + maxLength: 5000 + nullable: true + type: string + address_line1: + description: Address line 1 (Street address/PO Box/Company name). + maxLength: 5000 + nullable: true + type: string + address_line1_check: + description: 'If `address_line1` was provided, results of the check: `pass`, + `fail`, `unavailable`, or `unchecked`.' + maxLength: 5000 + nullable: true + type: string + address_line2: + description: Address line 2 (Apartment/Suite/Unit/Building). + maxLength: 5000 + nullable: true + type: string + address_state: + description: State/County/Province/Region. + maxLength: 5000 + nullable: true + type: string + address_zip: + description: ZIP or postal code. + maxLength: 5000 + nullable: true + type: string + address_zip_check: + description: 'If `address_zip` was provided, results of the check: `pass`, + `fail`, `unavailable`, or `unchecked`.' + maxLength: 5000 + nullable: true + type: string + available_payout_methods: + description: A set of available payout methods for this card. Only values + from this set should be passed as the `method` when creating a payout. + items: + enum: + - instant + - standard + type: string + nullable: true + type: array + brand: + description: Card brand. Can be `American Express`, `Diners Club`, `Discover`, + `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. + maxLength: 5000 + type: string + country: + description: Two-letter ISO code representing the country of the card. You + could use this attribute to get a sense of the international breakdown + of cards you've collected. + maxLength: 5000 + nullable: true + type: string + currency: + description: Three-letter [ISO code for currency](https://stripe.com/docs/payouts). + Only applicable on accounts (not customers or recipients). The card can + be used as a transfer destination for funds in this currency. + nullable: true + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The customer that this card belongs to. This attribute will + not be in the card object if the card belongs to an account or recipient + instead. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + cvc_check: + description: 'If a CVC was provided, results of the check: `pass`, `fail`, + `unavailable`, or `unchecked`. A result of unchecked indicates that CVC + was provided but hasn''t been checked yet. Checks are typically performed + when attaching a card to a Customer object, or when creating a charge. + For more details, see [Check if a card is valid without a charge](https://support.stripe.com/questions/check-if-a-card-is-valid-without-a-charge).' + maxLength: 5000 + nullable: true + type: string + default_for_currency: + description: Whether this card is the default external account for its currency. + nullable: true + type: boolean + dynamic_last4: + description: "(For tokenized numbers only.) The last four digits of the + device account number." + maxLength: 5000 + nullable: true + type: string + exp_month: + description: Two-digit number representing the card's expiration month. + type: integer + exp_year: + description: Four-digit number representing the card's expiration year. + type: integer + fingerprint: + description: |- + Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + + *Starting May 1, 2021, card fingerprint in India for Connect will change to allow two fingerprints for the same card --- one for India and one for the rest of the world.* + maxLength: 5000 + nullable: true + type: string + funding: + description: Card funding type. Can be `credit`, `debit`, `prepaid`, or + `unknown`. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + last4: + description: The last four digits of the card. + maxLength: 5000 + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + name: + description: Cardholder name. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - card + type: string + recipient: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/recipient" + description: The recipient that this card belongs to. This attribute will + not be in the card object if the card belongs to a customer or account + instead. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/recipient" + tokenization_method: + description: If the card number is tokenized, this is the method that was + used. Can be `android_pay` (includes Google Pay), `apple_pay`, `masterpass`, + `visa_checkout`, or null. + maxLength: 5000 + nullable: true + type: string + required: + - brand + - exp_month + - exp_year + - funding + - id + - last4 + - object + title: Card + type: object + x-expandableFields: + - account + - customer + - recipient + x-resourceId: card + card_generated_from_payment_method_details: + description: '' + properties: + card_present: + "$ref": "#/components/schemas/payment_method_details_card_present" + type: + description: The type of payment method transaction-specific details from + the transaction that generated this `card` payment method. Always `card_present`. + maxLength: 5000 + type: string + required: + - type + title: card_generated_from_payment_method_details + type: object + x-expandableFields: + - card_present + card_issuing_account_terms_of_service: + description: '' + properties: + date: + description: The Unix timestamp marking when the account representative + accepted the service agreement. + nullable: true + type: integer + ip: + description: The IP address from which the account representative accepted + the service agreement. + maxLength: 5000 + nullable: true + type: string + user_agent: + description: The user agent of the browser from which the account representative + accepted the service agreement. + maxLength: 5000 + type: string + title: CardIssuingAccountTermsOfService + type: object + x-expandableFields: [] + card_mandate_payment_method_details: + description: '' + properties: {} + title: card_mandate_payment_method_details + type: object + x-expandableFields: [] + charge: + description: |- + To charge a credit or a debit card, you create a `Charge` object. You can + retrieve and refund individual charges as well as list all charges. Charges + are identified by a unique, random ID. + + Related guide: [Accept a payment with the Charges API](https://stripe.com/docs/payments/accept-a-payment-charges). + properties: + amount: + description: Amount intended to be collected by this payment. A positive + integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) + (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal + currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). + The amount value supports up to eight digits (e.g., a value of 99999999 + for a USD charge of $999,999.99). + type: integer + amount_captured: + description: Amount in %s captured (can be less than the amount attribute + on the charge if a partial capture was made). + type: integer + amount_refunded: + description: Amount in %s refunded (can be less than the amount attribute + on the charge if a partial refund was issued). + type: integer + application: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application" + description: ID of the Connect application that created the charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application" + application_fee: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application_fee" + description: The application fee (if any) for the charge. [See the Connect + documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) + for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application_fee" + application_fee_amount: + description: The amount of the application fee (if any) requested for the + charge. [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) + for details. + nullable: true + type: integer + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: ID of the balance transaction that describes the impact of + this charge on your account balance (not including refunds or disputes). + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + billing_details: + "$ref": "#/components/schemas/billing_details" + calculated_statement_descriptor: + description: The full statement descriptor that is passed to card networks, + and that is displayed on your customers' credit card and bank statements. + Allows you to see what the statement descriptor looks like after the static + and dynamic portions are combined. + maxLength: 5000 + nullable: true + type: string + captured: + description: If the charge was created without capturing, this Boolean represents + whether it is still uncaptured or has since been captured. + type: boolean + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: ID of the customer this charge is for if one exists. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 40000 + nullable: true + type: string + disputed: + description: Whether the charge has been disputed. + type: boolean + failure_code: + description: Error code explaining reason for charge failure if available + (see [the errors section](https://stripe.com/docs/api#errors) for a list + of codes). + maxLength: 5000 + nullable: true + type: string + failure_message: + description: Message to user further explaining reason for charge failure + if available. + maxLength: 5000 + nullable: true + type: string + fraud_details: + anyOf: + - "$ref": "#/components/schemas/charge_fraud_details" + description: Information on fraud assessments for the charge. + nullable: true + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + description: ID of the invoice this charge is for if one exists. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - charge + type: string + on_behalf_of: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account (if any) the charge was made on behalf of without + triggering an automatic transfer. See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers) + for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + order: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/order" + description: ID of the order this charge is for if one exists. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/order" + outcome: + anyOf: + - "$ref": "#/components/schemas/charge_outcome" + description: Details about whether the payment was accepted, and why. See + [understanding declines](https://stripe.com/docs/declines) for details. + nullable: true + paid: + description: "`true` if the charge succeeded, or was successfully authorized + for later capture." + type: boolean + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: ID of the PaymentIntent associated with this charge, if one + exists. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + payment_method: + description: ID of the payment method used in this charge. + maxLength: 5000 + nullable: true + type: string + payment_method_details: + anyOf: + - "$ref": "#/components/schemas/payment_method_details" + description: Details about the payment method at the time of the transaction. + nullable: true + receipt_email: + description: This is the email address that the receipt for this charge + was sent to. + maxLength: 5000 + nullable: true + type: string + receipt_number: + description: This is the transaction number that appears on email receipts + sent for this charge. This attribute will be `null` until a receipt has + been sent. + maxLength: 5000 + nullable: true + type: string + receipt_url: + description: This is the URL to view the receipt for this charge. The receipt + is kept up-to-date to the latest state of the charge, including any refunds. + If the charge is for an Invoice, the receipt will be stylized as an Invoice + receipt. + maxLength: 5000 + nullable: true + type: string + refunded: + description: Whether the charge has been fully refunded. If the charge is + only partially refunded, this attribute will still be false. + type: boolean + refunds: + description: A list of refunds that have been applied to the charge. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/refund" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: RefundList + type: object + x-expandableFields: + - data + review: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/review" + description: ID of the review associated with this charge if one exists. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/review" + shipping: + anyOf: + - "$ref": "#/components/schemas/shipping" + description: Shipping information for the charge. + nullable: true + source_transfer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/transfer" + description: The transfer ID which created this charge. Only present if + the charge came from another Stripe account. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) + for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/transfer" + statement_descriptor: + description: For card charges, use `statement_descriptor_suffix` instead. + Otherwise, you can use this value as the complete description of a charge + on your customers’ statements. Must contain at least one letter, maximum + 22 characters. + maxLength: 5000 + nullable: true + type: string + statement_descriptor_suffix: + description: Provides information about the charge that customers see on + their statements. Concatenated with the prefix (shortened descriptor) + or statement descriptor that’s set on the account to form the complete + statement descriptor. Maximum 22 characters for the concatenated descriptor. + maxLength: 5000 + nullable: true + type: string + status: + description: The status of the payment is either `succeeded`, `pending`, + or `failed`. + maxLength: 5000 + type: string + transfer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/transfer" + description: ID of the transfer to the `destination` account (only applicable + if the charge was created using the `destination` parameter). + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/transfer" + transfer_data: + anyOf: + - "$ref": "#/components/schemas/charge_transfer_data" + description: An optional dictionary including the account to automatically + transfer to as part of a destination charge. [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) + for details. + nullable: true + transfer_group: + description: A string that identifies this transaction as part of a group. + See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) + for details. + maxLength: 5000 + nullable: true + type: string + required: + - amount + - amount_captured + - amount_refunded + - billing_details + - captured + - created + - currency + - disputed + - id + - livemode + - metadata + - object + - paid + - refunded + - refunds + - status + title: Charge + type: object + x-expandableFields: + - application + - application_fee + - balance_transaction + - billing_details + - customer + - fraud_details + - invoice + - on_behalf_of + - order + - outcome + - payment_intent + - payment_method_details + - refunds + - review + - shipping + - source_transfer + - transfer + - transfer_data + x-resourceId: charge + charge_fraud_details: + description: '' + properties: + stripe_report: + description: Assessments from Stripe. If set, the value is `fraudulent`. + maxLength: 5000 + type: string + user_report: + description: Assessments reported by you. If set, possible values of are + `safe` and `fraudulent`. + maxLength: 5000 + type: string + title: ChargeFraudDetails + type: object + x-expandableFields: [] + charge_outcome: + description: '' + properties: + network_status: + description: Possible values are `approved_by_network`, `declined_by_network`, + `not_sent_to_network`, and `reversed_after_approval`. The value `reversed_after_approval` + indicates the payment was [blocked by Stripe](https://stripe.com/docs/declines#blocked-payments) + after bank authorization, and may temporarily appear as "pending" on a + cardholder's statement. + maxLength: 5000 + nullable: true + type: string + reason: + description: An enumerated value providing a more detailed explanation of + the outcome's `type`. Charges blocked by Radar's default block rule have + the value `highest_risk_level`. Charges placed in review by Radar's default + review rule have the value `elevated_risk_level`. Charges authorized, + blocked, or placed in review by custom rules have the value `rule`. See + [understanding declines](https://stripe.com/docs/declines) for more details. + maxLength: 5000 + nullable: true + type: string + risk_level: + description: Stripe Radar's evaluation of the riskiness of the payment. + Possible values for evaluated payments are `normal`, `elevated`, `highest`. + For non-card payments, and card-based payments predating the public assignment + of risk levels, this field will have the value `not_assessed`. In the + event of an error in the evaluation, this field will have the value `unknown`. + This field is only available with Radar. + maxLength: 5000 + type: string + risk_score: + description: Stripe Radar's evaluation of the riskiness of the payment. + Possible values for evaluated payments are between 0 and 100. For non-card + payments, card-based payments predating the public assignment of risk + scores, or in the event of an error during evaluation, this field will + not be present. This field is only available with Radar for Fraud Teams. + type: integer + rule: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/rule" + description: The ID of the Radar rule that matched the payment, if applicable. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/rule" + seller_message: + description: A human-readable description of the outcome type and reason, + designed for you (the recipient of the payment), not your customer. + maxLength: 5000 + nullable: true + type: string + type: + description: Possible values are `authorized`, `manual_review`, `issuer_declined`, + `blocked`, and `invalid`. See [understanding declines](https://stripe.com/docs/declines) + and [Radar reviews](https://stripe.com/docs/radar/reviews) for details. + maxLength: 5000 + type: string + required: + - type + title: ChargeOutcome + type: object + x-expandableFields: + - rule + charge_transfer_data: + description: '' + properties: + amount: + description: The amount transferred to the destination account, if specified. + By default, the entire charge amount is transferred to the destination + account. + nullable: true + type: integer + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: ID of an existing, connected Stripe account to transfer funds + to if `transfer_data` was specified in the charge request. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + required: + - destination + title: ChargeTransferData + type: object + x-expandableFields: + - destination + checkout.session: + description: |- + A Checkout Session represents your customer's session as they pay for + one-time purchases or subscriptions through [Checkout](https://stripe.com/docs/payments/checkout). + We recommend creating a new Session each time your customer attempts to pay. + + Once payment is successful, the Checkout Session will contain a reference + to the [Customer](https://stripe.com/docs/api/customers), and either the successful + [PaymentIntent](https://stripe.com/docs/api/payment_intents) or an active + [Subscription](https://stripe.com/docs/api/subscriptions). + + You can create a Checkout Session on your server and pass its ID to the + client to begin Checkout. + + Related guide: [Checkout Server Quickstart](https://stripe.com/docs/payments/checkout/api). + properties: + allow_promotion_codes: + description: Enables user redeemable promotion codes. + nullable: true + type: boolean + amount_subtotal: + description: Total of all items before discounts or taxes are applied. + nullable: true + type: integer + amount_total: + description: Total of all items after discounts and taxes are applied. + nullable: true + type: integer + automatic_tax: + "$ref": "#/components/schemas/payment_pages_checkout_session_automatic_tax" + billing_address_collection: + description: Describes whether Checkout should collect the customer's billing + address. + enum: + - auto + - required + nullable: true + type: string + cancel_url: + description: The URL the customer will be directed to if they decide to + cancel payment and return to your website. + maxLength: 5000 + type: string + client_reference_id: + description: |- + A unique string to reference the Checkout Session. This can be a + customer ID, a cart ID, or similar, and can be used to reconcile the + Session with your internal systems. + maxLength: 5000 + nullable: true + type: string + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + nullable: true + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: |- + The ID of the customer for this Session. + For Checkout Sessions in `payment` or `subscription` mode, Checkout + will create a new customer object based on information provided + during the payment flow unless an existing customer was provided when + the Session was created. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + customer_details: + anyOf: + - "$ref": "#/components/schemas/payment_pages_checkout_session_customer_details" + description: The customer details including the customer's tax exempt status + and the customer's tax IDs. Only present on Sessions in `payment` or `subscription` + mode. + nullable: true + customer_email: + description: |- + If provided, this value will be used when the Customer object is created. + If not provided, customers will be asked to enter their email address. + Use this parameter to prefill customer data if you already have an email + on file. To access information about the customer once the payment flow is + complete, use the `customer` attribute. + maxLength: 5000 + nullable: true + type: string + id: + description: |- + Unique identifier for the object. Used to pass to `redirectToCheckout` + in Stripe.js. + maxLength: 5000 + type: string + line_items: + description: The line items purchased by the customer. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: PaymentPagesCheckoutSessionListLineItems + type: object + x-expandableFields: + - data + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + locale: + description: The IETF language tag of the locale Checkout is displayed in. + If blank or `auto`, the browser's locale is used. + enum: + - auto + - bg + - cs + - da + - de + - el + - en + - en-GB + - es + - es-419 + - et + - fi + - fil + - fr + - fr-CA + - hr + - hu + - id + - it + - ja + - ko + - lt + - lv + - ms + - mt + - nb + - nl + - pl + - pt + - pt-BR + - ro + - ru + - sk + - sl + - sv + - th + - tr + - vi + - zh + - zh-HK + - zh-TW + nullable: true + type: string + x-stripeBypassValidation: true + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + mode: + description: The mode of the Checkout Session. + enum: + - payment + - setup + - subscription + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - checkout.session + type: string + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: The ID of the PaymentIntent for Checkout Sessions in `payment` + mode. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + payment_method_options: + anyOf: + - "$ref": "#/components/schemas/checkout_session_payment_method_options" + description: Payment-method-specific configuration for the PaymentIntent + or SetupIntent of this CheckoutSession. + nullable: true + payment_method_types: + description: |- + A list of the types of payment methods (e.g. card) this Checkout + Session is allowed to accept. + items: + maxLength: 5000 + type: string + type: array + payment_status: + description: |- + The payment status of the Checkout Session, one of `paid`, `unpaid`, or `no_payment_required`. + You can use this value to decide when to fulfill your customer's order. + enum: + - no_payment_required + - paid + - unpaid + type: string + setup_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/setup_intent" + description: The ID of the SetupIntent for Checkout Sessions in `setup` + mode. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/setup_intent" + shipping: + anyOf: + - "$ref": "#/components/schemas/shipping" + description: Shipping information for this Checkout Session. + nullable: true + shipping_address_collection: + anyOf: + - "$ref": "#/components/schemas/payment_pages_payment_page_resources_shipping_address_collection" + description: When set, provides configuration for Checkout to collect a + shipping address from a customer. + nullable: true + submit_type: + description: |- + Describes the type of transaction being performed by Checkout in order to customize + relevant text on the page, such as the submit button. `submit_type` can only be + specified on Checkout Sessions in `payment` mode, but not Checkout Sessions + in `subscription` or `setup` mode. + enum: + - auto + - book + - donate + - pay + nullable: true + type: string + subscription: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription" + description: The ID of the subscription for Checkout Sessions in `subscription` + mode. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription" + success_url: + description: |- + The URL the customer will be directed to after the payment or + subscription creation is successful. + maxLength: 5000 + type: string + tax_id_collection: + "$ref": "#/components/schemas/payment_pages_checkout_session_tax_id_collection" + total_details: + anyOf: + - "$ref": "#/components/schemas/payment_pages_checkout_session_total_details" + description: Tax and discount details for the computed total amount. + nullable: true + url: + description: The URL to the Checkout Session. + maxLength: 5000 + nullable: true + type: string + required: + - automatic_tax + - cancel_url + - id + - livemode + - mode + - object + - payment_method_types + - payment_status + - success_url + title: Session + type: object + x-expandableFields: + - automatic_tax + - customer + - customer_details + - line_items + - payment_intent + - payment_method_options + - setup_intent + - shipping + - shipping_address_collection + - subscription + - tax_id_collection + - total_details + x-resourceId: checkout.session + checkout_acss_debit_mandate_options: + description: '' + properties: + custom_mandate_url: + description: A URL for custom mandate text + maxLength: 5000 + type: string + interval_description: + description: Description of the interval. Only required if the 'payment_schedule' + parameter is 'interval' or 'combined'. + maxLength: 5000 + nullable: true + type: string + payment_schedule: + description: Payment schedule for the mandate. + enum: + - combined + - interval + - sporadic + nullable: true + type: string + transaction_type: + description: Transaction type of the mandate. + enum: + - business + - personal + nullable: true + type: string + title: CheckoutAcssDebitMandateOptions + type: object + x-expandableFields: [] + checkout_acss_debit_payment_method_options: + description: '' + properties: + currency: + description: Currency supported by the bank account. Returned when the Session + is in `setup` mode. + enum: + - cad + - usd + type: string + mandate_options: + "$ref": "#/components/schemas/checkout_acss_debit_mandate_options" + verification_method: + description: Bank account verification method. + enum: + - automatic + - instant + - microdeposits + type: string + x-stripeBypassValidation: true + title: CheckoutAcssDebitPaymentMethodOptions + type: object + x-expandableFields: + - mandate_options + checkout_session_payment_method_options: + description: '' + properties: + acss_debit: + "$ref": "#/components/schemas/checkout_acss_debit_payment_method_options" + boleto: + "$ref": "#/components/schemas/payment_method_options_boleto" + oxxo: + "$ref": "#/components/schemas/payment_method_options_oxxo" + title: CheckoutSessionPaymentMethodOptions + type: object + x-expandableFields: + - acss_debit + - boleto + - oxxo + connect_collection_transfer: + description: '' + properties: + amount: + description: Amount transferred, in %s. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: ID of the account that funds are being collected for. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - connect_collection_transfer + type: string + required: + - amount + - currency + - destination + - id + - livemode + - object + title: ConnectCollectionTransfer + type: object + x-expandableFields: + - destination + country_spec: + description: |- + Stripe needs to collect certain pieces of information about each account + created. These requirements can differ depending on the account's country. The + Country Specs API makes these rules available to your integration. + + You can also view the information from this API call as [an online + guide](/docs/connect/required-verification-information). + properties: + default_currency: + description: The default currency for this country. This applies to both + payment methods and bank accounts. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. Represented as the ISO country + code for this country. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - country_spec + type: string + supported_bank_account_currencies: + additionalProperties: + items: + maxLength: 5000 + type: string + type: array + description: Currencies that can be accepted in the specific country (for + transfers). + type: object + supported_payment_currencies: + description: Currencies that can be accepted in the specified country (for + payments). + items: + maxLength: 5000 + type: string + type: array + supported_payment_methods: + description: Payment methods available in the specified country. You may + need to enable some payment methods (e.g., [ACH](https://stripe.com/docs/ach)) + on your account before they appear in this list. The `stripe` payment + method refers to [charging through your platform](https://stripe.com/docs/connect/destination-charges). + items: + maxLength: 5000 + type: string + type: array + supported_transfer_countries: + description: Countries that can accept transfers from the specified country. + items: + maxLength: 5000 + type: string + type: array + verification_fields: + "$ref": "#/components/schemas/country_spec_verification_fields" + required: + - default_currency + - id + - object + - supported_bank_account_currencies + - supported_payment_currencies + - supported_payment_methods + - supported_transfer_countries + - verification_fields + title: CountrySpec + type: object + x-expandableFields: + - verification_fields + x-resourceId: country_spec + country_spec_verification_field_details: + description: '' + properties: + additional: + description: Additional fields which are only required for some users. + items: + maxLength: 5000 + type: string + type: array + minimum: + description: Fields which every account must eventually provide. + items: + maxLength: 5000 + type: string + type: array + required: + - additional + - minimum + title: CountrySpecVerificationFieldDetails + type: object + x-expandableFields: [] + country_spec_verification_fields: + description: '' + properties: + company: + "$ref": "#/components/schemas/country_spec_verification_field_details" + individual: + "$ref": "#/components/schemas/country_spec_verification_field_details" + required: + - company + - individual + title: CountrySpecVerificationFields + type: object + x-expandableFields: + - company + - individual + coupon: + description: |- + A coupon contains information about a percent-off or amount-off discount you + might want to apply to a customer. Coupons may be applied to [invoices](https://stripe.com/docs/api#invoices) or + [orders](https://stripe.com/docs/api#create_order-coupon). Coupons do not work with conventional one-off [charges](https://stripe.com/docs/api#create_charge). + properties: + amount_off: + description: Amount (in the `currency` specified) that will be taken off + the subtotal of any invoices for this customer. + nullable: true + type: integer + applies_to: + "$ref": "#/components/schemas/coupon_applies_to" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: If `amount_off` has been set, the three-letter [ISO code for + the currency](https://stripe.com/docs/currencies) of the amount to take + off. + nullable: true + type: string + duration: + description: One of `forever`, `once`, and `repeating`. Describes how long + a customer who applies this coupon will get the discount. + enum: + - forever + - once + - repeating + type: string + duration_in_months: + description: If `duration` is `repeating`, the number of months the coupon + applies. Null if coupon `duration` is `forever` or `once`. + nullable: true + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + max_redemptions: + description: Maximum number of times this coupon can be redeemed, in total, + across all customers, before it is no longer valid. + nullable: true + type: integer + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + name: + description: Name of the coupon displayed to customers on for instance invoices + or receipts. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - coupon + type: string + percent_off: + description: Percent that will be taken off the subtotal of any invoices + for this customer for the duration of the coupon. For example, a coupon + with percent_off of 50 will make a %s100 invoice %s50 instead. + nullable: true + type: number + redeem_by: + description: Date after which the coupon can no longer be redeemed. + format: unix-time + nullable: true + type: integer + times_redeemed: + description: Number of times this coupon has been applied to a customer. + type: integer + valid: + description: Taking account of the above properties, whether this coupon + can still be applied to a customer. + type: boolean + required: + - created + - duration + - id + - livemode + - object + - times_redeemed + - valid + title: Coupon + type: object + x-expandableFields: + - applies_to + x-resourceId: coupon + coupon_applies_to: + description: 'Contains information about what this coupon applies to' + properties: + products: + description: A list of product IDs this coupon applies to + items: + maxLength: 5000 + type: string + type: array + required: + - products + title: CouponAppliesTo + type: object + x-expandableFields: [] + credit_note: + description: |- + Issue a credit note to adjust an invoice's amount after the invoice is finalized. + + Related guide: [Credit Notes](https://stripe.com/docs/billing/invoices/credit-notes). + properties: + amount: + description: The integer amount in %s representing the total amount of the + credit note, including tax. + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: ID of the customer. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + customer_balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer_balance_transaction" + description: Customer balance transaction related to this credit note. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer_balance_transaction" + discount_amount: + description: The integer amount in %s representing the total amount of discount + that was credited. + type: integer + discount_amounts: + description: The aggregate amounts calculated per discount for all line + items. + items: + "$ref": "#/components/schemas/discounts_resource_discount_amount" + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + description: ID of the invoice. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + lines: + description: Line items that make up the credit note + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/credit_note_line_item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: CreditNoteLinesList + type: object + x-expandableFields: + - data + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + memo: + description: Customer-facing text that appears on the credit note PDF. + maxLength: 5000 + nullable: true + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + number: + description: A unique number that identifies this particular credit note + and appears on the PDF of the credit note and its associated invoice. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - credit_note + type: string + out_of_band_amount: + description: Amount that was credited outside of Stripe. + nullable: true + type: integer + pdf: + description: The link to download the PDF of the credit note. + maxLength: 5000 + type: string + reason: + description: Reason for issuing this credit note, one of `duplicate`, `fraudulent`, + `order_change`, or `product_unsatisfactory` + enum: + - duplicate + - fraudulent + - order_change + - product_unsatisfactory + nullable: true + type: string + refund: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/refund" + description: Refund related to this credit note. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/refund" + status: + description: Status of this credit note, one of `issued` or `void`. Learn + more about [voiding credit notes](https://stripe.com/docs/billing/invoices/credit-notes#voiding). + enum: + - issued + - void + type: string + subtotal: + description: The integer amount in %s representing the amount of the credit + note, excluding tax and invoice level discounts. + type: integer + tax_amounts: + description: The aggregate amounts calculated per tax rate for all line + items. + items: + "$ref": "#/components/schemas/credit_note_tax_amount" + type: array + total: + description: The integer amount in %s representing the total amount of the + credit note, including tax and all discount. + type: integer + type: + description: Type of this credit note, one of `pre_payment` or `post_payment`. + A `pre_payment` credit note means it was issued when the invoice was open. + A `post_payment` credit note means it was issued when the invoice was + paid. + enum: + - post_payment + - pre_payment + type: string + voided_at: + description: The time that the credit note was voided. + format: unix-time + nullable: true + type: integer + required: + - amount + - created + - currency + - customer + - discount_amount + - discount_amounts + - id + - invoice + - lines + - livemode + - number + - object + - pdf + - status + - subtotal + - tax_amounts + - total + - type + title: CreditNote + type: object + x-expandableFields: + - customer + - customer_balance_transaction + - discount_amounts + - invoice + - lines + - refund + - tax_amounts + x-resourceId: credit_note + credit_note_line_item: + description: '' + properties: + amount: + description: The integer amount in %s representing the gross amount being + credited for this line item, excluding (exclusive) tax and discounts. + type: integer + description: + description: Description of the item being credited. + maxLength: 5000 + nullable: true + type: string + discount_amount: + description: The integer amount in %s representing the discount being credited + for this line item. + type: integer + discount_amounts: + description: The amount of discount calculated per discount for this line + item + items: + "$ref": "#/components/schemas/discounts_resource_discount_amount" + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice_line_item: + description: ID of the invoice line item being credited + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - credit_note_line_item + type: string + quantity: + description: The number of units of product being credited. + nullable: true + type: integer + tax_amounts: + description: The amount of tax calculated per tax rate for this line item + items: + "$ref": "#/components/schemas/credit_note_tax_amount" + type: array + tax_rates: + description: The tax rates which apply to the line item. + items: + "$ref": "#/components/schemas/tax_rate" + type: array + type: + description: The type of the credit note line item, one of `invoice_line_item` + or `custom_line_item`. When the type is `invoice_line_item` there is an + additional `invoice_line_item` property on the resource the value of which + is the id of the credited line item on the invoice. + enum: + - custom_line_item + - invoice_line_item + type: string + unit_amount: + description: The cost of each unit of product being credited. + nullable: true + type: integer + unit_amount_decimal: + description: Same as `unit_amount`, but contains a decimal value with at + most 12 decimal places. + format: decimal + nullable: true + type: string + required: + - amount + - discount_amount + - discount_amounts + - id + - livemode + - object + - tax_amounts + - tax_rates + - type + title: CreditNoteLineItem + type: object + x-expandableFields: + - discount_amounts + - tax_amounts + - tax_rates + x-resourceId: credit_note_line_item + credit_note_tax_amount: + description: '' + properties: + amount: + description: The amount, in %s, of the tax. + type: integer + inclusive: + description: Whether this tax amount is inclusive or exclusive. + type: boolean + tax_rate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/tax_rate" + description: The tax rate that was applied to get this tax amount. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/tax_rate" + required: + - amount + - inclusive + - tax_rate + title: CreditNoteTaxAmount + type: object + x-expandableFields: + - tax_rate + customer: + description: |- + `Customer` objects allow you to perform recurring charges, and to track + multiple charges, that are associated with the same customer. The API allows + you to create, delete, and update your customers. You can retrieve individual + customers as well as a list of all your customers. + + Related guide: [Save a card during payment](https://stripe.com/docs/payments/save-during-payment). + properties: + address: + anyOf: + - "$ref": "#/components/schemas/address" + description: The customer's address. + nullable: true + balance: + description: Current balance, if any, being stored on the customer. If negative, + the customer has credit to apply to their next invoice. If positive, the + customer has an amount owed that will be added to their next invoice. + The balance does not refer to any unpaid invoices; it solely takes into + account amounts that have yet to be successfully applied to any invoice. + This balance is only taken into account as invoices are finalized. + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) + the customer can be charged in for recurring billing purposes. + maxLength: 5000 + nullable: true + type: string + default_source: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + description: |- + ID of the default payment source for the customer. + + If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) field instead. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + delinquent: + description: |- + When the customer's latest invoice is billed by charging automatically, `delinquent` is `true` if the invoice's latest charge failed. When the customer's latest invoice is billed by sending an invoice, `delinquent` is `true` if the invoice isn't paid by its due date. + + If an invoice is marked uncollectible by [dunning](https://stripe.com/docs/billing/automatic-collection), `delinquent` doesn't get reset to `false`. + nullable: true + type: boolean + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + discount: + anyOf: + - "$ref": "#/components/schemas/discount" + description: Describes the current discount active on the customer, if there + is one. + nullable: true + email: + description: The customer's email address. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice_prefix: + description: The prefix for the customer used to generate unique invoice + numbers. + maxLength: 5000 + nullable: true + type: string + invoice_settings: + "$ref": "#/components/schemas/invoice_setting_customer_setting" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + name: + description: The customer's full name or business name. + maxLength: 5000 + nullable: true + type: string + next_invoice_sequence: + description: The suffix of the customer's next invoice number, e.g., 0001. + type: integer + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - customer + type: string + phone: + description: The customer's phone number. + maxLength: 5000 + nullable: true + type: string + preferred_locales: + description: The customer's preferred locales (languages), ordered by preference. + items: + maxLength: 5000 + type: string + nullable: true + type: array + shipping: + anyOf: + - "$ref": "#/components/schemas/shipping" + description: Mailing and shipping address for the customer. Appears on invoices + emailed to this customer. + nullable: true + sources: + description: The customer's payment sources, if any. + properties: + data: + description: Details about each object. + items: + anyOf: + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + title: Polymorphic + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: ApmsSourcesSourceList + type: object + x-expandableFields: + - data + subscriptions: + description: The customer's current subscriptions, if any. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/subscription" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: SubscriptionList + type: object + x-expandableFields: + - data + tax: + "$ref": "#/components/schemas/customer_tax" + tax_exempt: + description: Describes the customer's tax exemption status. One of `none`, + `exempt`, or `reverse`. When set to `reverse`, invoice and receipt PDFs + include the text **"Reverse charge"**. + enum: + - exempt + - none + - reverse + nullable: true + type: string + tax_ids: + description: The customer's tax IDs. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/tax_id" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: TaxIDsList + type: object + x-expandableFields: + - data + required: + - created + - id + - livemode + - object + title: Customer + type: object + x-expandableFields: + - address + - default_source + - discount + - invoice_settings + - shipping + - sources + - subscriptions + - tax + - tax_ids + x-resourceId: customer + customer_acceptance: + description: '' + properties: + accepted_at: + description: The time at which the customer accepted the Mandate. + format: unix-time + nullable: true + type: integer + offline: + "$ref": "#/components/schemas/offline_acceptance" + online: + "$ref": "#/components/schemas/online_acceptance" + type: + description: The type of customer acceptance information included with the + Mandate. One of `online` or `offline`. + enum: + - offline + - online + type: string + required: + - type + title: customer_acceptance + type: object + x-expandableFields: + - offline + - online + customer_balance_transaction: + description: |- + Each customer has a [`balance`](https://stripe.com/docs/api/customers/object#customer_object-balance) value, + which denotes a debit or credit that's automatically applied to their next invoice upon finalization. + You may modify the value directly by using the [update customer API](https://stripe.com/docs/api/customers/update), + or by creating a Customer Balance Transaction, which increments or decrements the customer's `balance` by the specified `amount`. + + Related guide: [Customer Balance](https://stripe.com/docs/billing/customer/balance) to learn more. + properties: + amount: + description: The amount of the transaction. A negative value is a credit + for the customer's balance, and a positive value is a debit to the customer's + `balance`. + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + credit_note: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/credit_note" + description: The ID of the credit note (if any) related to the transaction. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/credit_note" + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + description: The ID of the customer the transaction belongs to. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + ending_balance: + description: The customer's `balance` after the transaction was applied. + A negative value decreases the amount due on the customer's next invoice. + A positive value increases the amount due on the customer's next invoice. + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + description: The ID of the invoice (if any) related to the transaction. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - customer_balance_transaction + type: string + type: + description: 'Transaction type: `adjustment`, `applied_to_invoice`, `credit_note`, + `initial`, `invoice_too_large`, `invoice_too_small`, `unspent_receiver_credit`, + or `unapplied_from_invoice`. See the [Customer Balance page](https://stripe.com/docs/billing/customer/balance#types) + to learn more about transaction types.' + enum: + - adjustment + - applied_to_invoice + - credit_note + - initial + - invoice_too_large + - invoice_too_small + - migration + - unapplied_from_invoice + - unspent_receiver_credit + type: string + required: + - amount + - created + - currency + - customer + - ending_balance + - id + - livemode + - object + - type + title: CustomerBalanceTransaction + type: object + x-expandableFields: + - credit_note + - customer + - invoice + x-resourceId: customer_balance_transaction + customer_tax: + description: '' + properties: + automatic_tax: + description: Surfaces if automatic tax computation is possible given the + current customer location information. + enum: + - failed + - not_collecting + - supported + - unrecognized_location + type: string + ip_address: + description: A recent IP address of the customer used for tax reporting + and tax location inference. + maxLength: 5000 + nullable: true + type: string + location: + anyOf: + - "$ref": "#/components/schemas/customer_tax_location" + description: The customer's location as identified by Stripe Tax. + nullable: true + required: + - automatic_tax + title: CustomerTax + type: object + x-expandableFields: + - location + customer_tax_location: + description: '' + properties: + country: + description: The customer's country as identified by Stripe Tax. + maxLength: 5000 + type: string + source: + description: The data source used to infer the customer's location. + enum: + - billing_address + - ip_address + - payment_method + - shipping_destination + type: string + state: + description: The customer's state, county, province, or region as identified + by Stripe Tax. + maxLength: 5000 + nullable: true + type: string + required: + - country + - source + title: CustomerTaxLocation + type: object + x-expandableFields: [] + deleted_account: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - account + type: string + required: + - deleted + - id + - object + title: DeletedAccount + type: object + x-expandableFields: [] + x-resourceId: deleted_account + deleted_alipay_account: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - alipay_account + type: string + required: + - deleted + - id + - object + title: AlipayDeletedAccount + type: object + x-expandableFields: [] + deleted_apple_pay_domain: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - apple_pay_domain + type: string + required: + - deleted + - id + - object + title: DeletedApplePayDomain + type: object + x-expandableFields: [] + x-resourceId: deleted_apple_pay_domain + deleted_bank_account: + description: '' + properties: + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) + paid out to the bank account. + maxLength: 5000 + nullable: true + type: string + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - bank_account + type: string + required: + - deleted + - id + - object + title: DeletedBankAccount + type: object + x-expandableFields: [] + deleted_bitcoin_receiver: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - bitcoin_receiver + type: string + required: + - deleted + - id + - object + title: BitcoinDeletedReceiver + type: object + x-expandableFields: [] + deleted_card: + description: '' + properties: + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) + paid out to the bank account. + maxLength: 5000 + nullable: true + type: string + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - card + type: string + required: + - deleted + - id + - object + title: DeletedCard + type: object + x-expandableFields: [] + deleted_coupon: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - coupon + type: string + required: + - deleted + - id + - object + title: DeletedCoupon + type: object + x-expandableFields: [] + x-resourceId: deleted_coupon + deleted_customer: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - customer + type: string + required: + - deleted + - id + - object + title: DeletedCustomer + type: object + x-expandableFields: [] + x-resourceId: deleted_customer + deleted_discount: + description: '' + properties: + checkout_session: + description: The Checkout session that this coupon is applied to, if it + is applied to a particular session in payment mode. Will not be present + for subscription mode. + maxLength: 5000 + nullable: true + type: string + coupon: + "$ref": "#/components/schemas/coupon" + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The ID of the customer associated with this discount. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: The ID of the discount object. Discounts cannot be fetched + by ID. Use `expand[]=discounts` in API calls to expand discount IDs in + an array. + maxLength: 5000 + type: string + invoice: + description: The invoice that the discount's coupon was applied to, if it + was applied directly to a particular invoice. + maxLength: 5000 + nullable: true + type: string + invoice_item: + description: The invoice item `id` (or invoice line item `id` for invoice + line items of type='subscription') that the discount's coupon was applied + to, if it was applied directly to a particular invoice item or invoice + line item. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - discount + type: string + promotion_code: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/promotion_code" + description: The promotion code applied to create this discount. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/promotion_code" + start: + description: Date that the coupon was applied. + format: unix-time + type: integer + subscription: + description: The subscription that this coupon is applied to, if it is applied + to a particular subscription. + maxLength: 5000 + nullable: true + type: string + required: + - coupon + - deleted + - id + - object + - start + title: DeletedDiscount + type: object + x-expandableFields: + - coupon + - customer + - promotion_code + x-resourceId: deleted_discount + deleted_external_account: + anyOf: + - "$ref": "#/components/schemas/deleted_bank_account" + - "$ref": "#/components/schemas/deleted_card" + title: Polymorphic + x-resourceId: deleted_external_account + deleted_invoice: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - invoice + type: string + required: + - deleted + - id + - object + title: DeletedInvoice + type: object + x-expandableFields: [] + x-resourceId: deleted_invoice + deleted_invoiceitem: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - invoiceitem + type: string + required: + - deleted + - id + - object + title: DeletedInvoiceItem + type: object + x-expandableFields: [] + x-resourceId: deleted_invoiceitem + deleted_payment_source: + anyOf: + - "$ref": "#/components/schemas/deleted_alipay_account" + - "$ref": "#/components/schemas/deleted_bank_account" + - "$ref": "#/components/schemas/deleted_bitcoin_receiver" + - "$ref": "#/components/schemas/deleted_card" + title: Polymorphic + x-resourceId: deleted_payment_source + deleted_person: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - person + type: string + required: + - deleted + - id + - object + title: DeletedPerson + type: object + x-expandableFields: [] + x-resourceId: deleted_person + deleted_plan: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - plan + type: string + required: + - deleted + - id + - object + title: DeletedPlan + type: object + x-expandableFields: [] + x-resourceId: deleted_plan + deleted_price: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - price + type: string + required: + - deleted + - id + - object + title: DeletedPrice + type: object + x-expandableFields: [] + deleted_product: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - product + type: string + required: + - deleted + - id + - object + title: DeletedProduct + type: object + x-expandableFields: [] + x-resourceId: deleted_product + deleted_radar.value_list: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - radar.value_list + type: string + required: + - deleted + - id + - object + title: RadarListDeletedList + type: object + x-expandableFields: [] + x-resourceId: deleted_radar.value_list + deleted_radar.value_list_item: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - radar.value_list_item + type: string + required: + - deleted + - id + - object + title: RadarListDeletedListItem + type: object + x-expandableFields: [] + x-resourceId: deleted_radar.value_list_item + deleted_recipient: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - recipient + type: string + required: + - deleted + - id + - object + title: DeletedTransferRecipient + type: object + x-expandableFields: [] + x-resourceId: deleted_recipient + deleted_sku: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - sku + type: string + required: + - deleted + - id + - object + title: DeletedSku + type: object + x-expandableFields: [] + x-resourceId: deleted_sku + deleted_subscription_item: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - subscription_item + type: string + required: + - deleted + - id + - object + title: DeletedSubscriptionItem + type: object + x-expandableFields: [] + x-resourceId: deleted_subscription_item + deleted_tax_id: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - tax_id + type: string + required: + - deleted + - id + - object + title: deleted_tax_id + type: object + x-expandableFields: [] + x-resourceId: deleted_tax_id + deleted_terminal.location: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - terminal.location + type: string + required: + - deleted + - id + - object + title: TerminalLocationDeletedLocation + type: object + x-expandableFields: [] + x-resourceId: deleted_terminal.location + deleted_terminal.reader: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - terminal.reader + type: string + required: + - deleted + - id + - object + title: TerminalReaderDeletedReader + type: object + x-expandableFields: [] + x-resourceId: deleted_terminal.reader + deleted_webhook_endpoint: + description: '' + properties: + deleted: + description: Always true for a deleted object + enum: + - true + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - webhook_endpoint + type: string + required: + - deleted + - id + - object + title: NotificationWebhookEndpointDeleted + type: object + x-expandableFields: [] + x-resourceId: deleted_webhook_endpoint + delivery_estimate: + description: '' + properties: + date: + description: If `type` is `"exact"`, `date` will be the expected delivery + date in the format YYYY-MM-DD. + maxLength: 5000 + type: string + earliest: + description: If `type` is `"range"`, `earliest` will be be the earliest + delivery date in the format YYYY-MM-DD. + maxLength: 5000 + type: string + latest: + description: If `type` is `"range"`, `latest` will be the latest delivery + date in the format YYYY-MM-DD. + maxLength: 5000 + type: string + type: + description: The type of estimate. Must be either `"range"` or `"exact"`. + maxLength: 5000 + type: string + required: + - type + title: DeliveryEstimate + type: object + x-expandableFields: [] + discount: + description: |- + A discount represents the actual application of a coupon to a particular + customer. It contains information about when the discount began and when it + will end. + + Related guide: [Applying Discounts to Subscriptions](https://stripe.com/docs/billing/subscriptions/discounts). + properties: + checkout_session: + description: The Checkout session that this coupon is applied to, if it + is applied to a particular session in payment mode. Will not be present + for subscription mode. + maxLength: 5000 + nullable: true + type: string + coupon: + "$ref": "#/components/schemas/coupon" + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The ID of the customer associated with this discount. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + end: + description: If the coupon has a duration of `repeating`, the date that + this discount will end. If the coupon has a duration of `once` or `forever`, + this attribute will be null. + format: unix-time + nullable: true + type: integer + id: + description: The ID of the discount object. Discounts cannot be fetched + by ID. Use `expand[]=discounts` in API calls to expand discount IDs in + an array. + maxLength: 5000 + type: string + invoice: + description: The invoice that the discount's coupon was applied to, if it + was applied directly to a particular invoice. + maxLength: 5000 + nullable: true + type: string + invoice_item: + description: The invoice item `id` (or invoice line item `id` for invoice + line items of type='subscription') that the discount's coupon was applied + to, if it was applied directly to a particular invoice item or invoice + line item. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - discount + type: string + promotion_code: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/promotion_code" + description: The promotion code applied to create this discount. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/promotion_code" + start: + description: Date that the coupon was applied. + format: unix-time + type: integer + subscription: + description: The subscription that this coupon is applied to, if it is applied + to a particular subscription. + maxLength: 5000 + nullable: true + type: string + required: + - coupon + - id + - object + - start + title: Discount + type: object + x-expandableFields: + - coupon + - customer + - promotion_code + x-resourceId: discount + discounts_resource_discount_amount: + description: '' + properties: + amount: + description: The amount, in %s, of the discount. + type: integer + discount: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/discount" + - "$ref": "#/components/schemas/deleted_discount" + description: The discount that was applied to get this discount amount. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/discount" + - "$ref": "#/components/schemas/deleted_discount" + required: + - amount + - discount + title: DiscountsResourceDiscountAmount + type: object + x-expandableFields: + - discount + dispute: + description: |- + A dispute occurs when a customer questions your charge with their card issuer. + When this happens, you're given the opportunity to respond to the dispute with + evidence that shows that the charge is legitimate. You can find more + information about the dispute process in our [Disputes and + Fraud](/docs/disputes) documentation. + + Related guide: [Disputes and Fraud](https://stripe.com/docs/disputes). + properties: + amount: + description: Disputed amount. Usually the amount of the charge, but can + differ (usually because of currency fluctuation or because only part of + the order is disputed). + type: integer + balance_transactions: + description: List of zero, one, or two balance transactions that show funds + withdrawn and reinstated to your Stripe account as a result of this dispute. + items: + "$ref": "#/components/schemas/balance_transaction" + type: array + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the charge that was disputed. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + evidence: + "$ref": "#/components/schemas/dispute_evidence" + evidence_details: + "$ref": "#/components/schemas/dispute_evidence_details" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + is_charge_refundable: + description: If true, it is still possible to refund the disputed payment. + Once the payment has been fully refunded, no further funds will be withdrawn + from your Stripe account as a result of this dispute. + type: boolean + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - dispute + type: string + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: ID of the PaymentIntent that was disputed. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + reason: + description: Reason given by cardholder for dispute. Possible values are + `bank_cannot_process`, `check_returned`, `credit_not_processed`, `customer_initiated`, + `debit_not_authorized`, `duplicate`, `fraudulent`, `general`, `incorrect_account_details`, + `insufficient_funds`, `product_not_received`, `product_unacceptable`, + `subscription_canceled`, or `unrecognized`. Read more about [dispute reasons](https://stripe.com/docs/disputes/categories). + maxLength: 5000 + type: string + status: + description: Current status of dispute. Possible values are `warning_needs_response`, + `warning_under_review`, `warning_closed`, `needs_response`, `under_review`, + `charge_refunded`, `won`, or `lost`. + enum: + - charge_refunded + - lost + - needs_response + - under_review + - warning_closed + - warning_needs_response + - warning_under_review + - won + type: string + required: + - amount + - balance_transactions + - charge + - created + - currency + - evidence + - evidence_details + - id + - is_charge_refundable + - livemode + - metadata + - object + - reason + - status + title: Dispute + type: object + x-expandableFields: + - balance_transactions + - charge + - evidence + - evidence_details + - payment_intent + x-resourceId: dispute + dispute_evidence: + description: '' + properties: + access_activity_log: + description: Any server or activity logs showing proof that the customer + accessed or downloaded the purchased digital product. This information + should include IP addresses, corresponding timestamps, and any detailed + recorded activity. + maxLength: 150000 + nullable: true + type: string + billing_address: + description: The billing address provided by the customer. + maxLength: 5000 + nullable: true + type: string + cancellation_policy: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Your subscription cancellation policy, as shown to the customer." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + cancellation_policy_disclosure: + description: An explanation of how and when the customer was shown your + refund policy prior to purchase. + maxLength: 150000 + nullable: true + type: string + cancellation_rebuttal: + description: A justification for why the customer's subscription was not + canceled. + maxLength: 150000 + nullable: true + type: string + customer_communication: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Any communication with the customer that you feel is relevant to your + case. Examples include emails proving that the customer received the product + or service, or demonstrating their use of or satisfaction with the product + or service." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + customer_email_address: + description: The email address of the customer. + maxLength: 5000 + nullable: true + type: string + customer_name: + description: The name of the customer. + maxLength: 5000 + nullable: true + type: string + customer_purchase_ip: + description: The IP address that the customer used when making the purchase. + maxLength: 5000 + nullable: true + type: string + customer_signature: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + A relevant document or contract showing the customer's signature." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + duplicate_charge_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Documentation for the prior charge that can uniquely identify the charge, + such as a receipt, shipping label, work order, etc. This document should + be paired with a similar document from the disputed payment that proves + the two payments are separate." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + duplicate_charge_explanation: + description: An explanation of the difference between the disputed charge + versus the prior charge that appears to be a duplicate. + maxLength: 150000 + nullable: true + type: string + duplicate_charge_id: + description: The Stripe ID for the prior charge which appears to be a duplicate + of the disputed charge. + maxLength: 5000 + nullable: true + type: string + product_description: + description: A description of the product or service that was sold. + maxLength: 150000 + nullable: true + type: string + receipt: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Any receipt or message sent to the customer notifying them of the charge." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + refund_policy: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Your refund policy, as shown to the customer." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + refund_policy_disclosure: + description: Documentation demonstrating that the customer was shown your + refund policy prior to purchase. + maxLength: 150000 + nullable: true + type: string + refund_refusal_explanation: + description: A justification for why the customer is not entitled to a refund. + maxLength: 150000 + nullable: true + type: string + service_date: + description: The date on which the customer received or began receiving + the purchased service, in a clear human-readable format. + maxLength: 5000 + nullable: true + type: string + service_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Documentation showing proof that a service was provided to the customer. + This could include a copy of a signed contract, work order, or other form + of written agreement." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + shipping_address: + description: The address to which a physical product was shipped. You should + try to include as complete address information as possible. + maxLength: 5000 + nullable: true + type: string + shipping_carrier: + description: The delivery service that shipped a physical product, such + as Fedex, UPS, USPS, etc. If multiple carriers were used for this purchase, + please separate them with commas. + maxLength: 5000 + nullable: true + type: string + shipping_date: + description: The date on which a physical product began its route to the + shipping address, in a clear human-readable format. + maxLength: 5000 + nullable: true + type: string + shipping_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Documentation showing proof that a product was shipped to the customer + at the same address the customer provided to you. This could include a + copy of the shipment receipt, shipping label, etc. It should show the + customer's full shipping address, if possible." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + shipping_tracking_number: + description: The tracking number for a physical product, obtained from the + delivery service. If multiple tracking numbers were generated for this + purchase, please separate them with commas. + maxLength: 5000 + nullable: true + type: string + uncategorized_file: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Any additional evidence or statements." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + uncategorized_text: + description: Any additional evidence or statements. + maxLength: 150000 + nullable: true + type: string + title: DisputeEvidence + type: object + x-expandableFields: + - cancellation_policy + - customer_communication + - customer_signature + - duplicate_charge_documentation + - receipt + - refund_policy + - service_documentation + - shipping_documentation + - uncategorized_file + dispute_evidence_details: + description: '' + properties: + due_by: + description: Date by which evidence must be submitted in order to successfully + challenge dispute. Will be null if the customer's bank or credit card + company doesn't allow a response for this particular dispute. + format: unix-time + nullable: true + type: integer + has_evidence: + description: Whether evidence has been staged for this dispute. + type: boolean + past_due: + description: Whether the last evidence submission was submitted past the + due date. Defaults to `false` if no evidence submissions have occurred. + If `true`, then delivery of the latest evidence is *not* guaranteed. + type: boolean + submission_count: + description: The number of times evidence has been submitted. Typically, + you may only submit evidence once. + type: integer + required: + - has_evidence + - past_due + - submission_count + title: DisputeEvidenceDetails + type: object + x-expandableFields: [] + ephemeral_key: + description: '' + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + expires: + description: Time at which the key will expire. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - ephemeral_key + type: string + secret: + description: The key's secret. You can use this value to make authorized + requests to the Stripe API. + maxLength: 5000 + type: string + required: + - created + - expires + - id + - livemode + - object + title: EphemeralKey + type: object + x-expandableFields: [] + x-resourceId: ephemeral_key + error: + description: An error response from the Stripe API + properties: + error: + "$ref": "#/components/schemas/api_errors" + required: + - error + type: object + event: + description: |- + Events are our way of letting you know when something interesting happens in + your account. When an interesting event occurs, we create a new `Event` + object. For example, when a charge succeeds, we create a `charge.succeeded` + event; and when an invoice payment attempt fails, we create an + `invoice.payment_failed` event. Note that many API requests may cause multiple + events to be created. For example, if you create a new subscription for a + customer, you will receive both a `customer.subscription.created` event and a + `charge.succeeded` event. + + Events occur when the state of another API resource changes. The state of that + resource at the time of the change is embedded in the event's data field. For + example, a `charge.succeeded` event will contain a charge, and an + `invoice.payment_failed` event will contain an invoice. + + As with other API resources, you can use endpoints to retrieve an + [individual event](https://stripe.com/docs/api#retrieve_event) or a [list of events](https://stripe.com/docs/api#list_events) + from the API. We also have a separate + [webhooks](http://en.wikipedia.org/wiki/Webhook) system for sending the + `Event` objects directly to an endpoint on your server. Webhooks are managed + in your + [account settings](https://dashboard.stripe.com/account/webhooks), + and our [Using Webhooks](https://stripe.com/docs/webhooks) guide will help you get set up. + + When using [Connect](https://stripe.com/docs/connect), you can also receive notifications of + events that occur in connected accounts. For these events, there will be an + additional `account` attribute in the received `Event` object. + + **NOTE:** Right now, access to events through the [Retrieve Event API](https://stripe.com/docs/api#retrieve_event) is + guaranteed only for 30 days. + properties: + account: + description: The connected account that originated the event. + maxLength: 5000 + type: string + api_version: + description: 'The Stripe API version used to render `data`. *Note: This + property is populated only for events on or after October 31, 2014*.' + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + data: + "$ref": "#/components/schemas/notification_event_data" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - event + type: string + pending_webhooks: + description: Number of webhooks that have yet to be successfully delivered + (i.e., to return a 20x response) to the URLs you've specified. + type: integer + request: + anyOf: + - "$ref": "#/components/schemas/notification_event_request" + description: Information on the API request that instigated the event. + nullable: true + type: + description: Description of the event (e.g., `invoice.created` or `charge.refunded`). + maxLength: 5000 + type: string + required: + - created + - data + - id + - livemode + - object + - pending_webhooks + - type + title: NotificationEvent + type: object + x-expandableFields: + - data + - request + x-resourceId: event + exchange_rate: + description: |- + `Exchange Rate` objects allow you to determine the rates that Stripe is + currently using to convert from one currency to another. Since this number is + variable throughout the day, there are various reasons why you might want to + know the current rate (for example, to dynamically price an item for a user + with a default payment in a foreign currency). + + If you want a guarantee that the charge is made with a certain exchange rate + you expect is current, you can pass in `exchange_rate` to charges endpoints. + If the value is no longer up to date, the charge won't go through. Please + refer to our [Exchange Rates API](https://stripe.com/docs/exchange-rates) guide for more + details. + properties: + id: + description: Unique identifier for the object. Represented as the three-letter + [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html) + in lowercase. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - exchange_rate + type: string + rates: + additionalProperties: + type: number + description: Hash where the keys are supported currencies and the values + are the exchange rate at which the base id currency converts to the key + currency. + type: object + required: + - id + - object + - rates + title: ExchangeRate + type: object + x-expandableFields: [] + x-resourceId: exchange_rate + external_account: + anyOf: + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/card" + title: Polymorphic + x-resourceId: external_account + fee: + description: '' + properties: + amount: + description: Amount of the fee, in cents. + type: integer + application: + description: ID of the Connect application that earned the fee. + maxLength: 5000 + nullable: true + type: string + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + type: + description: 'Type of the fee, one of: `application_fee`, `stripe_fee` or + `tax`.' + maxLength: 5000 + type: string + required: + - amount + - currency + - type + title: Fee + type: object + x-expandableFields: [] + fee_refund: + description: |- + `Application Fee Refund` objects allow you to refund an application fee that + has previously been created but not yet refunded. Funds will be refunded to + the Stripe account from which the fee was originally collected. + + Related guide: [Refunding Application Fees](https://stripe.com/docs/connect/destination-charges#refunding-app-fee). + properties: + amount: + description: Amount, in %s. + type: integer + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: Balance transaction that describes the impact on your account + balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + fee: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application_fee" + description: ID of the application fee that was refunded. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application_fee" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - fee_refund + type: string + required: + - amount + - created + - currency + - fee + - id + - object + title: FeeRefund + type: object + x-expandableFields: + - balance_transaction + - fee + x-resourceId: fee_refund + file: + description: |- + This is an object representing a file hosted on Stripe's servers. The + file may have been uploaded by yourself using the [create file](https://stripe.com/docs/api#create_file) + request (for example, when uploading dispute evidence) or it may have + been created by Stripe (for example, the results of a [Sigma scheduled + query](#scheduled_queries)). + + Related guide: [File Upload Guide](https://stripe.com/docs/file-upload). + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + expires_at: + description: The time at which the file expires and is no longer available + in epoch seconds. + format: unix-time + nullable: true + type: integer + filename: + description: A filename for the file, suitable for saving to a filesystem. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + links: + description: A list of [file links](https://stripe.com/docs/api#file_links) + that point at this file. + nullable: true + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/file_link" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: FileFileLinkList + type: object + x-expandableFields: + - data + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - file + type: string + purpose: + description: The [purpose](https://stripe.com/docs/file-upload#uploading-a-file) + of the uploaded file. + enum: + - account_requirement + - additional_verification + - business_icon + - business_logo + - customer_signature + - dispute_evidence + - document_provider_identity_document + - finance_report_run + - identity_document + - identity_document_downloadable + - pci_document + - selfie + - sigma_scheduled_query + - tax_document_user_upload + type: string + x-stripeBypassValidation: true + size: + description: The size in bytes of the file object. + type: integer + title: + description: A user friendly title for the document. + maxLength: 5000 + nullable: true + type: string + type: + description: The type of the file returned (e.g., `csv`, `pdf`, `jpg`, or + `png`). + maxLength: 5000 + nullable: true + type: string + url: + description: The URL from which the file can be downloaded using your live + secret API key. + maxLength: 5000 + nullable: true + type: string + required: + - created + - id + - object + - purpose + - size + title: File + type: object + x-expandableFields: + - links + x-resourceId: file + file_link: + description: |- + To share the contents of a `File` object with non-Stripe users, you can + create a `FileLink`. `FileLink`s contain a URL that can be used to + retrieve the contents of the file without authentication. + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + expired: + description: Whether this link is already expired. + type: boolean + expires_at: + description: Time at which the link expires. + format: unix-time + nullable: true + type: integer + file: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The file object this link points to. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - file_link + type: string + url: + description: The publicly accessible URL to download the file. + maxLength: 5000 + nullable: true + type: string + required: + - created + - expired + - file + - id + - livemode + - metadata + - object + title: FileLink + type: object + x-expandableFields: + - file + x-resourceId: file_link + financial_reporting_finance_report_run_run_parameters: + description: '' + properties: + columns: + description: The set of output columns requested for inclusion in the report + run. + items: + maxLength: 5000 + type: string + type: array + connected_account: + description: Connected account ID by which to filter the report run. + maxLength: 5000 + type: string + currency: + description: Currency of objects to be included in the report run. + type: string + interval_end: + description: Ending timestamp of data to be included in the report run (exclusive). + format: unix-time + type: integer + interval_start: + description: Starting timestamp of data to be included in the report run. + format: unix-time + type: integer + payout: + description: Payout ID by which to filter the report run. + maxLength: 5000 + type: string + reporting_category: + description: Category of balance transactions to be included in the report + run. + maxLength: 5000 + type: string + timezone: + description: Defaults to `Etc/UTC`. The output timezone for all timestamps + in the report. A list of possible time zone values is maintained at the + [IANA Time Zone Database](http://www.iana.org/time-zones). Has no effect + on `interval_start` or `interval_end`. + maxLength: 5000 + type: string + title: FinancialReportingFinanceReportRunRunParameters + type: object + x-expandableFields: [] + gelato_data_document_report_date_of_birth: + description: Point in Time + properties: + day: + description: Numerical day between 1 and 31. + nullable: true + type: integer + month: + description: Numerical month between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year. + nullable: true + type: integer + title: GelatoDataDocumentReportDateOfBirth + type: object + x-expandableFields: [] + gelato_data_document_report_expiration_date: + description: Point in Time + properties: + day: + description: Numerical day between 1 and 31. + nullable: true + type: integer + month: + description: Numerical month between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year. + nullable: true + type: integer + title: GelatoDataDocumentReportExpirationDate + type: object + x-expandableFields: [] + gelato_data_document_report_issued_date: + description: Point in Time + properties: + day: + description: Numerical day between 1 and 31. + nullable: true + type: integer + month: + description: Numerical month between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year. + nullable: true + type: integer + title: GelatoDataDocumentReportIssuedDate + type: object + x-expandableFields: [] + gelato_data_id_number_report_date: + description: Point in Time + properties: + day: + description: Numerical day between 1 and 31. + nullable: true + type: integer + month: + description: Numerical month between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year. + nullable: true + type: integer + title: GelatoDataIdNumberReportDate + type: object + x-expandableFields: [] + gelato_data_verified_outputs_date: + description: Point in Time + properties: + day: + description: Numerical day between 1 and 31. + nullable: true + type: integer + month: + description: Numerical month between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year. + nullable: true + type: integer + title: GelatoDataVerifiedOutputsDate + type: object + x-expandableFields: [] + gelato_document_report: + description: Result from a document check + properties: + address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Address as it appears in the document. + nullable: true + dob: + anyOf: + - "$ref": "#/components/schemas/gelato_data_document_report_date_of_birth" + description: Date of birth as it appears in the document. + nullable: true + error: + anyOf: + - "$ref": "#/components/schemas/gelato_document_report_error" + description: Details on the verification error. Present when status is `unverified`. + nullable: true + expiration_date: + anyOf: + - "$ref": "#/components/schemas/gelato_data_document_report_expiration_date" + description: Expiration date of the document. + nullable: true + files: + description: Array of [File](https://stripe.com/docs/api/files) ids containing + images for this document. + items: + maxLength: 5000 + type: string + nullable: true + type: array + first_name: + description: First name as it appears in the document. + maxLength: 5000 + nullable: true + type: string + issued_date: + anyOf: + - "$ref": "#/components/schemas/gelato_data_document_report_issued_date" + description: Issued date of the document. + nullable: true + issuing_country: + description: Issuing country of the document. + maxLength: 5000 + nullable: true + type: string + last_name: + description: Last name as it appears in the document. + maxLength: 5000 + nullable: true + type: string + number: + description: Document ID number. + maxLength: 5000 + nullable: true + type: string + status: + description: Status of this `document` check. + enum: + - unverified + - verified + type: string + x-stripeBypassValidation: true + type: + description: Type of the document. + enum: + - driving_license + - id_card + - passport + nullable: true + type: string + required: + - status + title: GelatoDocumentReport + type: object + x-expandableFields: + - address + - dob + - error + - expiration_date + - issued_date + gelato_document_report_error: + description: '' + properties: + code: + description: A short machine-readable string giving the reason for the verification + failure. + enum: + - document_expired + - document_type_not_supported + - document_unverified_other + nullable: true + type: string + reason: + description: A human-readable message giving the reason for the failure. + These messages can be shown to your users. + maxLength: 5000 + nullable: true + type: string + title: GelatoDocumentReportError + type: object + x-expandableFields: [] + gelato_id_number_report: + description: Result from an id_number check + properties: + dob: + anyOf: + - "$ref": "#/components/schemas/gelato_data_id_number_report_date" + description: Date of birth. + nullable: true + error: + anyOf: + - "$ref": "#/components/schemas/gelato_id_number_report_error" + description: Details on the verification error. Present when status is `unverified`. + nullable: true + first_name: + description: First name. + maxLength: 5000 + nullable: true + type: string + id_number: + description: ID number. + maxLength: 5000 + nullable: true + type: string + id_number_type: + description: Type of ID number. + enum: + - br_cpf + - sg_nric + - us_ssn + nullable: true + type: string + last_name: + description: Last name. + maxLength: 5000 + nullable: true + type: string + status: + description: Status of this `id_number` check. + enum: + - unverified + - verified + type: string + x-stripeBypassValidation: true + required: + - status + title: GelatoIdNumberReport + type: object + x-expandableFields: + - dob + - error + gelato_id_number_report_error: + description: '' + properties: + code: + description: A short machine-readable string giving the reason for the verification + failure. + enum: + - id_number_insufficient_document_data + - id_number_mismatch + - id_number_unverified_other + nullable: true + type: string + reason: + description: A human-readable message giving the reason for the failure. + These messages can be shown to your users. + maxLength: 5000 + nullable: true + type: string + title: GelatoIdNumberReportError + type: object + x-expandableFields: [] + gelato_report_document_options: + description: '' + properties: + allowed_types: + description: Array of strings of allowed identity document types. If the + provided identity document isn’t one of the allowed types, the verification + check will fail with a document_type_not_allowed error code. + items: + enum: + - driving_license + - id_card + - passport + type: string + type: array + require_id_number: + description: Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) + with the document’s extracted name and date of birth. + type: boolean + require_live_capture: + description: Disable image uploads, identity document images have to be + captured using the device’s camera. + type: boolean + require_matching_selfie: + description: Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) + comparing a photo ID and a picture of your user’s face. [Learn more](https://stripe.com/docs/identity/selfie). + type: boolean + title: GelatoReportDocumentOptions + type: object + x-expandableFields: [] + gelato_report_id_number_options: + description: '' + properties: {} + title: GelatoReportIdNumberOptions + type: object + x-expandableFields: [] + gelato_selfie_report: + description: Result from a selfie check + properties: + document: + description: ID of the [File](https://stripe.com/docs/api/files) holding + the image of the identity document used in this check. + maxLength: 5000 + nullable: true + type: string + error: + anyOf: + - "$ref": "#/components/schemas/gelato_selfie_report_error" + description: Details on the verification error. Present when status is `unverified`. + nullable: true + selfie: + description: ID of the [File](https://stripe.com/docs/api/files) holding + the image of the selfie used in this check. + maxLength: 5000 + nullable: true + type: string + status: + description: Status of this `selfie` check. + enum: + - unverified + - verified + type: string + x-stripeBypassValidation: true + required: + - status + title: GelatoSelfieReport + type: object + x-expandableFields: + - error + gelato_selfie_report_error: + description: '' + properties: + code: + description: A short machine-readable string giving the reason for the verification + failure. + enum: + - selfie_document_missing_photo + - selfie_face_mismatch + - selfie_manipulated + - selfie_unverified_other + nullable: true + type: string + reason: + description: A human-readable message giving the reason for the failure. + These messages can be shown to your users. + maxLength: 5000 + nullable: true + type: string + title: GelatoSelfieReportError + type: object + x-expandableFields: [] + gelato_session_document_options: + description: '' + properties: + allowed_types: + description: Array of strings of allowed identity document types. If the + provided identity document isn’t one of the allowed types, the verification + check will fail with a document_type_not_allowed error code. + items: + enum: + - driving_license + - id_card + - passport + type: string + type: array + require_id_number: + description: Collect an ID number and perform an [ID number check](https://stripe.com/docs/identity/verification-checks?type=id-number) + with the document’s extracted name and date of birth. + type: boolean + require_live_capture: + description: Disable image uploads, identity document images have to be + captured using the device’s camera. + type: boolean + require_matching_selfie: + description: Capture a face image and perform a [selfie check](https://stripe.com/docs/identity/verification-checks?type=selfie) + comparing a photo ID and a picture of your user’s face. [Learn more](https://stripe.com/docs/identity/selfie). + type: boolean + title: GelatoSessionDocumentOptions + type: object + x-expandableFields: [] + gelato_session_id_number_options: + description: '' + properties: {} + title: GelatoSessionIdNumberOptions + type: object + x-expandableFields: [] + gelato_session_last_error: + description: Shows last VerificationSession error + properties: + code: + description: A short machine-readable string giving the reason for the verification + or user-session failure. + enum: + - abandoned + - consent_declined + - country_not_supported + - device_not_supported + - document_expired + - document_type_not_supported + - document_unverified_other + - id_number_insufficient_document_data + - id_number_mismatch + - id_number_unverified_other + - selfie_document_missing_photo + - selfie_face_mismatch + - selfie_manipulated + - selfie_unverified_other + - under_supported_age + nullable: true + type: string + reason: + description: A message that explains the reason for verification or user-session + failure. + maxLength: 5000 + nullable: true + type: string + title: GelatoSessionLastError + type: object + x-expandableFields: [] + gelato_verification_report_options: + description: '' + properties: + document: + "$ref": "#/components/schemas/gelato_report_document_options" + id_number: + "$ref": "#/components/schemas/gelato_report_id_number_options" + title: GelatoVerificationReportOptions + type: object + x-expandableFields: + - document + - id_number + gelato_verification_session_options: + description: '' + properties: + document: + "$ref": "#/components/schemas/gelato_session_document_options" + id_number: + "$ref": "#/components/schemas/gelato_session_id_number_options" + title: GelatoVerificationSessionOptions + type: object + x-expandableFields: + - document + - id_number + gelato_verified_outputs: + description: '' + properties: + address: + anyOf: + - "$ref": "#/components/schemas/address" + description: The user's verified address. + nullable: true + dob: + anyOf: + - "$ref": "#/components/schemas/gelato_data_verified_outputs_date" + description: The user’s verified date of birth. + nullable: true + first_name: + description: The user's verified first name. + maxLength: 5000 + nullable: true + type: string + id_number: + description: The user's verified id number. + maxLength: 5000 + nullable: true + type: string + id_number_type: + description: The user's verified id number type. + enum: + - br_cpf + - sg_nric + - us_ssn + nullable: true + type: string + last_name: + description: The user's verified last name. + maxLength: 5000 + nullable: true + type: string + title: GelatoVerifiedOutputs + type: object + x-expandableFields: + - address + - dob + identity.verification_report: + description: |- + A VerificationReport is the result of an attempt to collect and verify data from a user. + The collection of verification checks performed is determined from the `type` and `options` + parameters used. You can find the result of each verification check performed in the + appropriate sub-resource: `document`, `id_number`, `selfie`. + + Each VerificationReport contains a copy of any data collected by the user as well as + reference IDs which can be used to access collected images through the [FileUpload](https://stripe.com/docs/api/files) + API. To configure and create VerificationReports, use the + [VerificationSession](https://stripe.com/docs/api/identity/verification_sessions) API. + + Related guides: [Accessing verification results](https://stripe.com/docs/identity/verification-sessions#results). + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + document: + "$ref": "#/components/schemas/gelato_document_report" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + id_number: + "$ref": "#/components/schemas/gelato_id_number_report" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - identity.verification_report + type: string + options: + "$ref": "#/components/schemas/gelato_verification_report_options" + selfie: + "$ref": "#/components/schemas/gelato_selfie_report" + type: + description: Type of report. + enum: + - document + - id_number + type: string + x-stripeBypassValidation: true + verification_session: + description: ID of the VerificationSession that created this report. + maxLength: 5000 + nullable: true + type: string + required: + - created + - id + - livemode + - object + - options + - type + title: GelatoVerificationReport + type: object + x-expandableFields: + - document + - id_number + - options + - selfie + x-resourceId: identity.verification_report + identity.verification_session: + description: |- + A VerificationSession guides you through the process of collecting and verifying the identities + of your users. It contains details about the type of verification, such as what [verification + check](/docs/identity/verification-checks) to perform. Only create one VerificationSession for + each verification in your system. + + A VerificationSession transitions through [multiple + statuses](/docs/identity/how-sessions-work) throughout its lifetime as it progresses through + the verification flow. The VerificationSession contains the user’s verified data after + verification checks are complete. + + Related guide: [The Verification Sessions API](https://stripe.com/docs/identity/verification-sessions) + properties: + client_secret: + description: The short-lived client secret used by Stripe.js to [show a + verification modal](https://stripe.com/docs/js/identity/modal) inside + your app. This client secret expires after 24 hours and can only be used + once. Don’t store it, log it, embed it in a URL, or expose it to anyone + other than the user. Make sure that you have TLS enabled on any page that + includes the client secret. Refer to our docs on [passing the client secret + to the frontend](https://stripe.com/docs/identity/verification-sessions#client-secret) + to learn more. + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + last_error: + anyOf: + - "$ref": "#/components/schemas/gelato_session_last_error" + description: If present, this property tells you the last error encountered + when processing the verification. + nullable: true + last_verification_report: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/identity.verification_report" + description: ID of the most recent VerificationReport. [Learn more about + accessing detailed verification results.](https://stripe.com/docs/identity/verification-sessions#results) + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/identity.verification_report" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - identity.verification_session + type: string + options: + "$ref": "#/components/schemas/gelato_verification_session_options" + redaction: + anyOf: + - "$ref": "#/components/schemas/verification_session_redaction" + description: Redaction status of this VerificationSession. If the VerificationSession + is not redacted, this field will be null. + nullable: true + status: + description: Status of this VerificationSession. [Learn more about the lifecycle + of sessions](https://stripe.com/docs/identity/how-sessions-work). + enum: + - canceled + - processing + - requires_input + - verified + type: string + type: + description: The type of [verification check](https://stripe.com/docs/identity/verification-checks) + to be performed. + enum: + - document + - id_number + type: string + x-stripeBypassValidation: true + url: + description: The short-lived URL that you use to redirect a user to Stripe + to submit their identity information. This URL expires after 48 hours + and can only be used once. Don’t store it, log it, send it in emails or + expose it to anyone other than the user. Refer to our docs on [verifying + identity documents](https://stripe.com/docs/identity/verify-identity-documents?platform=web&type=redirect) + to learn how to redirect users to Stripe. + maxLength: 5000 + nullable: true + type: string + verified_outputs: + anyOf: + - "$ref": "#/components/schemas/gelato_verified_outputs" + description: The user’s verified data. + nullable: true + required: + - created + - id + - livemode + - metadata + - object + - options + - status + - type + title: GelatoVerificationSession + type: object + x-expandableFields: + - last_error + - last_verification_report + - options + - redaction + - verified_outputs + x-resourceId: identity.verification_session + invoice: + description: |- + Invoices are statements of amounts owed by a customer, and are either + generated one-off, or generated periodically from a subscription. + + They contain [invoice items](https://stripe.com/docs/api#invoiceitems), and proration adjustments + that may be caused by subscription upgrades/downgrades (if necessary). + + If your invoice is configured to be billed through automatic charges, + Stripe automatically finalizes your invoice and attempts payment. Note + that finalizing the invoice, + [when automatic](https://stripe.com/docs/billing/invoices/workflow/#auto_advance), does + not happen immediately as the invoice is created. Stripe waits + until one hour after the last webhook was successfully sent (or the last + webhook timed out after failing). If you (and the platforms you may have + connected to) have no webhooks configured, Stripe waits one hour after + creation to finalize the invoice. + + If your invoice is configured to be billed by sending an email, then based on your + [email settings](https://dashboard.stripe.com/account/billing/automatic), + Stripe will email the invoice to your customer and await payment. These + emails can contain a link to a hosted page to pay the invoice. + + Stripe applies any customer credit on the account before determining the + amount due for the invoice (i.e., the amount that will be actually + charged). If the amount due for the invoice is less than Stripe's [minimum allowed charge + per currency](/docs/currencies#minimum-and-maximum-charge-amounts), the + invoice is automatically marked paid, and we add the amount due to the + customer's credit balance which is applied to the next invoice. + + More details on the customer's credit balance are + [here](https://stripe.com/docs/billing/customer/balance). + + Related guide: [Send Invoices to Customers](https://stripe.com/docs/billing/invoices/sending). + properties: + account_country: + description: The country of the business associated with this invoice, most + often the business creating the invoice. + maxLength: 5000 + nullable: true + type: string + account_name: + description: The public name of the business associated with this invoice, + most often the business creating the invoice. + maxLength: 5000 + nullable: true + type: string + account_tax_ids: + description: The account tax IDs associated with the invoice. Only editable + when the invoice is a draft. + items: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/tax_id" + - "$ref": "#/components/schemas/deleted_tax_id" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/tax_id" + - "$ref": "#/components/schemas/deleted_tax_id" + nullable: true + type: array + amount_due: + description: Final amount due at this time for this invoice. If the invoice's + total is smaller than the minimum charge amount, for example, or if there + is account credit that can be applied to the invoice, the `amount_due` + may be 0. If there is a positive `starting_balance` for the invoice (the + customer owes money), the `amount_due` will also take that into account. + The charge that gets generated for the invoice will be for the amount + specified in `amount_due`. + type: integer + amount_paid: + description: The amount, in %s, that was paid. + type: integer + amount_remaining: + description: The amount remaining, in %s, that is due. + type: integer + application_fee_amount: + description: The fee in %s that will be applied to the invoice and transferred + to the application owner's Stripe account when the invoice is paid. + nullable: true + type: integer + attempt_count: + description: Number of payment attempts made for this invoice, from the + perspective of the payment retry schedule. Any payment attempt counts + as the first attempt, and subsequently only automatic retries increment + the attempt count. In other words, manual payment attempts after the first + attempt do not affect the retry schedule. + type: integer + attempted: + description: Whether an attempt has been made to pay the invoice. An invoice + is not attempted until 1 hour after the `invoice.created` webhook, for + example, so you might not want to display that invoice as unpaid to your + users. + type: boolean + auto_advance: + description: Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) + of the invoice. When `false`, the invoice's state will not automatically + advance without an explicit action. + type: boolean + automatic_tax: + "$ref": "#/components/schemas/automatic_tax" + billing_reason: + description: 'Indicates the reason why the invoice was created. `subscription_cycle` + indicates an invoice created by a subscription advancing into a new period. + `subscription_create` indicates an invoice created due to creating a subscription. + `subscription_update` indicates an invoice created due to updating a subscription. + `subscription` is set for all old invoices to indicate either a change + to a subscription or a period advancement. `manual` is set for all invoices + unrelated to a subscription (for example: created via the invoice editor). + The `upcoming` value is reserved for simulated invoices per the upcoming + invoice endpoint. `subscription_threshold` indicates an invoice created + due to a billing threshold being reached.' + enum: + - automatic_pending_invoice_item_invoice + - manual + - quote_accept + - subscription + - subscription_create + - subscription_cycle + - subscription_threshold + - subscription_update + - upcoming + nullable: true + type: string + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the latest charge generated for this invoice, if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When charging + automatically, Stripe will attempt to pay this invoice using the default + source attached to the customer. When sending an invoice, Stripe will + email this invoice to the customer with payment instructions. + enum: + - charge_automatically + - send_invoice + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + custom_fields: + description: Custom fields displayed on the invoice. + items: + "$ref": "#/components/schemas/invoice_setting_custom_field" + nullable: true + type: array + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The ID of the customer who will be billed. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + customer_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: The customer's address. Until the invoice is finalized, this + field will equal `customer.address`. Once the invoice is finalized, this + field will no longer be updated. + nullable: true + customer_email: + description: The customer's email. Until the invoice is finalized, this + field will equal `customer.email`. Once the invoice is finalized, this + field will no longer be updated. + maxLength: 5000 + nullable: true + type: string + customer_name: + description: The customer's name. Until the invoice is finalized, this field + will equal `customer.name`. Once the invoice is finalized, this field + will no longer be updated. + maxLength: 5000 + nullable: true + type: string + customer_phone: + description: The customer's phone number. Until the invoice is finalized, + this field will equal `customer.phone`. Once the invoice is finalized, + this field will no longer be updated. + maxLength: 5000 + nullable: true + type: string + customer_shipping: + anyOf: + - "$ref": "#/components/schemas/shipping" + description: The customer's shipping information. Until the invoice is finalized, + this field will equal `customer.shipping`. Once the invoice is finalized, + this field will no longer be updated. + nullable: true + customer_tax_exempt: + description: The customer's tax exempt status. Until the invoice is finalized, + this field will equal `customer.tax_exempt`. Once the invoice is finalized, + this field will no longer be updated. + enum: + - exempt + - none + - reverse + nullable: true + type: string + customer_tax_ids: + description: The customer's tax IDs. Until the invoice is finalized, this + field will contain the same tax IDs as `customer.tax_ids`. Once the invoice + is finalized, this field will no longer be updated. + items: + "$ref": "#/components/schemas/invoices_resource_invoice_tax_id" + nullable: true + type: array + default_payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the default payment method for the invoice. It must belong + to the customer associated with the invoice. If not set, defaults to the + subscription's default payment method, if any, or to the default payment + method in the customer's invoice settings. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + default_source: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + description: ID of the default payment source for the invoice. It must belong + to the customer associated with the invoice and be in a chargeable state. + If not set, defaults to the subscription's default source, if any, or + to the customer's default source. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + default_tax_rates: + description: The tax rates applied to this invoice, if any. + items: + "$ref": "#/components/schemas/tax_rate" + type: array + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. Referenced as 'memo' in the Dashboard. + maxLength: 5000 + nullable: true + type: string + discount: + anyOf: + - "$ref": "#/components/schemas/discount" + description: Describes the current discount applied to this invoice, if + there is one. Not populated if there are multiple discounts. + nullable: true + discounts: + description: The discounts applied to the invoice. Line item discounts are + applied before invoice discounts. Use `expand[]=discounts` to expand each + discount. + items: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/discount" + - "$ref": "#/components/schemas/deleted_discount" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/discount" + - "$ref": "#/components/schemas/deleted_discount" + nullable: true + type: array + due_date: + description: The date on which payment for this invoice is due. This value + will be `null` for invoices where `collection_method=charge_automatically`. + format: unix-time + nullable: true + type: integer + ending_balance: + description: Ending customer balance after the invoice is finalized. Invoices + are finalized approximately an hour after successful webhook delivery + or when payment collection is attempted for the invoice. If the invoice + has not been finalized yet, this will be null. + nullable: true + type: integer + footer: + description: Footer displayed on the invoice. + maxLength: 5000 + nullable: true + type: string + hosted_invoice_url: + description: The URL for the hosted invoice page, which allows customers + to view and pay an invoice. If the invoice has not been finalized yet, + this will be null. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice_pdf: + description: The link to download the PDF for the invoice. If the invoice + has not been finalized yet, this will be null. + maxLength: 5000 + nullable: true + type: string + last_finalization_error: + anyOf: + - "$ref": "#/components/schemas/api_errors" + description: The error encountered during the previous attempt to finalize + the invoice. This field is cleared when the invoice is successfully finalized. + nullable: true + lines: + description: 'The individual line items that make up the invoice. `lines` + is sorted as follows: invoice items in reverse chronological order, followed + by the subscription, if any.' + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/line_item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: InvoiceLinesList + type: object + x-expandableFields: + - data + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + next_payment_attempt: + description: The time at which payment will next be attempted. This value + will be `null` for invoices where `collection_method=send_invoice`. + format: unix-time + nullable: true + type: integer + number: + description: A unique, identifying string that appears on emails sent to + the customer for this invoice. This starts with the customer's unique + invoice_prefix if it is specified. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - invoice + type: string + on_behalf_of: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account (if any) for which the funds of the invoice payment + are intended. If set, the invoice will be presented with the branding + and support information of the specified account. See the [Invoices with + Connect](https://stripe.com/docs/billing/invoices/connect) documentation + for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + paid: + description: Whether payment was successfully collected for this invoice. + An invoice can be paid (most commonly) with a charge or with credit from + the customer's account balance. + type: boolean + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: The PaymentIntent associated with this invoice. The PaymentIntent + is generated when the invoice is finalized, and can then be used to pay + the invoice. Note that voiding an invoice will cancel the PaymentIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + payment_settings: + "$ref": "#/components/schemas/invoices_payment_settings" + period_end: + description: End of the usage period during which invoice items were added + to this invoice. + format: unix-time + type: integer + period_start: + description: Start of the usage period during which invoice items were added + to this invoice. + format: unix-time + type: integer + post_payment_credit_notes_amount: + description: Total amount of all post-payment credit notes issued for this + invoice. + type: integer + pre_payment_credit_notes_amount: + description: Total amount of all pre-payment credit notes issued for this + invoice. + type: integer + quote: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/quote" + description: The quote this invoice was generated from. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/quote" + receipt_number: + description: This is the transaction number that appears on email receipts + sent for this invoice. + maxLength: 5000 + nullable: true + type: string + starting_balance: + description: Starting customer balance before the invoice is finalized. + If the invoice has not been finalized yet, this will be the current customer + balance. + type: integer + statement_descriptor: + description: Extra information about an invoice for the customer's credit + card statement. + maxLength: 5000 + nullable: true + type: string + status: + description: The status of the invoice, one of `draft`, `open`, `paid`, + `uncollectible`, or `void`. [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview) + enum: + - deleted + - draft + - open + - paid + - uncollectible + - void + nullable: true + type: string + status_transitions: + "$ref": "#/components/schemas/invoices_status_transitions" + subscription: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription" + description: The subscription that this invoice was prepared for, if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription" + subscription_proration_date: + description: Only set for upcoming invoices that preview prorations. The + time used to calculate prorations. + type: integer + subtotal: + description: Total of all subscriptions, invoice items, and prorations on + the invoice before any invoice level discount or tax is applied. Item + discounts are already incorporated + type: integer + tax: + description: The amount of tax on this invoice. This is the sum of all the + tax amounts on this invoice. + nullable: true + type: integer + threshold_reason: + "$ref": "#/components/schemas/invoice_threshold_reason" + total: + description: Total after discounts and taxes. + type: integer + total_discount_amounts: + description: The aggregate amounts calculated per discount across all line + items. + items: + "$ref": "#/components/schemas/discounts_resource_discount_amount" + nullable: true + type: array + total_tax_amounts: + description: The aggregate amounts calculated per tax rate for all line + items. + items: + "$ref": "#/components/schemas/invoice_tax_amount" + type: array + transfer_data: + anyOf: + - "$ref": "#/components/schemas/invoice_transfer_data" + description: The account (if any) the payment will be attributed to for + tax reporting, and where funds from the payment will be transferred to + for the invoice. + nullable: true + webhooks_delivered_at: + description: Invoices are automatically paid or sent 1 hour after webhooks + are delivered, or until all webhook delivery attempts have [been exhausted](https://stripe.com/docs/billing/webhooks#understand). + This field tracks the time when webhooks for this invoice were successfully + delivered. If the invoice had no webhooks to deliver, this will be set + while the invoice is being created. + format: unix-time + nullable: true + type: integer + required: + - amount_due + - amount_paid + - amount_remaining + - attempt_count + - attempted + - automatic_tax + - collection_method + - created + - currency + - default_tax_rates + - lines + - livemode + - object + - paid + - payment_settings + - period_end + - period_start + - post_payment_credit_notes_amount + - pre_payment_credit_notes_amount + - starting_balance + - status_transitions + - subtotal + - total + - total_tax_amounts + title: Invoice + type: object + x-expandableFields: + - account_tax_ids + - automatic_tax + - charge + - custom_fields + - customer + - customer_address + - customer_shipping + - customer_tax_ids + - default_payment_method + - default_source + - default_tax_rates + - discount + - discounts + - last_finalization_error + - lines + - on_behalf_of + - payment_intent + - payment_settings + - quote + - status_transitions + - subscription + - threshold_reason + - total_discount_amounts + - total_tax_amounts + - transfer_data + x-resourceId: invoice + invoice_item_threshold_reason: + description: '' + properties: + line_item_ids: + description: The IDs of the line items that triggered the threshold invoice. + items: + maxLength: 5000 + type: string + type: array + usage_gte: + description: The quantity threshold boundary that applied to the given line + item. + type: integer + required: + - line_item_ids + - usage_gte + title: InvoiceItemThresholdReason + type: object + x-expandableFields: [] + invoice_line_item_period: + description: '' + properties: + end: + description: End of the line item's billing period + format: unix-time + type: integer + start: + description: Start of the line item's billing period + format: unix-time + type: integer + required: + - end + - start + title: InvoiceLineItemPeriod + type: object + x-expandableFields: [] + invoice_payment_method_options_bancontact: + description: '' + properties: + preferred_language: + description: Preferred language of the Bancontact authorization page that + the customer is redirected to. + enum: + - de + - en + - fr + - nl + type: string + required: + - preferred_language + title: invoice_payment_method_options_bancontact + type: object + x-expandableFields: [] + invoice_payment_method_options_card: + description: '' + properties: + request_three_d_secure: + description: We strongly recommend that you rely on our SCA Engine to automatically + prompt your customers for authentication based on risk level and [other + requirements](https://stripe.com/docs/strong-customer-authentication). + However, if you wish to request 3D Secure based on logic from your own + fraud engine, provide this option. Read our guide on [manually requesting + 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) + for more information on how this configuration interacts with Radar and + our SCA Engine. + enum: + - any + - automatic + nullable: true + type: string + title: invoice_payment_method_options_card + type: object + x-expandableFields: [] + invoice_setting_custom_field: + description: '' + properties: + name: + description: The name of the custom field. + maxLength: 5000 + type: string + value: + description: The value of the custom field. + maxLength: 5000 + type: string + required: + - name + - value + title: InvoiceSettingCustomField + type: object + x-expandableFields: [] + invoice_setting_customer_setting: + description: '' + properties: + custom_fields: + description: Default custom fields to be displayed on invoices for this + customer. + items: + "$ref": "#/components/schemas/invoice_setting_custom_field" + nullable: true + type: array + default_payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of a payment method that's attached to the customer, to + be used as the customer's default payment method for subscriptions and + invoices. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + footer: + description: Default footer to be displayed on invoices for this customer. + maxLength: 5000 + nullable: true + type: string + title: InvoiceSettingCustomerSetting + type: object + x-expandableFields: + - custom_fields + - default_payment_method + invoice_setting_quote_setting: + description: '' + properties: + days_until_due: + description: Number of days within which a customer must pay invoices generated + by this quote. This value will be `null` for quotes where `collection_method=charge_automatically`. + nullable: true + type: integer + title: InvoiceSettingQuoteSetting + type: object + x-expandableFields: [] + invoice_setting_subscription_schedule_setting: + description: '' + properties: + days_until_due: + description: Number of days within which a customer must pay invoices generated + by this subscription schedule. This value will be `null` for subscription + schedules where `billing=charge_automatically`. + nullable: true + type: integer + title: InvoiceSettingSubscriptionScheduleSetting + type: object + x-expandableFields: [] + invoice_tax_amount: + description: '' + properties: + amount: + description: The amount, in %s, of the tax. + type: integer + inclusive: + description: Whether this tax amount is inclusive or exclusive. + type: boolean + tax_rate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/tax_rate" + description: The tax rate that was applied to get this tax amount. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/tax_rate" + required: + - amount + - inclusive + - tax_rate + title: InvoiceTaxAmount + type: object + x-expandableFields: + - tax_rate + invoice_threshold_reason: + description: '' + properties: + amount_gte: + description: The total invoice amount threshold boundary if it triggered + the threshold invoice. + nullable: true + type: integer + item_reasons: + description: Indicates which line items triggered a threshold invoice. + items: + "$ref": "#/components/schemas/invoice_item_threshold_reason" + type: array + required: + - item_reasons + title: InvoiceThresholdReason + type: object + x-expandableFields: + - item_reasons + invoice_transfer_data: + description: '' + properties: + amount: + description: The amount in %s that will be transferred to the destination + account when the invoice is paid. By default, the entire amount is transferred + to the destination. + nullable: true + type: integer + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account where funds from the payment will be transferred + to upon payment success. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + required: + - destination + title: InvoiceTransferData + type: object + x-expandableFields: + - destination + invoiceitem: + description: |- + Sometimes you want to add a charge or credit to a customer, but actually + charge or credit the customer's card only at the end of a regular billing + cycle. This is useful for combining several charges (to minimize + per-transaction fees), or for having Stripe tabulate your usage-based billing + totals. + + Related guide: [Subscription Invoices](https://stripe.com/docs/billing/invoices/subscription#adding-upcoming-invoice-items). + properties: + amount: + description: Amount (in the `currency` specified) of the invoice item. This + should always be equal to `unit_amount * quantity`. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The ID of the customer who will be billed when this invoice + item is billed. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + date: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + discountable: + description: If true, discounts will apply to this invoice item. Always + false for prorations. + type: boolean + discounts: + description: The discounts which apply to the invoice item. Item discounts + are applied before invoice discounts. Use `expand[]=discounts` to expand + each discount. + items: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/discount" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/discount" + nullable: true + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + description: The ID of the invoice this invoice item belongs to. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - invoiceitem + type: string + period: + "$ref": "#/components/schemas/invoice_line_item_period" + price: + anyOf: + - "$ref": "#/components/schemas/price" + description: The price of the invoice item. + nullable: true + proration: + description: Whether the invoice item was created automatically as a proration + adjustment when the customer switched plans. + type: boolean + quantity: + description: Quantity of units for the invoice item. If the invoice item + is a proration, the quantity of the subscription that the proration was + computed for. + type: integer + subscription: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription" + description: The subscription that this invoice item has been created for, + if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription" + subscription_item: + description: The subscription item that this invoice item has been created + for, if any. + maxLength: 5000 + type: string + tax_rates: + description: The tax rates which apply to the invoice item. When set, the + `default_tax_rates` on the invoice do not apply to this invoice item. + items: + "$ref": "#/components/schemas/tax_rate" + nullable: true + type: array + unit_amount: + description: Unit amount (in the `currency` specified) of the invoice item. + nullable: true + type: integer + unit_amount_decimal: + description: Same as `unit_amount`, but contains a decimal value with at + most 12 decimal places. + format: decimal + nullable: true + type: string + required: + - amount + - currency + - customer + - date + - discountable + - id + - livemode + - object + - period + - proration + - quantity + title: InvoiceItem + type: object + x-expandableFields: + - customer + - discounts + - invoice + - period + - price + - subscription + - tax_rates + x-resourceId: invoiceitem + invoices_payment_method_options: + description: '' + properties: + bancontact: + anyOf: + - "$ref": "#/components/schemas/invoice_payment_method_options_bancontact" + description: If paying by `bancontact`, this sub-hash contains details about + the Bancontact payment method options to pass to the invoice’s PaymentIntent. + nullable: true + card: + anyOf: + - "$ref": "#/components/schemas/invoice_payment_method_options_card" + description: If paying by `card`, this sub-hash contains details about the + Card payment method options to pass to the invoice’s PaymentIntent. + nullable: true + title: InvoicesPaymentMethodOptions + type: object + x-expandableFields: + - bancontact + - card + invoices_payment_settings: + description: '' + properties: + payment_method_options: + anyOf: + - "$ref": "#/components/schemas/invoices_payment_method_options" + description: Payment-method-specific configuration to provide to the invoice’s + PaymentIntent. + nullable: true + payment_method_types: + description: The list of payment method types (e.g. card) to provide to + the invoice’s PaymentIntent. If not set, Stripe attempts to automatically + determine the types to use by looking at the invoice’s default payment + method, the subscription’s default payment method, the customer’s default + payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + items: + enum: + - ach_credit_transfer + - ach_debit + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - fpx + - giropay + - ideal + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + nullable: true + type: array + title: InvoicesPaymentSettings + type: object + x-expandableFields: + - payment_method_options + invoices_resource_invoice_tax_id: + description: '' + properties: + type: + description: The type of the tax ID, one of `eu_vat`, `br_cnpj`, `br_cpf`, + `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `za_vat`, + `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, + `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `li_uid`, `my_itn`, `us_ein`, `kr_brn`, + `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, + `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, + or `unknown` + enum: + - ae_trn + - au_abn + - au_arn + - br_cnpj + - br_cpf + - ca_bn + - ca_gst_hst + - ca_pst_bc + - ca_pst_mb + - ca_pst_sk + - ca_qst + - ch_vat + - cl_tin + - es_cif + - eu_vat + - gb_vat + - hk_br + - id_npwp + - il_vat + - in_gst + - jp_cn + - jp_rn + - kr_brn + - li_uid + - mx_rfc + - my_frp + - my_itn + - my_sst + - no_vat + - nz_gst + - ru_inn + - ru_kpp + - sa_vat + - sg_gst + - sg_uen + - th_vat + - tw_vat + - unknown + - us_ein + - za_vat + type: string + value: + description: The value of the tax ID. + maxLength: 5000 + nullable: true + type: string + required: + - type + title: InvoicesResourceInvoiceTaxID + type: object + x-expandableFields: [] + invoices_status_transitions: + description: '' + properties: + finalized_at: + description: The time that the invoice draft was finalized. + format: unix-time + nullable: true + type: integer + marked_uncollectible_at: + description: The time that the invoice was marked uncollectible. + format: unix-time + nullable: true + type: integer + paid_at: + description: The time that the invoice was paid. + format: unix-time + nullable: true + type: integer + voided_at: + description: The time that the invoice was voided. + format: unix-time + nullable: true + type: integer + title: InvoicesStatusTransitions + type: object + x-expandableFields: [] + issuer_fraud_record: + description: |- + This resource has been renamed to [Early Fraud + Warning](#early_fraud_warning_object) and will be removed in a future API + version. + properties: + actionable: + description: An IFR is actionable if it has not received a dispute and has + not been fully refunded. You may wish to proactively refund a charge that + receives an IFR, in order to avoid receiving a dispute later. + type: boolean + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the charge this issuer fraud record is for, optionally + expanded. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + fraud_type: + description: The type of fraud labelled by the issuer. One of `card_never_received`, + `fraudulent_card_application`, `made_with_counterfeit_card`, `made_with_lost_card`, + `made_with_stolen_card`, `misc`, `unauthorized_use_of_card`. + maxLength: 5000 + type: string + has_liability_shift: + description: If true, the associated charge is subject to [liability shift](https://stripe.com/docs/payments/3d-secure#disputed-payments). + type: boolean + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuer_fraud_record + type: string + post_date: + description: The timestamp at which the card issuer posted the issuer fraud + record. + type: integer + required: + - actionable + - charge + - created + - fraud_type + - has_liability_shift + - id + - livemode + - object + - post_date + title: IssuerFraudRecord + type: object + x-expandableFields: + - charge + x-resourceId: issuer_fraud_record + issuing.authorization: + description: |- + When an [issued card](https://stripe.com/docs/issuing) is used to make a purchase, an Issuing `Authorization` + object is created. [Authorizations](https://stripe.com/docs/issuing/purchases/authorizations) must be approved for the + purchase to be completed successfully. + + Related guide: [Issued Card Authorizations](https://stripe.com/docs/issuing/purchases/authorizations). + properties: + amount: + description: The total amount that was authorized or rejected. This amount + is in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + type: integer + amount_details: + anyOf: + - "$ref": "#/components/schemas/issuing_authorization_amount_details" + description: Detailed breakdown of amount components. These amounts are + denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + nullable: true + approved: + description: Whether the authorization has been approved. + type: boolean + authorization_method: + description: How the card details were provided. + enum: + - chip + - contactless + - keyed_in + - online + - swipe + type: string + balance_transactions: + description: List of balance transactions associated with this authorization. + items: + "$ref": "#/components/schemas/balance_transaction" + type: array + card: + "$ref": "#/components/schemas/issuing.card" + cardholder: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.cardholder" + description: The cardholder to whom this authorization belongs. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.cardholder" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + merchant_amount: + description: The total amount that was authorized or rejected. This amount + is in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + type: integer + merchant_currency: + description: The currency that was presented to the cardholder for the authorization. + Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + merchant_data: + "$ref": "#/components/schemas/issuing_authorization_merchant_data" + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuing.authorization + type: string + pending_request: + anyOf: + - "$ref": "#/components/schemas/issuing_authorization_pending_request" + description: The pending authorization request. This field will only be + non-null during an `issuing_authorization.request` webhook. + nullable: true + request_history: + description: History of every time `pending_request` was approved/denied, + either by you directly or by Stripe (e.g. based on your `spending_controls`). + If the merchant changes the authorization by performing an [incremental + authorization](https://stripe.com/docs/issuing/purchases/authorizations), + you can look at this field to see the previous requests for the authorization. + items: + "$ref": "#/components/schemas/issuing_authorization_request" + type: array + status: + description: The current status of the authorization in its lifecycle. + enum: + - closed + - pending + - reversed + type: string + transactions: + description: List of [transactions](https://stripe.com/docs/api/issuing/transactions) + associated with this authorization. + items: + "$ref": "#/components/schemas/issuing.transaction" + type: array + verification_data: + "$ref": "#/components/schemas/issuing_authorization_verification_data" + wallet: + description: The digital wallet used for this authorization. One of `apple_pay`, + `google_pay`, or `samsung_pay`. + maxLength: 5000 + nullable: true + type: string + required: + - amount + - approved + - authorization_method + - balance_transactions + - card + - created + - currency + - id + - livemode + - merchant_amount + - merchant_currency + - merchant_data + - metadata + - object + - request_history + - status + - transactions + - verification_data + title: IssuingAuthorization + type: object + x-expandableFields: + - amount_details + - balance_transactions + - card + - cardholder + - merchant_data + - pending_request + - request_history + - transactions + - verification_data + x-resourceId: issuing.authorization + issuing.card: + description: You can [create physical or virtual cards](https://stripe.com/docs/issuing/cards) + that are issued to cardholders. + properties: + brand: + description: The brand of the card. + maxLength: 5000 + type: string + cancellation_reason: + description: The reason why the card was canceled. + enum: + - lost + - stolen + nullable: true + type: string + cardholder: + "$ref": "#/components/schemas/issuing.cardholder" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + cvc: + description: The card's CVC. For security reasons, this is only available + for virtual cards, and will be omitted unless you explicitly request it + with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). + Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), + not via "List all cards" or any other endpoint. + maxLength: 5000 + type: string + exp_month: + description: The expiration month of the card. + type: integer + exp_year: + description: The expiration year of the card. + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + last4: + description: The last 4 digits of the card number. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + number: + description: The full unredacted card number. For security reasons, this + is only available for virtual cards, and will be omitted unless you explicitly + request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). + Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), + not via "List all cards" or any other endpoint. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuing.card + type: string + replaced_by: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.card" + description: The latest card that replaces this card, if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.card" + replacement_for: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.card" + description: The card this card replaces, if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.card" + replacement_reason: + description: The reason why the previous card needed to be replaced. + enum: + - damaged + - expired + - lost + - stolen + nullable: true + type: string + x-stripeBypassValidation: true + shipping: + anyOf: + - "$ref": "#/components/schemas/issuing_card_shipping" + description: Where and how the card will be shipped. + nullable: true + spending_controls: + "$ref": "#/components/schemas/issuing_card_authorization_controls" + status: + description: Whether authorizations can be approved on this card. + enum: + - active + - canceled + - inactive + type: string + x-stripeBypassValidation: true + type: + description: The type of the card. + enum: + - physical + - virtual + type: string + required: + - brand + - cardholder + - created + - currency + - exp_month + - exp_year + - id + - last4 + - livemode + - metadata + - object + - spending_controls + - status + - type + title: IssuingCard + type: object + x-expandableFields: + - cardholder + - replaced_by + - replacement_for + - shipping + - spending_controls + x-resourceId: issuing.card + issuing.cardholder: + description: |- + An Issuing `Cardholder` object represents an individual or business entity who is [issued](https://stripe.com/docs/issuing) cards. + + Related guide: [How to create a Cardholder](https://stripe.com/docs/issuing/cards#create-cardholder) + properties: + billing: + "$ref": "#/components/schemas/issuing_cardholder_address" + company: + anyOf: + - "$ref": "#/components/schemas/issuing_cardholder_company" + description: Additional information about a `company` cardholder. + nullable: true + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + email: + description: The cardholder's email address. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + individual: + anyOf: + - "$ref": "#/components/schemas/issuing_cardholder_individual" + description: Additional information about an `individual` cardholder. + nullable: true + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + name: + description: The cardholder's name. This will be printed on cards issued + to them. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuing.cardholder + type: string + phone_number: + description: The cardholder's phone number. This is required for all cardholders + who will be creating EU cards. See the [3D Secure documentation](https://stripe.com/docs/issuing/3d-secure#when-is-3d-secure-applied) + for more details. + maxLength: 5000 + nullable: true + type: string + requirements: + "$ref": "#/components/schemas/issuing_cardholder_requirements" + spending_controls: + anyOf: + - "$ref": "#/components/schemas/issuing_cardholder_authorization_controls" + description: Rules that control spending across this cardholder's cards. + Refer to our [documentation](https://stripe.com/docs/issuing/controls/spending-controls) + for more details. + nullable: true + status: + description: Specifies whether to permit authorizations on this cardholder's + cards. + enum: + - active + - blocked + - inactive + type: string + type: + description: One of `individual` or `company`. + enum: + - company + - individual + type: string + x-stripeBypassValidation: true + required: + - billing + - created + - id + - livemode + - metadata + - name + - object + - requirements + - status + - type + title: IssuingCardholder + type: object + x-expandableFields: + - billing + - company + - individual + - requirements + - spending_controls + x-resourceId: issuing.cardholder + issuing.dispute: + description: |- + As a [card issuer](https://stripe.com/docs/issuing), you can dispute transactions that the cardholder does not recognize, suspects to be fraudulent, or has other issues with. + + Related guide: [Disputing Transactions](https://stripe.com/docs/issuing/purchases/disputes) + properties: + amount: + description: Disputed amount. Usually the amount of the `transaction`, but + can differ (usually because of currency fluctuation). + type: integer + balance_transactions: + description: List of balance transactions associated with the dispute. + items: + "$ref": "#/components/schemas/balance_transaction" + nullable: true + type: array + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: The currency the `transaction` was made in. + type: string + evidence: + "$ref": "#/components/schemas/issuing_dispute_evidence" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuing.dispute + type: string + status: + description: Current status of the dispute. + enum: + - expired + - lost + - submitted + - unsubmitted + - won + type: string + transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.transaction" + description: The transaction being disputed. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.transaction" + required: + - amount + - created + - currency + - evidence + - id + - livemode + - metadata + - object + - status + - transaction + title: IssuingDispute + type: object + x-expandableFields: + - balance_transactions + - evidence + - transaction + x-resourceId: issuing.dispute + issuing.settlement: + description: When a non-stripe BIN is used, any use of an [issued card](https://stripe.com/docs/issuing) + must be settled directly with the card network. The net amount owed is represented + by an Issuing `Settlement` object. + properties: + bin: + description: The Bank Identification Number reflecting this settlement record. + maxLength: 5000 + type: string + clearing_date: + description: The date that the transactions are cleared and posted to user's + accounts. + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + interchange_fees: + description: The total interchange received as reimbursement for the transactions. + type: integer + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + net_total: + description: The total net amount required to settle with the network. + type: integer + network: + description: The card network for this settlement report. One of ["visa"] + enum: + - visa + type: string + network_fees: + description: The total amount of fees owed to the network. + type: integer + network_settlement_identifier: + description: The Settlement Identification Number assigned by the network. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuing.settlement + type: string + settlement_service: + description: One of `international` or `uk_national_net`. + maxLength: 5000 + type: string + transaction_count: + description: The total number of transactions reflected in this settlement. + type: integer + transaction_volume: + description: The total transaction amount reflected in this settlement. + type: integer + required: + - bin + - clearing_date + - created + - currency + - id + - interchange_fees + - livemode + - metadata + - net_total + - network + - network_fees + - network_settlement_identifier + - object + - settlement_service + - transaction_count + - transaction_volume + title: IssuingSettlement + type: object + x-expandableFields: [] + x-resourceId: issuing.settlement + issuing.transaction: + description: |- + Any use of an [issued card](https://stripe.com/docs/issuing) that results in funds entering or leaving + your Stripe account, such as a completed purchase or refund, is represented by an Issuing + `Transaction` object. + + Related guide: [Issued Card Transactions](https://stripe.com/docs/issuing/purchases/transactions). + properties: + amount: + description: The transaction amount, which will be reflected in your balance. + This amount is in your currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + type: integer + amount_details: + anyOf: + - "$ref": "#/components/schemas/issuing_transaction_amount_details" + description: Detailed breakdown of amount components. These amounts are + denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + nullable: true + authorization: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.authorization" + description: The `Authorization` object that led to this transaction. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.authorization" + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: ID of the [balance transaction](https://stripe.com/docs/api/balance_transactions) + associated with this transaction. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + card: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.card" + description: The card used to make this transaction. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.card" + cardholder: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.cardholder" + description: The cardholder to whom this transaction belongs. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.cardholder" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + dispute: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/issuing.dispute" + description: If you've disputed the transaction, the ID of the dispute. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/issuing.dispute" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + merchant_amount: + description: The amount that the merchant will receive, denominated in `merchant_currency` + and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + It will be different from `amount` if the merchant is taking payment in + a different currency. + type: integer + merchant_currency: + description: The currency with which the merchant is taking payment. + type: string + merchant_data: + "$ref": "#/components/schemas/issuing_authorization_merchant_data" + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - issuing.transaction + type: string + purchase_details: + anyOf: + - "$ref": "#/components/schemas/issuing_transaction_purchase_details" + description: Additional purchase information that is optionally provided + by the merchant. + nullable: true + type: + description: The nature of the transaction. + enum: + - capture + - refund + type: string + x-stripeBypassValidation: true + wallet: + description: The digital wallet used for this transaction. One of `apple_pay`, + `google_pay`, or `samsung_pay`. + enum: + - apple_pay + - google_pay + - samsung_pay + nullable: true + type: string + required: + - amount + - card + - created + - currency + - id + - livemode + - merchant_amount + - merchant_currency + - merchant_data + - metadata + - object + - type + title: IssuingTransaction + type: object + x-expandableFields: + - amount_details + - authorization + - balance_transaction + - card + - cardholder + - dispute + - merchant_data + - purchase_details + x-resourceId: issuing.transaction + issuing_authorization_amount_details: + description: '' + properties: + atm_fee: + description: The fee charged by the ATM for the cash withdrawal. + nullable: true + type: integer + title: IssuingAuthorizationAmountDetails + type: object + x-expandableFields: [] + issuing_authorization_merchant_data: + description: '' + properties: + category: + description: A categorization of the seller's type of business. See our + [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) + for a list of possible values. + maxLength: 5000 + type: string + category_code: + description: The merchant category code for the seller’s business + maxLength: 5000 + type: string + city: + description: City where the seller is located + maxLength: 5000 + nullable: true + type: string + country: + description: Country where the seller is located + maxLength: 5000 + nullable: true + type: string + name: + description: Name of the seller + maxLength: 5000 + nullable: true + type: string + network_id: + description: Identifier assigned to the seller by the card brand + maxLength: 5000 + type: string + postal_code: + description: Postal code where the seller is located + maxLength: 5000 + nullable: true + type: string + state: + description: State where the seller is located + maxLength: 5000 + nullable: true + type: string + required: + - category + - category_code + - network_id + title: IssuingAuthorizationMerchantData + type: object + x-expandableFields: [] + issuing_authorization_pending_request: + description: '' + properties: + amount: + description: The additional amount Stripe will hold if the authorization + is approved, in the card's [currency](https://stripe.com/docs/api#issuing_authorization_object-pending-request-currency) + and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + type: integer + amount_details: + anyOf: + - "$ref": "#/components/schemas/issuing_authorization_amount_details" + description: Detailed breakdown of amount components. These amounts are + denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + nullable: true + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + is_amount_controllable: + description: If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) + to control how much to hold for the authorization. + type: boolean + merchant_amount: + description: The amount the merchant is requesting to be authorized in the + `merchant_currency`. The amount is in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + type: integer + merchant_currency: + description: The local currency the merchant is requesting to authorize. + type: string + required: + - amount + - currency + - is_amount_controllable + - merchant_amount + - merchant_currency + title: IssuingAuthorizationPendingRequest + type: object + x-expandableFields: + - amount_details + issuing_authorization_request: + description: '' + properties: + amount: + description: The `pending_request.amount` at the time of the request, presented + in your card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + Stripe held this amount from your account to fund the authorization if + the request was approved. + type: integer + amount_details: + anyOf: + - "$ref": "#/components/schemas/issuing_authorization_amount_details" + description: Detailed breakdown of amount components. These amounts are + denominated in `currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + nullable: true + approved: + description: Whether this request was approved. + type: boolean + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + maxLength: 5000 + type: string + merchant_amount: + description: The `pending_request.merchant_amount` at the time of the request, + presented in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + type: integer + merchant_currency: + description: The currency that was collected by the merchant and presented + to the cardholder for the authorization. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + maxLength: 5000 + type: string + reason: + description: The reason for the approval or decline. + enum: + - account_disabled + - card_active + - card_inactive + - cardholder_inactive + - cardholder_verification_required + - insufficient_funds + - not_allowed + - spending_controls + - suspected_fraud + - verification_failed + - webhook_approved + - webhook_declined + - webhook_timeout + type: string + x-stripeBypassValidation: true + required: + - amount + - approved + - created + - currency + - merchant_amount + - merchant_currency + - reason + title: IssuingAuthorizationRequest + type: object + x-expandableFields: + - amount_details + issuing_authorization_verification_data: + description: '' + properties: + address_line1_check: + description: Whether the cardholder provided an address first line and if + it matched the cardholder’s `billing.address.line1`. + enum: + - match + - mismatch + - not_provided + type: string + address_postal_code_check: + description: Whether the cardholder provided a postal code and if it matched + the cardholder’s `billing.address.postal_code`. + enum: + - match + - mismatch + - not_provided + type: string + cvc_check: + description: Whether the cardholder provided a CVC and if it matched Stripe’s + record. + enum: + - match + - mismatch + - not_provided + type: string + expiry_check: + description: Whether the cardholder provided an expiry date and if it matched + Stripe’s record. + enum: + - match + - mismatch + - not_provided + type: string + required: + - address_line1_check + - address_postal_code_check + - cvc_check + - expiry_check + title: IssuingAuthorizationVerificationData + type: object + x-expandableFields: [] + issuing_card_authorization_controls: + description: '' + properties: + allowed_categories: + description: Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) + of authorizations to allow. All other categories will be blocked. Cannot + be set with `blocked_categories`. + items: + enum: + - ac_refrigeration_repair + - accounting_bookkeeping_services + - advertising_services + - agricultural_cooperative + - airlines_air_carriers + - airports_flying_fields + - ambulance_services + - amusement_parks_carnivals + - antique_reproductions + - antique_shops + - aquariums + - architectural_surveying_services + - art_dealers_and_galleries + - artists_supply_and_craft_shops + - auto_and_home_supply_stores + - auto_body_repair_shops + - auto_paint_shops + - auto_service_shops + - automated_cash_disburse + - automated_fuel_dispensers + - automobile_associations + - automotive_parts_and_accessories_stores + - automotive_tire_stores + - bail_and_bond_payments + - bakeries + - bands_orchestras + - barber_and_beauty_shops + - betting_casino_gambling + - bicycle_shops + - billiard_pool_establishments + - boat_dealers + - boat_rentals_and_leases + - book_stores + - books_periodicals_and_newspapers + - bowling_alleys + - bus_lines + - business_secretarial_schools + - buying_shopping_services + - cable_satellite_and_other_pay_television_and_radio + - camera_and_photographic_supply_stores + - candy_nut_and_confectionery_stores + - car_and_truck_dealers_new_used + - car_and_truck_dealers_used_only + - car_rental_agencies + - car_washes + - carpentry_services + - carpet_upholstery_cleaning + - caterers + - charitable_and_social_service_organizations_fundraising + - chemicals_and_allied_products + - child_care_services + - childrens_and_infants_wear_stores + - chiropodists_podiatrists + - chiropractors + - cigar_stores_and_stands + - civic_social_fraternal_associations + - cleaning_and_maintenance + - clothing_rental + - colleges_universities + - commercial_equipment + - commercial_footwear + - commercial_photography_art_and_graphics + - commuter_transport_and_ferries + - computer_network_services + - computer_programming + - computer_repair + - computer_software_stores + - computers_peripherals_and_software + - concrete_work_services + - construction_materials + - consulting_public_relations + - correspondence_schools + - cosmetic_stores + - counseling_services + - country_clubs + - courier_services + - court_costs + - credit_reporting_agencies + - cruise_lines + - dairy_products_stores + - dance_hall_studios_schools + - dating_escort_services + - dentists_orthodontists + - department_stores + - detective_agencies + - digital_goods_applications + - digital_goods_games + - digital_goods_large_volume + - digital_goods_media + - direct_marketing_catalog_merchant + - direct_marketing_combination_catalog_and_retail_merchant + - direct_marketing_inbound_telemarketing + - direct_marketing_insurance_services + - direct_marketing_other + - direct_marketing_outbound_telemarketing + - direct_marketing_subscription + - direct_marketing_travel + - discount_stores + - doctors + - door_to_door_sales + - drapery_window_covering_and_upholstery_stores + - drinking_places + - drug_stores_and_pharmacies + - drugs_drug_proprietaries_and_druggist_sundries + - dry_cleaners + - durable_goods + - duty_free_stores + - eating_places_restaurants + - educational_services + - electric_razor_stores + - electrical_parts_and_equipment + - electrical_services + - electronics_repair_shops + - electronics_stores + - elementary_secondary_schools + - employment_temp_agencies + - equipment_rental + - exterminating_services + - family_clothing_stores + - fast_food_restaurants + - financial_institutions + - fines_government_administrative_entities + - fireplace_fireplace_screens_and_accessories_stores + - floor_covering_stores + - florists + - florists_supplies_nursery_stock_and_flowers + - freezer_and_locker_meat_provisioners + - fuel_dealers_non_automotive + - funeral_services_crematories + - furniture_home_furnishings_and_equipment_stores_except_appliances + - furniture_repair_refinishing + - furriers_and_fur_shops + - general_services + - gift_card_novelty_and_souvenir_shops + - glass_paint_and_wallpaper_stores + - glassware_crystal_stores + - golf_courses_public + - government_services + - grocery_stores_supermarkets + - hardware_equipment_and_supplies + - hardware_stores + - health_and_beauty_spas + - hearing_aids_sales_and_supplies + - heating_plumbing_a_c + - hobby_toy_and_game_shops + - home_supply_warehouse_stores + - hospitals + - hotels_motels_and_resorts + - household_appliance_stores + - industrial_supplies + - information_retrieval_services + - insurance_default + - insurance_underwriting_premiums + - intra_company_purchases + - jewelry_stores_watches_clocks_and_silverware_stores + - landscaping_services + - laundries + - laundry_cleaning_services + - legal_services_attorneys + - luggage_and_leather_goods_stores + - lumber_building_materials_stores + - manual_cash_disburse + - marinas_service_and_supplies + - masonry_stonework_and_plaster + - massage_parlors + - medical_and_dental_labs + - medical_dental_ophthalmic_and_hospital_equipment_and_supplies + - medical_services + - membership_organizations + - mens_and_boys_clothing_and_accessories_stores + - mens_womens_clothing_stores + - metal_service_centers + - miscellaneous + - miscellaneous_apparel_and_accessory_shops + - miscellaneous_auto_dealers + - miscellaneous_business_services + - miscellaneous_food_stores + - miscellaneous_general_merchandise + - miscellaneous_general_services + - miscellaneous_home_furnishing_specialty_stores + - miscellaneous_publishing_and_printing + - miscellaneous_recreation_services + - miscellaneous_repair_shops + - miscellaneous_specialty_retail + - mobile_home_dealers + - motion_picture_theaters + - motor_freight_carriers_and_trucking + - motor_homes_dealers + - motor_vehicle_supplies_and_new_parts + - motorcycle_shops_and_dealers + - motorcycle_shops_dealers + - music_stores_musical_instruments_pianos_and_sheet_music + - news_dealers_and_newsstands + - non_fi_money_orders + - non_fi_stored_value_card_purchase_load + - nondurable_goods + - nurseries_lawn_and_garden_supply_stores + - nursing_personal_care + - office_and_commercial_furniture + - opticians_eyeglasses + - optometrists_ophthalmologist + - orthopedic_goods_prosthetic_devices + - osteopaths + - package_stores_beer_wine_and_liquor + - paints_varnishes_and_supplies + - parking_lots_garages + - passenger_railways + - pawn_shops + - pet_shops_pet_food_and_supplies + - petroleum_and_petroleum_products + - photo_developing + - photographic_photocopy_microfilm_equipment_and_supplies + - photographic_studios + - picture_video_production + - piece_goods_notions_and_other_dry_goods + - plumbing_heating_equipment_and_supplies + - political_organizations + - postal_services_government_only + - precious_stones_and_metals_watches_and_jewelry + - professional_services + - public_warehousing_and_storage + - quick_copy_repro_and_blueprint + - railroads + - real_estate_agents_and_managers_rentals + - record_stores + - recreational_vehicle_rentals + - religious_goods_stores + - religious_organizations + - roofing_siding_sheet_metal + - secretarial_support_services + - security_brokers_dealers + - service_stations + - sewing_needlework_fabric_and_piece_goods_stores + - shoe_repair_hat_cleaning + - shoe_stores + - small_appliance_repair + - snowmobile_dealers + - special_trade_services + - specialty_cleaning + - sporting_goods_stores + - sporting_recreation_camps + - sports_and_riding_apparel_stores + - sports_clubs_fields + - stamp_and_coin_stores + - stationary_office_supplies_printing_and_writing_paper + - stationery_stores_office_and_school_supply_stores + - swimming_pools_sales + - t_ui_travel_germany + - tailors_alterations + - tax_payments_government_agencies + - tax_preparation_services + - taxicabs_limousines + - telecommunication_equipment_and_telephone_sales + - telecommunication_services + - telegraph_services + - tent_and_awning_shops + - testing_laboratories + - theatrical_ticket_agencies + - timeshares + - tire_retreading_and_repair + - tolls_bridge_fees + - tourist_attractions_and_exhibits + - towing_services + - trailer_parks_campgrounds + - transportation_services + - travel_agencies_tour_operators + - truck_stop_iteration + - truck_utility_trailer_rentals + - typesetting_plate_making_and_related_services + - typewriter_stores + - u_s_federal_government_agencies_or_departments + - uniforms_commercial_clothing + - used_merchandise_and_secondhand_stores + - utilities + - variety_stores + - veterinary_services + - video_amusement_game_supplies + - video_game_arcades + - video_tape_rental_stores + - vocational_trade_schools + - watch_jewelry_repair + - welding_repair + - wholesale_clubs + - wig_and_toupee_stores + - wires_money_orders + - womens_accessory_and_specialty_shops + - womens_ready_to_wear_stores + - wrecking_and_salvage_yards + type: string + nullable: true + type: array + blocked_categories: + description: Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) + of authorizations to decline. All other categories will be allowed. Cannot + be set with `allowed_categories`. + items: + enum: + - ac_refrigeration_repair + - accounting_bookkeeping_services + - advertising_services + - agricultural_cooperative + - airlines_air_carriers + - airports_flying_fields + - ambulance_services + - amusement_parks_carnivals + - antique_reproductions + - antique_shops + - aquariums + - architectural_surveying_services + - art_dealers_and_galleries + - artists_supply_and_craft_shops + - auto_and_home_supply_stores + - auto_body_repair_shops + - auto_paint_shops + - auto_service_shops + - automated_cash_disburse + - automated_fuel_dispensers + - automobile_associations + - automotive_parts_and_accessories_stores + - automotive_tire_stores + - bail_and_bond_payments + - bakeries + - bands_orchestras + - barber_and_beauty_shops + - betting_casino_gambling + - bicycle_shops + - billiard_pool_establishments + - boat_dealers + - boat_rentals_and_leases + - book_stores + - books_periodicals_and_newspapers + - bowling_alleys + - bus_lines + - business_secretarial_schools + - buying_shopping_services + - cable_satellite_and_other_pay_television_and_radio + - camera_and_photographic_supply_stores + - candy_nut_and_confectionery_stores + - car_and_truck_dealers_new_used + - car_and_truck_dealers_used_only + - car_rental_agencies + - car_washes + - carpentry_services + - carpet_upholstery_cleaning + - caterers + - charitable_and_social_service_organizations_fundraising + - chemicals_and_allied_products + - child_care_services + - childrens_and_infants_wear_stores + - chiropodists_podiatrists + - chiropractors + - cigar_stores_and_stands + - civic_social_fraternal_associations + - cleaning_and_maintenance + - clothing_rental + - colleges_universities + - commercial_equipment + - commercial_footwear + - commercial_photography_art_and_graphics + - commuter_transport_and_ferries + - computer_network_services + - computer_programming + - computer_repair + - computer_software_stores + - computers_peripherals_and_software + - concrete_work_services + - construction_materials + - consulting_public_relations + - correspondence_schools + - cosmetic_stores + - counseling_services + - country_clubs + - courier_services + - court_costs + - credit_reporting_agencies + - cruise_lines + - dairy_products_stores + - dance_hall_studios_schools + - dating_escort_services + - dentists_orthodontists + - department_stores + - detective_agencies + - digital_goods_applications + - digital_goods_games + - digital_goods_large_volume + - digital_goods_media + - direct_marketing_catalog_merchant + - direct_marketing_combination_catalog_and_retail_merchant + - direct_marketing_inbound_telemarketing + - direct_marketing_insurance_services + - direct_marketing_other + - direct_marketing_outbound_telemarketing + - direct_marketing_subscription + - direct_marketing_travel + - discount_stores + - doctors + - door_to_door_sales + - drapery_window_covering_and_upholstery_stores + - drinking_places + - drug_stores_and_pharmacies + - drugs_drug_proprietaries_and_druggist_sundries + - dry_cleaners + - durable_goods + - duty_free_stores + - eating_places_restaurants + - educational_services + - electric_razor_stores + - electrical_parts_and_equipment + - electrical_services + - electronics_repair_shops + - electronics_stores + - elementary_secondary_schools + - employment_temp_agencies + - equipment_rental + - exterminating_services + - family_clothing_stores + - fast_food_restaurants + - financial_institutions + - fines_government_administrative_entities + - fireplace_fireplace_screens_and_accessories_stores + - floor_covering_stores + - florists + - florists_supplies_nursery_stock_and_flowers + - freezer_and_locker_meat_provisioners + - fuel_dealers_non_automotive + - funeral_services_crematories + - furniture_home_furnishings_and_equipment_stores_except_appliances + - furniture_repair_refinishing + - furriers_and_fur_shops + - general_services + - gift_card_novelty_and_souvenir_shops + - glass_paint_and_wallpaper_stores + - glassware_crystal_stores + - golf_courses_public + - government_services + - grocery_stores_supermarkets + - hardware_equipment_and_supplies + - hardware_stores + - health_and_beauty_spas + - hearing_aids_sales_and_supplies + - heating_plumbing_a_c + - hobby_toy_and_game_shops + - home_supply_warehouse_stores + - hospitals + - hotels_motels_and_resorts + - household_appliance_stores + - industrial_supplies + - information_retrieval_services + - insurance_default + - insurance_underwriting_premiums + - intra_company_purchases + - jewelry_stores_watches_clocks_and_silverware_stores + - landscaping_services + - laundries + - laundry_cleaning_services + - legal_services_attorneys + - luggage_and_leather_goods_stores + - lumber_building_materials_stores + - manual_cash_disburse + - marinas_service_and_supplies + - masonry_stonework_and_plaster + - massage_parlors + - medical_and_dental_labs + - medical_dental_ophthalmic_and_hospital_equipment_and_supplies + - medical_services + - membership_organizations + - mens_and_boys_clothing_and_accessories_stores + - mens_womens_clothing_stores + - metal_service_centers + - miscellaneous + - miscellaneous_apparel_and_accessory_shops + - miscellaneous_auto_dealers + - miscellaneous_business_services + - miscellaneous_food_stores + - miscellaneous_general_merchandise + - miscellaneous_general_services + - miscellaneous_home_furnishing_specialty_stores + - miscellaneous_publishing_and_printing + - miscellaneous_recreation_services + - miscellaneous_repair_shops + - miscellaneous_specialty_retail + - mobile_home_dealers + - motion_picture_theaters + - motor_freight_carriers_and_trucking + - motor_homes_dealers + - motor_vehicle_supplies_and_new_parts + - motorcycle_shops_and_dealers + - motorcycle_shops_dealers + - music_stores_musical_instruments_pianos_and_sheet_music + - news_dealers_and_newsstands + - non_fi_money_orders + - non_fi_stored_value_card_purchase_load + - nondurable_goods + - nurseries_lawn_and_garden_supply_stores + - nursing_personal_care + - office_and_commercial_furniture + - opticians_eyeglasses + - optometrists_ophthalmologist + - orthopedic_goods_prosthetic_devices + - osteopaths + - package_stores_beer_wine_and_liquor + - paints_varnishes_and_supplies + - parking_lots_garages + - passenger_railways + - pawn_shops + - pet_shops_pet_food_and_supplies + - petroleum_and_petroleum_products + - photo_developing + - photographic_photocopy_microfilm_equipment_and_supplies + - photographic_studios + - picture_video_production + - piece_goods_notions_and_other_dry_goods + - plumbing_heating_equipment_and_supplies + - political_organizations + - postal_services_government_only + - precious_stones_and_metals_watches_and_jewelry + - professional_services + - public_warehousing_and_storage + - quick_copy_repro_and_blueprint + - railroads + - real_estate_agents_and_managers_rentals + - record_stores + - recreational_vehicle_rentals + - religious_goods_stores + - religious_organizations + - roofing_siding_sheet_metal + - secretarial_support_services + - security_brokers_dealers + - service_stations + - sewing_needlework_fabric_and_piece_goods_stores + - shoe_repair_hat_cleaning + - shoe_stores + - small_appliance_repair + - snowmobile_dealers + - special_trade_services + - specialty_cleaning + - sporting_goods_stores + - sporting_recreation_camps + - sports_and_riding_apparel_stores + - sports_clubs_fields + - stamp_and_coin_stores + - stationary_office_supplies_printing_and_writing_paper + - stationery_stores_office_and_school_supply_stores + - swimming_pools_sales + - t_ui_travel_germany + - tailors_alterations + - tax_payments_government_agencies + - tax_preparation_services + - taxicabs_limousines + - telecommunication_equipment_and_telephone_sales + - telecommunication_services + - telegraph_services + - tent_and_awning_shops + - testing_laboratories + - theatrical_ticket_agencies + - timeshares + - tire_retreading_and_repair + - tolls_bridge_fees + - tourist_attractions_and_exhibits + - towing_services + - trailer_parks_campgrounds + - transportation_services + - travel_agencies_tour_operators + - truck_stop_iteration + - truck_utility_trailer_rentals + - typesetting_plate_making_and_related_services + - typewriter_stores + - u_s_federal_government_agencies_or_departments + - uniforms_commercial_clothing + - used_merchandise_and_secondhand_stores + - utilities + - variety_stores + - veterinary_services + - video_amusement_game_supplies + - video_game_arcades + - video_tape_rental_stores + - vocational_trade_schools + - watch_jewelry_repair + - welding_repair + - wholesale_clubs + - wig_and_toupee_stores + - wires_money_orders + - womens_accessory_and_specialty_shops + - womens_ready_to_wear_stores + - wrecking_and_salvage_yards + type: string + nullable: true + type: array + spending_limits: + description: Limit spending with amount-based rules that apply across any + cards this card replaced (i.e., its `replacement_for` card and _that_ + card's `replacement_for` card, up the chain). + items: + "$ref": "#/components/schemas/issuing_card_spending_limit" + nullable: true + type: array + spending_limits_currency: + description: Currency of the amounts within `spending_limits`. Always the + same as the currency of the card. + nullable: true + type: string + title: IssuingCardAuthorizationControls + type: object + x-expandableFields: + - spending_limits + issuing_card_shipping: + description: '' + properties: + address: + "$ref": "#/components/schemas/address" + carrier: + description: The delivery company that shipped a card. + enum: + - dhl + - fedex + - royal_mail + - usps + nullable: true + type: string + eta: + description: A unix timestamp representing a best estimate of when the card + will be delivered. + format: unix-time + nullable: true + type: integer + name: + description: Recipient name. + maxLength: 5000 + type: string + service: + description: Shipment service, such as `standard` or `express`. + enum: + - express + - priority + - standard + type: string + x-stripeBypassValidation: true + status: + description: The delivery status of the card. + enum: + - canceled + - delivered + - failure + - pending + - returned + - shipped + nullable: true + type: string + tracking_number: + description: A tracking number for a card shipment. + maxLength: 5000 + nullable: true + type: string + tracking_url: + description: A link to the shipping carrier's site where you can view detailed + information about a card shipment. + maxLength: 5000 + nullable: true + type: string + type: + description: Packaging options. + enum: + - bulk + - individual + type: string + required: + - address + - name + - service + - type + title: IssuingCardShipping + type: object + x-expandableFields: + - address + issuing_card_spending_limit: + description: '' + properties: + amount: + description: Maximum amount allowed to spend per interval. + type: integer + categories: + description: Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) + this limit applies to. Omitting this field will apply the limit to all + categories. + items: + enum: + - ac_refrigeration_repair + - accounting_bookkeeping_services + - advertising_services + - agricultural_cooperative + - airlines_air_carriers + - airports_flying_fields + - ambulance_services + - amusement_parks_carnivals + - antique_reproductions + - antique_shops + - aquariums + - architectural_surveying_services + - art_dealers_and_galleries + - artists_supply_and_craft_shops + - auto_and_home_supply_stores + - auto_body_repair_shops + - auto_paint_shops + - auto_service_shops + - automated_cash_disburse + - automated_fuel_dispensers + - automobile_associations + - automotive_parts_and_accessories_stores + - automotive_tire_stores + - bail_and_bond_payments + - bakeries + - bands_orchestras + - barber_and_beauty_shops + - betting_casino_gambling + - bicycle_shops + - billiard_pool_establishments + - boat_dealers + - boat_rentals_and_leases + - book_stores + - books_periodicals_and_newspapers + - bowling_alleys + - bus_lines + - business_secretarial_schools + - buying_shopping_services + - cable_satellite_and_other_pay_television_and_radio + - camera_and_photographic_supply_stores + - candy_nut_and_confectionery_stores + - car_and_truck_dealers_new_used + - car_and_truck_dealers_used_only + - car_rental_agencies + - car_washes + - carpentry_services + - carpet_upholstery_cleaning + - caterers + - charitable_and_social_service_organizations_fundraising + - chemicals_and_allied_products + - child_care_services + - childrens_and_infants_wear_stores + - chiropodists_podiatrists + - chiropractors + - cigar_stores_and_stands + - civic_social_fraternal_associations + - cleaning_and_maintenance + - clothing_rental + - colleges_universities + - commercial_equipment + - commercial_footwear + - commercial_photography_art_and_graphics + - commuter_transport_and_ferries + - computer_network_services + - computer_programming + - computer_repair + - computer_software_stores + - computers_peripherals_and_software + - concrete_work_services + - construction_materials + - consulting_public_relations + - correspondence_schools + - cosmetic_stores + - counseling_services + - country_clubs + - courier_services + - court_costs + - credit_reporting_agencies + - cruise_lines + - dairy_products_stores + - dance_hall_studios_schools + - dating_escort_services + - dentists_orthodontists + - department_stores + - detective_agencies + - digital_goods_applications + - digital_goods_games + - digital_goods_large_volume + - digital_goods_media + - direct_marketing_catalog_merchant + - direct_marketing_combination_catalog_and_retail_merchant + - direct_marketing_inbound_telemarketing + - direct_marketing_insurance_services + - direct_marketing_other + - direct_marketing_outbound_telemarketing + - direct_marketing_subscription + - direct_marketing_travel + - discount_stores + - doctors + - door_to_door_sales + - drapery_window_covering_and_upholstery_stores + - drinking_places + - drug_stores_and_pharmacies + - drugs_drug_proprietaries_and_druggist_sundries + - dry_cleaners + - durable_goods + - duty_free_stores + - eating_places_restaurants + - educational_services + - electric_razor_stores + - electrical_parts_and_equipment + - electrical_services + - electronics_repair_shops + - electronics_stores + - elementary_secondary_schools + - employment_temp_agencies + - equipment_rental + - exterminating_services + - family_clothing_stores + - fast_food_restaurants + - financial_institutions + - fines_government_administrative_entities + - fireplace_fireplace_screens_and_accessories_stores + - floor_covering_stores + - florists + - florists_supplies_nursery_stock_and_flowers + - freezer_and_locker_meat_provisioners + - fuel_dealers_non_automotive + - funeral_services_crematories + - furniture_home_furnishings_and_equipment_stores_except_appliances + - furniture_repair_refinishing + - furriers_and_fur_shops + - general_services + - gift_card_novelty_and_souvenir_shops + - glass_paint_and_wallpaper_stores + - glassware_crystal_stores + - golf_courses_public + - government_services + - grocery_stores_supermarkets + - hardware_equipment_and_supplies + - hardware_stores + - health_and_beauty_spas + - hearing_aids_sales_and_supplies + - heating_plumbing_a_c + - hobby_toy_and_game_shops + - home_supply_warehouse_stores + - hospitals + - hotels_motels_and_resorts + - household_appliance_stores + - industrial_supplies + - information_retrieval_services + - insurance_default + - insurance_underwriting_premiums + - intra_company_purchases + - jewelry_stores_watches_clocks_and_silverware_stores + - landscaping_services + - laundries + - laundry_cleaning_services + - legal_services_attorneys + - luggage_and_leather_goods_stores + - lumber_building_materials_stores + - manual_cash_disburse + - marinas_service_and_supplies + - masonry_stonework_and_plaster + - massage_parlors + - medical_and_dental_labs + - medical_dental_ophthalmic_and_hospital_equipment_and_supplies + - medical_services + - membership_organizations + - mens_and_boys_clothing_and_accessories_stores + - mens_womens_clothing_stores + - metal_service_centers + - miscellaneous + - miscellaneous_apparel_and_accessory_shops + - miscellaneous_auto_dealers + - miscellaneous_business_services + - miscellaneous_food_stores + - miscellaneous_general_merchandise + - miscellaneous_general_services + - miscellaneous_home_furnishing_specialty_stores + - miscellaneous_publishing_and_printing + - miscellaneous_recreation_services + - miscellaneous_repair_shops + - miscellaneous_specialty_retail + - mobile_home_dealers + - motion_picture_theaters + - motor_freight_carriers_and_trucking + - motor_homes_dealers + - motor_vehicle_supplies_and_new_parts + - motorcycle_shops_and_dealers + - motorcycle_shops_dealers + - music_stores_musical_instruments_pianos_and_sheet_music + - news_dealers_and_newsstands + - non_fi_money_orders + - non_fi_stored_value_card_purchase_load + - nondurable_goods + - nurseries_lawn_and_garden_supply_stores + - nursing_personal_care + - office_and_commercial_furniture + - opticians_eyeglasses + - optometrists_ophthalmologist + - orthopedic_goods_prosthetic_devices + - osteopaths + - package_stores_beer_wine_and_liquor + - paints_varnishes_and_supplies + - parking_lots_garages + - passenger_railways + - pawn_shops + - pet_shops_pet_food_and_supplies + - petroleum_and_petroleum_products + - photo_developing + - photographic_photocopy_microfilm_equipment_and_supplies + - photographic_studios + - picture_video_production + - piece_goods_notions_and_other_dry_goods + - plumbing_heating_equipment_and_supplies + - political_organizations + - postal_services_government_only + - precious_stones_and_metals_watches_and_jewelry + - professional_services + - public_warehousing_and_storage + - quick_copy_repro_and_blueprint + - railroads + - real_estate_agents_and_managers_rentals + - record_stores + - recreational_vehicle_rentals + - religious_goods_stores + - religious_organizations + - roofing_siding_sheet_metal + - secretarial_support_services + - security_brokers_dealers + - service_stations + - sewing_needlework_fabric_and_piece_goods_stores + - shoe_repair_hat_cleaning + - shoe_stores + - small_appliance_repair + - snowmobile_dealers + - special_trade_services + - specialty_cleaning + - sporting_goods_stores + - sporting_recreation_camps + - sports_and_riding_apparel_stores + - sports_clubs_fields + - stamp_and_coin_stores + - stationary_office_supplies_printing_and_writing_paper + - stationery_stores_office_and_school_supply_stores + - swimming_pools_sales + - t_ui_travel_germany + - tailors_alterations + - tax_payments_government_agencies + - tax_preparation_services + - taxicabs_limousines + - telecommunication_equipment_and_telephone_sales + - telecommunication_services + - telegraph_services + - tent_and_awning_shops + - testing_laboratories + - theatrical_ticket_agencies + - timeshares + - tire_retreading_and_repair + - tolls_bridge_fees + - tourist_attractions_and_exhibits + - towing_services + - trailer_parks_campgrounds + - transportation_services + - travel_agencies_tour_operators + - truck_stop_iteration + - truck_utility_trailer_rentals + - typesetting_plate_making_and_related_services + - typewriter_stores + - u_s_federal_government_agencies_or_departments + - uniforms_commercial_clothing + - used_merchandise_and_secondhand_stores + - utilities + - variety_stores + - veterinary_services + - video_amusement_game_supplies + - video_game_arcades + - video_tape_rental_stores + - vocational_trade_schools + - watch_jewelry_repair + - welding_repair + - wholesale_clubs + - wig_and_toupee_stores + - wires_money_orders + - womens_accessory_and_specialty_shops + - womens_ready_to_wear_stores + - wrecking_and_salvage_yards + type: string + nullable: true + type: array + interval: + description: Interval (or event) to which the amount applies. + enum: + - all_time + - daily + - monthly + - per_authorization + - weekly + - yearly + type: string + required: + - amount + - interval + title: IssuingCardSpendingLimit + type: object + x-expandableFields: [] + issuing_cardholder_address: + description: 'The cardholder’s billing information' + properties: + address: + "$ref": "#/components/schemas/address" + required: + - address + title: IssuingCardholderAddress + type: object + x-expandableFields: + - address + issuing_cardholder_authorization_controls: + description: '' + properties: + allowed_categories: + description: Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) + of authorizations to allow. All other categories will be blocked. Cannot + be set with `blocked_categories`. + items: + enum: + - ac_refrigeration_repair + - accounting_bookkeeping_services + - advertising_services + - agricultural_cooperative + - airlines_air_carriers + - airports_flying_fields + - ambulance_services + - amusement_parks_carnivals + - antique_reproductions + - antique_shops + - aquariums + - architectural_surveying_services + - art_dealers_and_galleries + - artists_supply_and_craft_shops + - auto_and_home_supply_stores + - auto_body_repair_shops + - auto_paint_shops + - auto_service_shops + - automated_cash_disburse + - automated_fuel_dispensers + - automobile_associations + - automotive_parts_and_accessories_stores + - automotive_tire_stores + - bail_and_bond_payments + - bakeries + - bands_orchestras + - barber_and_beauty_shops + - betting_casino_gambling + - bicycle_shops + - billiard_pool_establishments + - boat_dealers + - boat_rentals_and_leases + - book_stores + - books_periodicals_and_newspapers + - bowling_alleys + - bus_lines + - business_secretarial_schools + - buying_shopping_services + - cable_satellite_and_other_pay_television_and_radio + - camera_and_photographic_supply_stores + - candy_nut_and_confectionery_stores + - car_and_truck_dealers_new_used + - car_and_truck_dealers_used_only + - car_rental_agencies + - car_washes + - carpentry_services + - carpet_upholstery_cleaning + - caterers + - charitable_and_social_service_organizations_fundraising + - chemicals_and_allied_products + - child_care_services + - childrens_and_infants_wear_stores + - chiropodists_podiatrists + - chiropractors + - cigar_stores_and_stands + - civic_social_fraternal_associations + - cleaning_and_maintenance + - clothing_rental + - colleges_universities + - commercial_equipment + - commercial_footwear + - commercial_photography_art_and_graphics + - commuter_transport_and_ferries + - computer_network_services + - computer_programming + - computer_repair + - computer_software_stores + - computers_peripherals_and_software + - concrete_work_services + - construction_materials + - consulting_public_relations + - correspondence_schools + - cosmetic_stores + - counseling_services + - country_clubs + - courier_services + - court_costs + - credit_reporting_agencies + - cruise_lines + - dairy_products_stores + - dance_hall_studios_schools + - dating_escort_services + - dentists_orthodontists + - department_stores + - detective_agencies + - digital_goods_applications + - digital_goods_games + - digital_goods_large_volume + - digital_goods_media + - direct_marketing_catalog_merchant + - direct_marketing_combination_catalog_and_retail_merchant + - direct_marketing_inbound_telemarketing + - direct_marketing_insurance_services + - direct_marketing_other + - direct_marketing_outbound_telemarketing + - direct_marketing_subscription + - direct_marketing_travel + - discount_stores + - doctors + - door_to_door_sales + - drapery_window_covering_and_upholstery_stores + - drinking_places + - drug_stores_and_pharmacies + - drugs_drug_proprietaries_and_druggist_sundries + - dry_cleaners + - durable_goods + - duty_free_stores + - eating_places_restaurants + - educational_services + - electric_razor_stores + - electrical_parts_and_equipment + - electrical_services + - electronics_repair_shops + - electronics_stores + - elementary_secondary_schools + - employment_temp_agencies + - equipment_rental + - exterminating_services + - family_clothing_stores + - fast_food_restaurants + - financial_institutions + - fines_government_administrative_entities + - fireplace_fireplace_screens_and_accessories_stores + - floor_covering_stores + - florists + - florists_supplies_nursery_stock_and_flowers + - freezer_and_locker_meat_provisioners + - fuel_dealers_non_automotive + - funeral_services_crematories + - furniture_home_furnishings_and_equipment_stores_except_appliances + - furniture_repair_refinishing + - furriers_and_fur_shops + - general_services + - gift_card_novelty_and_souvenir_shops + - glass_paint_and_wallpaper_stores + - glassware_crystal_stores + - golf_courses_public + - government_services + - grocery_stores_supermarkets + - hardware_equipment_and_supplies + - hardware_stores + - health_and_beauty_spas + - hearing_aids_sales_and_supplies + - heating_plumbing_a_c + - hobby_toy_and_game_shops + - home_supply_warehouse_stores + - hospitals + - hotels_motels_and_resorts + - household_appliance_stores + - industrial_supplies + - information_retrieval_services + - insurance_default + - insurance_underwriting_premiums + - intra_company_purchases + - jewelry_stores_watches_clocks_and_silverware_stores + - landscaping_services + - laundries + - laundry_cleaning_services + - legal_services_attorneys + - luggage_and_leather_goods_stores + - lumber_building_materials_stores + - manual_cash_disburse + - marinas_service_and_supplies + - masonry_stonework_and_plaster + - massage_parlors + - medical_and_dental_labs + - medical_dental_ophthalmic_and_hospital_equipment_and_supplies + - medical_services + - membership_organizations + - mens_and_boys_clothing_and_accessories_stores + - mens_womens_clothing_stores + - metal_service_centers + - miscellaneous + - miscellaneous_apparel_and_accessory_shops + - miscellaneous_auto_dealers + - miscellaneous_business_services + - miscellaneous_food_stores + - miscellaneous_general_merchandise + - miscellaneous_general_services + - miscellaneous_home_furnishing_specialty_stores + - miscellaneous_publishing_and_printing + - miscellaneous_recreation_services + - miscellaneous_repair_shops + - miscellaneous_specialty_retail + - mobile_home_dealers + - motion_picture_theaters + - motor_freight_carriers_and_trucking + - motor_homes_dealers + - motor_vehicle_supplies_and_new_parts + - motorcycle_shops_and_dealers + - motorcycle_shops_dealers + - music_stores_musical_instruments_pianos_and_sheet_music + - news_dealers_and_newsstands + - non_fi_money_orders + - non_fi_stored_value_card_purchase_load + - nondurable_goods + - nurseries_lawn_and_garden_supply_stores + - nursing_personal_care + - office_and_commercial_furniture + - opticians_eyeglasses + - optometrists_ophthalmologist + - orthopedic_goods_prosthetic_devices + - osteopaths + - package_stores_beer_wine_and_liquor + - paints_varnishes_and_supplies + - parking_lots_garages + - passenger_railways + - pawn_shops + - pet_shops_pet_food_and_supplies + - petroleum_and_petroleum_products + - photo_developing + - photographic_photocopy_microfilm_equipment_and_supplies + - photographic_studios + - picture_video_production + - piece_goods_notions_and_other_dry_goods + - plumbing_heating_equipment_and_supplies + - political_organizations + - postal_services_government_only + - precious_stones_and_metals_watches_and_jewelry + - professional_services + - public_warehousing_and_storage + - quick_copy_repro_and_blueprint + - railroads + - real_estate_agents_and_managers_rentals + - record_stores + - recreational_vehicle_rentals + - religious_goods_stores + - religious_organizations + - roofing_siding_sheet_metal + - secretarial_support_services + - security_brokers_dealers + - service_stations + - sewing_needlework_fabric_and_piece_goods_stores + - shoe_repair_hat_cleaning + - shoe_stores + - small_appliance_repair + - snowmobile_dealers + - special_trade_services + - specialty_cleaning + - sporting_goods_stores + - sporting_recreation_camps + - sports_and_riding_apparel_stores + - sports_clubs_fields + - stamp_and_coin_stores + - stationary_office_supplies_printing_and_writing_paper + - stationery_stores_office_and_school_supply_stores + - swimming_pools_sales + - t_ui_travel_germany + - tailors_alterations + - tax_payments_government_agencies + - tax_preparation_services + - taxicabs_limousines + - telecommunication_equipment_and_telephone_sales + - telecommunication_services + - telegraph_services + - tent_and_awning_shops + - testing_laboratories + - theatrical_ticket_agencies + - timeshares + - tire_retreading_and_repair + - tolls_bridge_fees + - tourist_attractions_and_exhibits + - towing_services + - trailer_parks_campgrounds + - transportation_services + - travel_agencies_tour_operators + - truck_stop_iteration + - truck_utility_trailer_rentals + - typesetting_plate_making_and_related_services + - typewriter_stores + - u_s_federal_government_agencies_or_departments + - uniforms_commercial_clothing + - used_merchandise_and_secondhand_stores + - utilities + - variety_stores + - veterinary_services + - video_amusement_game_supplies + - video_game_arcades + - video_tape_rental_stores + - vocational_trade_schools + - watch_jewelry_repair + - welding_repair + - wholesale_clubs + - wig_and_toupee_stores + - wires_money_orders + - womens_accessory_and_specialty_shops + - womens_ready_to_wear_stores + - wrecking_and_salvage_yards + type: string + nullable: true + type: array + blocked_categories: + description: Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) + of authorizations to decline. All other categories will be allowed. Cannot + be set with `allowed_categories`. + items: + enum: + - ac_refrigeration_repair + - accounting_bookkeeping_services + - advertising_services + - agricultural_cooperative + - airlines_air_carriers + - airports_flying_fields + - ambulance_services + - amusement_parks_carnivals + - antique_reproductions + - antique_shops + - aquariums + - architectural_surveying_services + - art_dealers_and_galleries + - artists_supply_and_craft_shops + - auto_and_home_supply_stores + - auto_body_repair_shops + - auto_paint_shops + - auto_service_shops + - automated_cash_disburse + - automated_fuel_dispensers + - automobile_associations + - automotive_parts_and_accessories_stores + - automotive_tire_stores + - bail_and_bond_payments + - bakeries + - bands_orchestras + - barber_and_beauty_shops + - betting_casino_gambling + - bicycle_shops + - billiard_pool_establishments + - boat_dealers + - boat_rentals_and_leases + - book_stores + - books_periodicals_and_newspapers + - bowling_alleys + - bus_lines + - business_secretarial_schools + - buying_shopping_services + - cable_satellite_and_other_pay_television_and_radio + - camera_and_photographic_supply_stores + - candy_nut_and_confectionery_stores + - car_and_truck_dealers_new_used + - car_and_truck_dealers_used_only + - car_rental_agencies + - car_washes + - carpentry_services + - carpet_upholstery_cleaning + - caterers + - charitable_and_social_service_organizations_fundraising + - chemicals_and_allied_products + - child_care_services + - childrens_and_infants_wear_stores + - chiropodists_podiatrists + - chiropractors + - cigar_stores_and_stands + - civic_social_fraternal_associations + - cleaning_and_maintenance + - clothing_rental + - colleges_universities + - commercial_equipment + - commercial_footwear + - commercial_photography_art_and_graphics + - commuter_transport_and_ferries + - computer_network_services + - computer_programming + - computer_repair + - computer_software_stores + - computers_peripherals_and_software + - concrete_work_services + - construction_materials + - consulting_public_relations + - correspondence_schools + - cosmetic_stores + - counseling_services + - country_clubs + - courier_services + - court_costs + - credit_reporting_agencies + - cruise_lines + - dairy_products_stores + - dance_hall_studios_schools + - dating_escort_services + - dentists_orthodontists + - department_stores + - detective_agencies + - digital_goods_applications + - digital_goods_games + - digital_goods_large_volume + - digital_goods_media + - direct_marketing_catalog_merchant + - direct_marketing_combination_catalog_and_retail_merchant + - direct_marketing_inbound_telemarketing + - direct_marketing_insurance_services + - direct_marketing_other + - direct_marketing_outbound_telemarketing + - direct_marketing_subscription + - direct_marketing_travel + - discount_stores + - doctors + - door_to_door_sales + - drapery_window_covering_and_upholstery_stores + - drinking_places + - drug_stores_and_pharmacies + - drugs_drug_proprietaries_and_druggist_sundries + - dry_cleaners + - durable_goods + - duty_free_stores + - eating_places_restaurants + - educational_services + - electric_razor_stores + - electrical_parts_and_equipment + - electrical_services + - electronics_repair_shops + - electronics_stores + - elementary_secondary_schools + - employment_temp_agencies + - equipment_rental + - exterminating_services + - family_clothing_stores + - fast_food_restaurants + - financial_institutions + - fines_government_administrative_entities + - fireplace_fireplace_screens_and_accessories_stores + - floor_covering_stores + - florists + - florists_supplies_nursery_stock_and_flowers + - freezer_and_locker_meat_provisioners + - fuel_dealers_non_automotive + - funeral_services_crematories + - furniture_home_furnishings_and_equipment_stores_except_appliances + - furniture_repair_refinishing + - furriers_and_fur_shops + - general_services + - gift_card_novelty_and_souvenir_shops + - glass_paint_and_wallpaper_stores + - glassware_crystal_stores + - golf_courses_public + - government_services + - grocery_stores_supermarkets + - hardware_equipment_and_supplies + - hardware_stores + - health_and_beauty_spas + - hearing_aids_sales_and_supplies + - heating_plumbing_a_c + - hobby_toy_and_game_shops + - home_supply_warehouse_stores + - hospitals + - hotels_motels_and_resorts + - household_appliance_stores + - industrial_supplies + - information_retrieval_services + - insurance_default + - insurance_underwriting_premiums + - intra_company_purchases + - jewelry_stores_watches_clocks_and_silverware_stores + - landscaping_services + - laundries + - laundry_cleaning_services + - legal_services_attorneys + - luggage_and_leather_goods_stores + - lumber_building_materials_stores + - manual_cash_disburse + - marinas_service_and_supplies + - masonry_stonework_and_plaster + - massage_parlors + - medical_and_dental_labs + - medical_dental_ophthalmic_and_hospital_equipment_and_supplies + - medical_services + - membership_organizations + - mens_and_boys_clothing_and_accessories_stores + - mens_womens_clothing_stores + - metal_service_centers + - miscellaneous + - miscellaneous_apparel_and_accessory_shops + - miscellaneous_auto_dealers + - miscellaneous_business_services + - miscellaneous_food_stores + - miscellaneous_general_merchandise + - miscellaneous_general_services + - miscellaneous_home_furnishing_specialty_stores + - miscellaneous_publishing_and_printing + - miscellaneous_recreation_services + - miscellaneous_repair_shops + - miscellaneous_specialty_retail + - mobile_home_dealers + - motion_picture_theaters + - motor_freight_carriers_and_trucking + - motor_homes_dealers + - motor_vehicle_supplies_and_new_parts + - motorcycle_shops_and_dealers + - motorcycle_shops_dealers + - music_stores_musical_instruments_pianos_and_sheet_music + - news_dealers_and_newsstands + - non_fi_money_orders + - non_fi_stored_value_card_purchase_load + - nondurable_goods + - nurseries_lawn_and_garden_supply_stores + - nursing_personal_care + - office_and_commercial_furniture + - opticians_eyeglasses + - optometrists_ophthalmologist + - orthopedic_goods_prosthetic_devices + - osteopaths + - package_stores_beer_wine_and_liquor + - paints_varnishes_and_supplies + - parking_lots_garages + - passenger_railways + - pawn_shops + - pet_shops_pet_food_and_supplies + - petroleum_and_petroleum_products + - photo_developing + - photographic_photocopy_microfilm_equipment_and_supplies + - photographic_studios + - picture_video_production + - piece_goods_notions_and_other_dry_goods + - plumbing_heating_equipment_and_supplies + - political_organizations + - postal_services_government_only + - precious_stones_and_metals_watches_and_jewelry + - professional_services + - public_warehousing_and_storage + - quick_copy_repro_and_blueprint + - railroads + - real_estate_agents_and_managers_rentals + - record_stores + - recreational_vehicle_rentals + - religious_goods_stores + - religious_organizations + - roofing_siding_sheet_metal + - secretarial_support_services + - security_brokers_dealers + - service_stations + - sewing_needlework_fabric_and_piece_goods_stores + - shoe_repair_hat_cleaning + - shoe_stores + - small_appliance_repair + - snowmobile_dealers + - special_trade_services + - specialty_cleaning + - sporting_goods_stores + - sporting_recreation_camps + - sports_and_riding_apparel_stores + - sports_clubs_fields + - stamp_and_coin_stores + - stationary_office_supplies_printing_and_writing_paper + - stationery_stores_office_and_school_supply_stores + - swimming_pools_sales + - t_ui_travel_germany + - tailors_alterations + - tax_payments_government_agencies + - tax_preparation_services + - taxicabs_limousines + - telecommunication_equipment_and_telephone_sales + - telecommunication_services + - telegraph_services + - tent_and_awning_shops + - testing_laboratories + - theatrical_ticket_agencies + - timeshares + - tire_retreading_and_repair + - tolls_bridge_fees + - tourist_attractions_and_exhibits + - towing_services + - trailer_parks_campgrounds + - transportation_services + - travel_agencies_tour_operators + - truck_stop_iteration + - truck_utility_trailer_rentals + - typesetting_plate_making_and_related_services + - typewriter_stores + - u_s_federal_government_agencies_or_departments + - uniforms_commercial_clothing + - used_merchandise_and_secondhand_stores + - utilities + - variety_stores + - veterinary_services + - video_amusement_game_supplies + - video_game_arcades + - video_tape_rental_stores + - vocational_trade_schools + - watch_jewelry_repair + - welding_repair + - wholesale_clubs + - wig_and_toupee_stores + - wires_money_orders + - womens_accessory_and_specialty_shops + - womens_ready_to_wear_stores + - wrecking_and_salvage_yards + type: string + nullable: true + type: array + spending_limits: + description: Limit spending with amount-based rules that apply across this + cardholder's cards. + items: + "$ref": "#/components/schemas/issuing_cardholder_spending_limit" + nullable: true + type: array + spending_limits_currency: + description: Currency of the amounts within `spending_limits`. + nullable: true + type: string + title: IssuingCardholderAuthorizationControls + type: object + x-expandableFields: + - spending_limits + issuing_cardholder_company: + description: '' + properties: + tax_id_provided: + description: Whether the company's business ID number was provided. + type: boolean + required: + - tax_id_provided + title: IssuingCardholderCompany + type: object + x-expandableFields: [] + issuing_cardholder_id_document: + description: '' + properties: + back: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) + with a `purpose` value of `identity_document`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + front: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) + with a `purpose` value of `identity_document`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + title: IssuingCardholderIdDocument + type: object + x-expandableFields: + - back + - front + issuing_cardholder_individual: + description: '' + properties: + dob: + anyOf: + - "$ref": "#/components/schemas/issuing_cardholder_individual_dob" + description: The date of birth of this cardholder. + nullable: true + first_name: + description: The first name of this cardholder. + maxLength: 5000 + type: string + last_name: + description: The last name of this cardholder. + maxLength: 5000 + type: string + verification: + anyOf: + - "$ref": "#/components/schemas/issuing_cardholder_verification" + description: Government-issued ID document for this cardholder. + nullable: true + required: + - first_name + - last_name + title: IssuingCardholderIndividual + type: object + x-expandableFields: + - dob + - verification + issuing_cardholder_individual_dob: + description: '' + properties: + day: + description: The day of birth, between 1 and 31. + nullable: true + type: integer + month: + description: The month of birth, between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year of birth. + nullable: true + type: integer + title: IssuingCardholderIndividualDOB + type: object + x-expandableFields: [] + issuing_cardholder_requirements: + description: '' + properties: + disabled_reason: + description: If `disabled_reason` is present, all cards will decline authorizations + with `cardholder_verification_required` reason. + enum: + - listed + - rejected.listed + - under_review + nullable: true + type: string + past_due: + description: Array of fields that need to be collected in order to verify + and re-enable the cardholder. + items: + enum: + - company.tax_id + - individual.dob.day + - individual.dob.month + - individual.dob.year + - individual.first_name + - individual.last_name + - individual.verification.document + type: string + x-stripeBypassValidation: true + nullable: true + type: array + title: IssuingCardholderRequirements + type: object + x-expandableFields: [] + issuing_cardholder_spending_limit: + description: '' + properties: + amount: + description: Maximum amount allowed to spend per interval. + type: integer + categories: + description: Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) + this limit applies to. Omitting this field will apply the limit to all + categories. + items: + enum: + - ac_refrigeration_repair + - accounting_bookkeeping_services + - advertising_services + - agricultural_cooperative + - airlines_air_carriers + - airports_flying_fields + - ambulance_services + - amusement_parks_carnivals + - antique_reproductions + - antique_shops + - aquariums + - architectural_surveying_services + - art_dealers_and_galleries + - artists_supply_and_craft_shops + - auto_and_home_supply_stores + - auto_body_repair_shops + - auto_paint_shops + - auto_service_shops + - automated_cash_disburse + - automated_fuel_dispensers + - automobile_associations + - automotive_parts_and_accessories_stores + - automotive_tire_stores + - bail_and_bond_payments + - bakeries + - bands_orchestras + - barber_and_beauty_shops + - betting_casino_gambling + - bicycle_shops + - billiard_pool_establishments + - boat_dealers + - boat_rentals_and_leases + - book_stores + - books_periodicals_and_newspapers + - bowling_alleys + - bus_lines + - business_secretarial_schools + - buying_shopping_services + - cable_satellite_and_other_pay_television_and_radio + - camera_and_photographic_supply_stores + - candy_nut_and_confectionery_stores + - car_and_truck_dealers_new_used + - car_and_truck_dealers_used_only + - car_rental_agencies + - car_washes + - carpentry_services + - carpet_upholstery_cleaning + - caterers + - charitable_and_social_service_organizations_fundraising + - chemicals_and_allied_products + - child_care_services + - childrens_and_infants_wear_stores + - chiropodists_podiatrists + - chiropractors + - cigar_stores_and_stands + - civic_social_fraternal_associations + - cleaning_and_maintenance + - clothing_rental + - colleges_universities + - commercial_equipment + - commercial_footwear + - commercial_photography_art_and_graphics + - commuter_transport_and_ferries + - computer_network_services + - computer_programming + - computer_repair + - computer_software_stores + - computers_peripherals_and_software + - concrete_work_services + - construction_materials + - consulting_public_relations + - correspondence_schools + - cosmetic_stores + - counseling_services + - country_clubs + - courier_services + - court_costs + - credit_reporting_agencies + - cruise_lines + - dairy_products_stores + - dance_hall_studios_schools + - dating_escort_services + - dentists_orthodontists + - department_stores + - detective_agencies + - digital_goods_applications + - digital_goods_games + - digital_goods_large_volume + - digital_goods_media + - direct_marketing_catalog_merchant + - direct_marketing_combination_catalog_and_retail_merchant + - direct_marketing_inbound_telemarketing + - direct_marketing_insurance_services + - direct_marketing_other + - direct_marketing_outbound_telemarketing + - direct_marketing_subscription + - direct_marketing_travel + - discount_stores + - doctors + - door_to_door_sales + - drapery_window_covering_and_upholstery_stores + - drinking_places + - drug_stores_and_pharmacies + - drugs_drug_proprietaries_and_druggist_sundries + - dry_cleaners + - durable_goods + - duty_free_stores + - eating_places_restaurants + - educational_services + - electric_razor_stores + - electrical_parts_and_equipment + - electrical_services + - electronics_repair_shops + - electronics_stores + - elementary_secondary_schools + - employment_temp_agencies + - equipment_rental + - exterminating_services + - family_clothing_stores + - fast_food_restaurants + - financial_institutions + - fines_government_administrative_entities + - fireplace_fireplace_screens_and_accessories_stores + - floor_covering_stores + - florists + - florists_supplies_nursery_stock_and_flowers + - freezer_and_locker_meat_provisioners + - fuel_dealers_non_automotive + - funeral_services_crematories + - furniture_home_furnishings_and_equipment_stores_except_appliances + - furniture_repair_refinishing + - furriers_and_fur_shops + - general_services + - gift_card_novelty_and_souvenir_shops + - glass_paint_and_wallpaper_stores + - glassware_crystal_stores + - golf_courses_public + - government_services + - grocery_stores_supermarkets + - hardware_equipment_and_supplies + - hardware_stores + - health_and_beauty_spas + - hearing_aids_sales_and_supplies + - heating_plumbing_a_c + - hobby_toy_and_game_shops + - home_supply_warehouse_stores + - hospitals + - hotels_motels_and_resorts + - household_appliance_stores + - industrial_supplies + - information_retrieval_services + - insurance_default + - insurance_underwriting_premiums + - intra_company_purchases + - jewelry_stores_watches_clocks_and_silverware_stores + - landscaping_services + - laundries + - laundry_cleaning_services + - legal_services_attorneys + - luggage_and_leather_goods_stores + - lumber_building_materials_stores + - manual_cash_disburse + - marinas_service_and_supplies + - masonry_stonework_and_plaster + - massage_parlors + - medical_and_dental_labs + - medical_dental_ophthalmic_and_hospital_equipment_and_supplies + - medical_services + - membership_organizations + - mens_and_boys_clothing_and_accessories_stores + - mens_womens_clothing_stores + - metal_service_centers + - miscellaneous + - miscellaneous_apparel_and_accessory_shops + - miscellaneous_auto_dealers + - miscellaneous_business_services + - miscellaneous_food_stores + - miscellaneous_general_merchandise + - miscellaneous_general_services + - miscellaneous_home_furnishing_specialty_stores + - miscellaneous_publishing_and_printing + - miscellaneous_recreation_services + - miscellaneous_repair_shops + - miscellaneous_specialty_retail + - mobile_home_dealers + - motion_picture_theaters + - motor_freight_carriers_and_trucking + - motor_homes_dealers + - motor_vehicle_supplies_and_new_parts + - motorcycle_shops_and_dealers + - motorcycle_shops_dealers + - music_stores_musical_instruments_pianos_and_sheet_music + - news_dealers_and_newsstands + - non_fi_money_orders + - non_fi_stored_value_card_purchase_load + - nondurable_goods + - nurseries_lawn_and_garden_supply_stores + - nursing_personal_care + - office_and_commercial_furniture + - opticians_eyeglasses + - optometrists_ophthalmologist + - orthopedic_goods_prosthetic_devices + - osteopaths + - package_stores_beer_wine_and_liquor + - paints_varnishes_and_supplies + - parking_lots_garages + - passenger_railways + - pawn_shops + - pet_shops_pet_food_and_supplies + - petroleum_and_petroleum_products + - photo_developing + - photographic_photocopy_microfilm_equipment_and_supplies + - photographic_studios + - picture_video_production + - piece_goods_notions_and_other_dry_goods + - plumbing_heating_equipment_and_supplies + - political_organizations + - postal_services_government_only + - precious_stones_and_metals_watches_and_jewelry + - professional_services + - public_warehousing_and_storage + - quick_copy_repro_and_blueprint + - railroads + - real_estate_agents_and_managers_rentals + - record_stores + - recreational_vehicle_rentals + - religious_goods_stores + - religious_organizations + - roofing_siding_sheet_metal + - secretarial_support_services + - security_brokers_dealers + - service_stations + - sewing_needlework_fabric_and_piece_goods_stores + - shoe_repair_hat_cleaning + - shoe_stores + - small_appliance_repair + - snowmobile_dealers + - special_trade_services + - specialty_cleaning + - sporting_goods_stores + - sporting_recreation_camps + - sports_and_riding_apparel_stores + - sports_clubs_fields + - stamp_and_coin_stores + - stationary_office_supplies_printing_and_writing_paper + - stationery_stores_office_and_school_supply_stores + - swimming_pools_sales + - t_ui_travel_germany + - tailors_alterations + - tax_payments_government_agencies + - tax_preparation_services + - taxicabs_limousines + - telecommunication_equipment_and_telephone_sales + - telecommunication_services + - telegraph_services + - tent_and_awning_shops + - testing_laboratories + - theatrical_ticket_agencies + - timeshares + - tire_retreading_and_repair + - tolls_bridge_fees + - tourist_attractions_and_exhibits + - towing_services + - trailer_parks_campgrounds + - transportation_services + - travel_agencies_tour_operators + - truck_stop_iteration + - truck_utility_trailer_rentals + - typesetting_plate_making_and_related_services + - typewriter_stores + - u_s_federal_government_agencies_or_departments + - uniforms_commercial_clothing + - used_merchandise_and_secondhand_stores + - utilities + - variety_stores + - veterinary_services + - video_amusement_game_supplies + - video_game_arcades + - video_tape_rental_stores + - vocational_trade_schools + - watch_jewelry_repair + - welding_repair + - wholesale_clubs + - wig_and_toupee_stores + - wires_money_orders + - womens_accessory_and_specialty_shops + - womens_ready_to_wear_stores + - wrecking_and_salvage_yards + type: string + nullable: true + type: array + interval: + description: Interval (or event) to which the amount applies. + enum: + - all_time + - daily + - monthly + - per_authorization + - weekly + - yearly + type: string + required: + - amount + - interval + title: IssuingCardholderSpendingLimit + type: object + x-expandableFields: [] + issuing_cardholder_verification: + description: '' + properties: + document: + anyOf: + - "$ref": "#/components/schemas/issuing_cardholder_id_document" + description: An identifying document, either a passport or local ID card. + nullable: true + title: IssuingCardholderVerification + type: object + x-expandableFields: + - document + issuing_dispute_canceled_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + canceled_at: + description: Date when order was canceled. + format: unix-time + nullable: true + type: integer + cancellation_policy_provided: + description: Whether the cardholder was provided with a cancellation policy. + nullable: true + type: boolean + cancellation_reason: + description: Reason for canceling the order. + maxLength: 5000 + nullable: true + type: string + expected_at: + description: Date when the cardholder expected to receive the product. + format: unix-time + nullable: true + type: integer + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + product_description: + description: Description of the merchandise or service that was purchased. + maxLength: 5000 + nullable: true + type: string + product_type: + description: Whether the product was a merchandise or service. + enum: + - merchandise + - service + nullable: true + type: string + return_status: + description: Result of cardholder's attempt to return the product. + enum: + - merchant_rejected + - successful + nullable: true + type: string + returned_at: + description: Date when the product was returned or attempted to be returned. + format: unix-time + nullable: true + type: integer + title: IssuingDisputeCanceledEvidence + type: object + x-expandableFields: + - additional_documentation + issuing_dispute_duplicate_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + card_statement: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Copy of the card statement showing that the product had already been paid + for." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + cash_receipt: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Copy of the receipt showing that the product had been paid for in cash." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + check_image: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Image of the front and back of the check that was used to pay for the + product." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + original_transaction: + description: Transaction (e.g., ipi_...) that the disputed transaction is + a duplicate of. Of the two or more transactions that are copies of each + other, this is original undisputed one. + maxLength: 5000 + nullable: true + type: string + title: IssuingDisputeDuplicateEvidence + type: object + x-expandableFields: + - additional_documentation + - card_statement + - cash_receipt + - check_image + issuing_dispute_evidence: + description: 'Evidence for the dispute. Evidence contains exactly two non-null fields: the reason for the dispute and the associated evidence field for the selected reason' + properties: + canceled: + "$ref": "#/components/schemas/issuing_dispute_canceled_evidence" + duplicate: + "$ref": "#/components/schemas/issuing_dispute_duplicate_evidence" + fraudulent: + "$ref": "#/components/schemas/issuing_dispute_fraudulent_evidence" + merchandise_not_as_described: + "$ref": "#/components/schemas/issuing_dispute_merchandise_not_as_described_evidence" + not_received: + "$ref": "#/components/schemas/issuing_dispute_not_received_evidence" + other: + "$ref": "#/components/schemas/issuing_dispute_other_evidence" + reason: + description: The reason for filing the dispute. Its value will match the + field containing the evidence. + enum: + - canceled + - duplicate + - fraudulent + - merchandise_not_as_described + - not_received + - other + - service_not_as_described + type: string + x-stripeBypassValidation: true + service_not_as_described: + "$ref": "#/components/schemas/issuing_dispute_service_not_as_described_evidence" + required: + - reason + title: IssuingDisputeEvidence + type: object + x-expandableFields: + - canceled + - duplicate + - fraudulent + - merchandise_not_as_described + - not_received + - other + - service_not_as_described + issuing_dispute_fraudulent_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + title: IssuingDisputeFraudulentEvidence + type: object + x-expandableFields: + - additional_documentation + issuing_dispute_merchandise_not_as_described_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + received_at: + description: Date when the product was received. + format: unix-time + nullable: true + type: integer + return_description: + description: Description of the cardholder's attempt to return the product. + maxLength: 5000 + nullable: true + type: string + return_status: + description: Result of cardholder's attempt to return the product. + enum: + - merchant_rejected + - successful + nullable: true + type: string + returned_at: + description: Date when the product was returned or attempted to be returned. + format: unix-time + nullable: true + type: integer + title: IssuingDisputeMerchandiseNotAsDescribedEvidence + type: object + x-expandableFields: + - additional_documentation + issuing_dispute_not_received_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + expected_at: + description: Date when the cardholder expected to receive the product. + format: unix-time + nullable: true + type: integer + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + product_description: + description: Description of the merchandise or service that was purchased. + maxLength: 5000 + nullable: true + type: string + product_type: + description: Whether the product was a merchandise or service. + enum: + - merchandise + - service + nullable: true + type: string + title: IssuingDisputeNotReceivedEvidence + type: object + x-expandableFields: + - additional_documentation + issuing_dispute_other_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + product_description: + description: Description of the merchandise or service that was purchased. + maxLength: 5000 + nullable: true + type: string + product_type: + description: Whether the product was a merchandise or service. + enum: + - merchandise + - service + nullable: true + type: string + title: IssuingDisputeOtherEvidence + type: object + x-expandableFields: + - additional_documentation + issuing_dispute_service_not_as_described_evidence: + description: '' + properties: + additional_documentation: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: "(ID of a [file upload](https://stripe.com/docs/guides/file-upload)) + Additional documentation supporting the dispute." + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + canceled_at: + description: Date when order was canceled. + format: unix-time + nullable: true + type: integer + cancellation_reason: + description: Reason for canceling the order. + maxLength: 5000 + nullable: true + type: string + explanation: + description: Explanation of why the cardholder is disputing this transaction. + maxLength: 5000 + nullable: true + type: string + received_at: + description: Date when the product was received. + format: unix-time + nullable: true + type: integer + title: IssuingDisputeServiceNotAsDescribedEvidence + type: object + x-expandableFields: + - additional_documentation + issuing_transaction_amount_details: + description: '' + properties: + atm_fee: + description: The fee charged by the ATM for the cash withdrawal. + nullable: true + type: integer + title: IssuingTransactionAmountDetails + type: object + x-expandableFields: [] + issuing_transaction_flight_data: + description: '' + properties: + departure_at: + description: The time that the flight departed. + nullable: true + type: integer + passenger_name: + description: The name of the passenger. + maxLength: 5000 + nullable: true + type: string + refundable: + description: Whether the ticket is refundable. + nullable: true + type: boolean + segments: + description: The legs of the trip. + items: + "$ref": "#/components/schemas/issuing_transaction_flight_data_leg" + nullable: true + type: array + travel_agency: + description: The travel agency that issued the ticket. + maxLength: 5000 + nullable: true + type: string + title: IssuingTransactionFlightData + type: object + x-expandableFields: + - segments + issuing_transaction_flight_data_leg: + description: '' + properties: + arrival_airport_code: + description: The three-letter IATA airport code of the flight's destination. + maxLength: 5000 + nullable: true + type: string + carrier: + description: The airline carrier code. + maxLength: 5000 + nullable: true + type: string + departure_airport_code: + description: The three-letter IATA airport code that the flight departed + from. + maxLength: 5000 + nullable: true + type: string + flight_number: + description: The flight number. + maxLength: 5000 + nullable: true + type: string + service_class: + description: The flight's service class. + maxLength: 5000 + nullable: true + type: string + stopover_allowed: + description: Whether a stopover is allowed on this flight. + nullable: true + type: boolean + title: IssuingTransactionFlightDataLeg + type: object + x-expandableFields: [] + issuing_transaction_fuel_data: + description: '' + properties: + type: + description: The type of fuel that was purchased. One of `diesel`, `unleaded_plus`, + `unleaded_regular`, `unleaded_super`, or `other`. + maxLength: 5000 + type: string + unit: + description: The units for `volume_decimal`. One of `us_gallon` or `liter`. + maxLength: 5000 + type: string + unit_cost_decimal: + description: The cost in cents per each unit of fuel, represented as a decimal + string with at most 12 decimal places. + format: decimal + type: string + volume_decimal: + description: The volume of the fuel that was pumped, represented as a decimal + string with at most 12 decimal places. + format: decimal + nullable: true + type: string + required: + - type + - unit + - unit_cost_decimal + title: IssuingTransactionFuelData + type: object + x-expandableFields: [] + issuing_transaction_lodging_data: + description: '' + properties: + check_in_at: + description: The time of checking into the lodging. + nullable: true + type: integer + nights: + description: The number of nights stayed at the lodging. + nullable: true + type: integer + title: IssuingTransactionLodgingData + type: object + x-expandableFields: [] + issuing_transaction_purchase_details: + description: '' + properties: + flight: + anyOf: + - "$ref": "#/components/schemas/issuing_transaction_flight_data" + description: Information about the flight that was purchased with this transaction. + nullable: true + fuel: + anyOf: + - "$ref": "#/components/schemas/issuing_transaction_fuel_data" + description: Information about fuel that was purchased with this transaction. + nullable: true + lodging: + anyOf: + - "$ref": "#/components/schemas/issuing_transaction_lodging_data" + description: Information about lodging that was purchased with this transaction. + nullable: true + receipt: + description: The line items in the purchase. + items: + "$ref": "#/components/schemas/issuing_transaction_receipt_data" + nullable: true + type: array + reference: + description: A merchant-specific order number. + maxLength: 5000 + nullable: true + type: string + title: IssuingTransactionPurchaseDetails + type: object + x-expandableFields: + - flight + - fuel + - lodging + - receipt + issuing_transaction_receipt_data: + description: '' + properties: + description: + description: The description of the item. The maximum length of this field + is 26 characters. + maxLength: 5000 + nullable: true + type: string + quantity: + description: The quantity of the item. + nullable: true + type: number + total: + description: The total for this line item in cents. + nullable: true + type: integer + unit_cost: + description: The unit cost of the item in cents. + nullable: true + type: integer + title: IssuingTransactionReceiptData + type: object + x-expandableFields: [] + item: + description: A line item. + properties: + amount_subtotal: + description: Total before any discounts or taxes are applied. + type: integer + amount_total: + description: Total after discounts and taxes. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. Defaults to product name. + maxLength: 5000 + type: string + discounts: + description: The discounts applied to the line item. + items: + "$ref": "#/components/schemas/line_items_discount_amount" + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - item + type: string + price: + anyOf: + - "$ref": "#/components/schemas/price" + description: The price used to generate the line item. + nullable: true + quantity: + description: The quantity of products being purchased. + nullable: true + type: integer + taxes: + description: The taxes applied to the line item. + items: + "$ref": "#/components/schemas/line_items_tax_amount" + type: array + required: + - amount_subtotal + - amount_total + - currency + - description + - id + - object + title: LineItem + type: object + x-expandableFields: + - discounts + - price + - taxes + x-resourceId: item + legal_entity_company: + description: '' + properties: + address: + "$ref": "#/components/schemas/address" + address_kana: + anyOf: + - "$ref": "#/components/schemas/legal_entity_japan_address" + description: The Kana variation of the company's primary address (Japan + only). + nullable: true + address_kanji: + anyOf: + - "$ref": "#/components/schemas/legal_entity_japan_address" + description: The Kanji variation of the company's primary address (Japan + only). + nullable: true + directors_provided: + description: Whether the company's directors have been provided. This Boolean + will be `true` if you've manually indicated that all directors are provided + via [the `directors_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-directors_provided). + type: boolean + executives_provided: + description: Whether the company's executives have been provided. This Boolean + will be `true` if you've manually indicated that all executives are provided + via [the `executives_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-executives_provided), + or if Stripe determined that sufficient executives were provided. + type: boolean + name: + description: The company's legal name. + maxLength: 5000 + nullable: true + type: string + name_kana: + description: The Kana variation of the company's legal name (Japan only). + maxLength: 5000 + nullable: true + type: string + name_kanji: + description: The Kanji variation of the company's legal name (Japan only). + maxLength: 5000 + nullable: true + type: string + owners_provided: + description: Whether the company's owners have been provided. This Boolean + will be `true` if you've manually indicated that all owners are provided + via [the `owners_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-owners_provided), + or if Stripe determined that sufficient owners were provided. Stripe determines + ownership requirements using both the number of owners provided and their + total percent ownership (calculated by adding the `percent_ownership` + of each owner together). + type: boolean + phone: + description: The company's phone number (used for verification). + maxLength: 5000 + nullable: true + type: string + structure: + description: The category identifying the legal structure of the company + or legal entity. See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) + for more details. + enum: + - free_zone_establishment + - free_zone_llc + - government_instrumentality + - governmental_unit + - incorporated_non_profit + - limited_liability_partnership + - llc + - multi_member_llc + - private_company + - private_corporation + - private_partnership + - public_company + - public_corporation + - public_partnership + - single_member_llc + - sole_establishment + - sole_proprietorship + - tax_exempt_government_instrumentality + - unincorporated_association + - unincorporated_non_profit + type: string + x-stripeBypassValidation: true + tax_id_provided: + description: Whether the company's business ID number was provided. + type: boolean + tax_id_registrar: + description: The jurisdiction in which the `tax_id` is registered (Germany-based + companies only). + maxLength: 5000 + type: string + vat_id_provided: + description: Whether the company's business VAT number was provided. + type: boolean + verification: + anyOf: + - "$ref": "#/components/schemas/legal_entity_company_verification" + description: Information on the verification state of the company. + nullable: true + title: LegalEntityCompany + type: object + x-expandableFields: + - address + - address_kana + - address_kanji + - verification + legal_entity_company_verification: + description: '' + properties: + document: + "$ref": "#/components/schemas/legal_entity_company_verification_document" + required: + - document + title: LegalEntityCompanyVerification + type: object + x-expandableFields: + - document + legal_entity_company_verification_document: + description: '' + properties: + back: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) + with a `purpose` value of `additional_verification`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + details: + description: A user-displayable string describing the verification state + of this document. + maxLength: 5000 + nullable: true + type: string + details_code: + description: One of `document_corrupt`, `document_expired`, `document_failed_copy`, + `document_failed_greyscale`, `document_failed_other`, `document_failed_test_mode`, + `document_fraudulent`, `document_incomplete`, `document_invalid`, `document_manipulated`, + `document_not_readable`, `document_not_uploaded`, `document_type_not_supported`, + or `document_too_large`. A machine-readable code specifying the verification + state for this document. + maxLength: 5000 + nullable: true + type: string + front: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) + with a `purpose` value of `additional_verification`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + title: LegalEntityCompanyVerificationDocument + type: object + x-expandableFields: + - back + - front + legal_entity_dob: + description: '' + properties: + day: + description: The day of birth, between 1 and 31. + nullable: true + type: integer + month: + description: The month of birth, between 1 and 12. + nullable: true + type: integer + year: + description: The four-digit year of birth. + nullable: true + type: integer + title: LegalEntityDOB + type: object + x-expandableFields: [] + legal_entity_japan_address: + description: '' + properties: + city: + description: City/Ward. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + maxLength: 5000 + nullable: true + type: string + line1: + description: Block/Building number. + maxLength: 5000 + nullable: true + type: string + line2: + description: Building details. + maxLength: 5000 + nullable: true + type: string + postal_code: + description: ZIP or postal code. + maxLength: 5000 + nullable: true + type: string + state: + description: Prefecture. + maxLength: 5000 + nullable: true + type: string + town: + description: Town/cho-me. + maxLength: 5000 + nullable: true + type: string + title: LegalEntityJapanAddress + type: object + x-expandableFields: [] + legal_entity_person_verification: + description: '' + properties: + additional_document: + anyOf: + - "$ref": "#/components/schemas/legal_entity_person_verification_document" + description: A document showing address, either a passport, local ID card, + or utility bill from a well-known utility company. + nullable: true + details: + description: A user-displayable string describing the verification state + for the person. For example, this may say "Provided identity information + could not be verified". + maxLength: 5000 + nullable: true + type: string + details_code: + description: One of `document_address_mismatch`, `document_dob_mismatch`, + `document_duplicate_type`, `document_id_number_mismatch`, `document_name_mismatch`, + `document_nationality_mismatch`, `failed_keyed_identity`, or `failed_other`. + A machine-readable code specifying the verification state for the person. + maxLength: 5000 + nullable: true + type: string + document: + "$ref": "#/components/schemas/legal_entity_person_verification_document" + status: + description: The state of verification for the person. Possible values are + `unverified`, `pending`, or `verified`. + maxLength: 5000 + type: string + required: + - status + title: LegalEntityPersonVerification + type: object + x-expandableFields: + - additional_document + - document + legal_entity_person_verification_document: + description: '' + properties: + back: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) + with a `purpose` value of `identity_document`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + details: + description: A user-displayable string describing the verification state + of this document. For example, if a document is uploaded and the picture + is too fuzzy, this may say "Identity document is too unclear to read". + maxLength: 5000 + nullable: true + type: string + details_code: + description: One of `document_corrupt`, `document_country_not_supported`, + `document_expired`, `document_failed_copy`, `document_failed_other`, `document_failed_test_mode`, + `document_fraudulent`, `document_failed_greyscale`, `document_incomplete`, + `document_invalid`, `document_manipulated`, `document_missing_back`, `document_missing_front`, + `document_not_readable`, `document_not_uploaded`, `document_photo_mismatch`, + `document_too_large`, or `document_type_not_supported`. A machine-readable + code specifying the verification state for this document. + maxLength: 5000 + nullable: true + type: string + front: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/file" + description: The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) + with a `purpose` value of `identity_document`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/file" + title: LegalEntityPersonVerificationDocument + type: object + x-expandableFields: + - back + - front + line_item: + description: '' + properties: + amount: + description: The amount, in %s. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + discount_amounts: + description: The amount of discount calculated per discount for this line + item. + items: + "$ref": "#/components/schemas/discounts_resource_discount_amount" + nullable: true + type: array + discountable: + description: If true, discounts will apply to this line item. Always false + for prorations. + type: boolean + discounts: + description: The discounts applied to the invoice line item. Line item discounts + are applied before invoice discounts. Use `expand[]=discounts` to expand + each discount. + items: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/discount" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/discount" + nullable: true + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice_item: + description: The ID of the [invoice item](https://stripe.com/docs/api/invoiceitems) + associated with this line item if any. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. Note that for line + items with `type=subscription` this will reflect the metadata of the subscription + that caused the line item to be created. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - line_item + type: string + period: + "$ref": "#/components/schemas/invoice_line_item_period" + price: + anyOf: + - "$ref": "#/components/schemas/price" + description: The price of the line item. + nullable: true + proration: + description: Whether this is a proration. + type: boolean + quantity: + description: The quantity of the subscription, if the line item is a subscription + or a proration. + nullable: true + type: integer + subscription: + description: The subscription that the invoice item pertains to, if any. + maxLength: 5000 + nullable: true + type: string + subscription_item: + description: The subscription item that generated this invoice item. Left + empty if the line item is not an explicit result of a subscription. + maxLength: 5000 + type: string + tax_amounts: + description: The amount of tax calculated per tax rate for this line item + items: + "$ref": "#/components/schemas/invoice_tax_amount" + type: array + tax_rates: + description: The tax rates which apply to the line item. + items: + "$ref": "#/components/schemas/tax_rate" + type: array + type: + description: A string identifying the type of the source of this line item, + either an `invoiceitem` or a `subscription`. + enum: + - invoiceitem + - subscription + type: string + required: + - amount + - currency + - discountable + - id + - livemode + - metadata + - object + - period + - proration + - type + title: InvoiceLineItem + type: object + x-expandableFields: + - discount_amounts + - discounts + - period + - price + - tax_amounts + - tax_rates + x-resourceId: line_item + line_items_discount_amount: + description: '' + properties: + amount: + description: The amount discounted. + type: integer + discount: + "$ref": "#/components/schemas/discount" + required: + - amount + - discount + title: LineItemsDiscountAmount + type: object + x-expandableFields: + - discount + line_items_tax_amount: + description: '' + properties: + amount: + description: Amount of tax applied for this rate. + type: integer + rate: + "$ref": "#/components/schemas/tax_rate" + required: + - amount + - rate + title: LineItemsTaxAmount + type: object + x-expandableFields: + - rate + login_link: + description: '' + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - login_link + type: string + url: + description: The URL for the login link. + maxLength: 5000 + type: string + required: + - created + - object + - url + title: LoginLink + type: object + x-expandableFields: [] + x-resourceId: login_link + mandate: + description: A Mandate is a record of the permission a customer has given you + to debit their payment method. + properties: + customer_acceptance: + "$ref": "#/components/schemas/customer_acceptance" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + multi_use: + "$ref": "#/components/schemas/mandate_multi_use" + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - mandate + type: string + payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the payment method associated with this mandate. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + payment_method_details: + "$ref": "#/components/schemas/mandate_payment_method_details" + single_use: + "$ref": "#/components/schemas/mandate_single_use" + status: + description: The status of the mandate, which indicates whether it can be + used to initiate a payment. + enum: + - active + - inactive + - pending + type: string + type: + description: The type of the mandate. + enum: + - multi_use + - single_use + type: string + required: + - customer_acceptance + - id + - livemode + - object + - payment_method + - payment_method_details + - status + - type + title: Mandate + type: object + x-expandableFields: + - customer_acceptance + - multi_use + - payment_method + - payment_method_details + - single_use + x-resourceId: mandate + mandate_acss_debit: + description: '' + properties: + interval_description: + description: Description of the interval. Only required if the 'payment_schedule' + parameter is 'interval' or 'combined'. + maxLength: 5000 + nullable: true + type: string + payment_schedule: + description: Payment schedule for the mandate. + enum: + - combined + - interval + - sporadic + type: string + transaction_type: + description: Transaction type of the mandate. + enum: + - business + - personal + type: string + required: + - payment_schedule + - transaction_type + title: mandate_acss_debit + type: object + x-expandableFields: [] + mandate_au_becs_debit: + description: '' + properties: + url: + description: The URL of the mandate. This URL generally contains sensitive + information about the customer and should be shared with them exclusively. + maxLength: 5000 + type: string + required: + - url + title: mandate_au_becs_debit + type: object + x-expandableFields: [] + mandate_bacs_debit: + description: '' + properties: + network_status: + description: The status of the mandate on the Bacs network. Can be one of + `pending`, `revoked`, `refused`, or `accepted`. + enum: + - accepted + - pending + - refused + - revoked + type: string + reference: + description: The unique reference identifying the mandate on the Bacs network. + maxLength: 5000 + type: string + url: + description: The URL that will contain the mandate that the customer has + signed. + maxLength: 5000 + type: string + required: + - network_status + - reference + - url + title: mandate_bacs_debit + type: object + x-expandableFields: [] + mandate_multi_use: + description: '' + properties: {} + title: mandate_multi_use + type: object + x-expandableFields: [] + mandate_payment_method_details: + description: '' + properties: + acss_debit: + "$ref": "#/components/schemas/mandate_acss_debit" + au_becs_debit: + "$ref": "#/components/schemas/mandate_au_becs_debit" + bacs_debit: + "$ref": "#/components/schemas/mandate_bacs_debit" + card: + "$ref": "#/components/schemas/card_mandate_payment_method_details" + sepa_debit: + "$ref": "#/components/schemas/mandate_sepa_debit" + type: + description: The type of the payment method associated with this mandate. + An additional hash is included on `payment_method_details` with a name + matching this value. It contains mandate information specific to the payment + method. + maxLength: 5000 + type: string + required: + - type + title: mandate_payment_method_details + type: object + x-expandableFields: + - acss_debit + - au_becs_debit + - bacs_debit + - card + - sepa_debit + mandate_sepa_debit: + description: '' + properties: + reference: + description: The unique reference of the mandate. + maxLength: 5000 + type: string + url: + description: The URL of the mandate. This URL generally contains sensitive + information about the customer and should be shared with them exclusively. + maxLength: 5000 + type: string + required: + - reference + - url + title: mandate_sepa_debit + type: object + x-expandableFields: [] + mandate_single_use: + description: '' + properties: + amount: + description: On a single use mandate, the amount of the payment. + type: integer + currency: + description: On a single use mandate, the currency of the payment. + type: string + required: + - amount + - currency + title: mandate_single_use + type: object + x-expandableFields: [] + networks: + description: '' + properties: + available: + description: All available networks for the card. + items: + maxLength: 5000 + type: string + type: array + preferred: + description: The preferred network for the card. + maxLength: 5000 + nullable: true + type: string + required: + - available + title: networks + type: object + x-expandableFields: [] + notification_event_data: + description: '' + properties: + object: + description: Object containing the API resource relevant to the event. For + example, an `invoice.created` event will have a full [invoice object](https://stripe.com/docs/api#invoice_object) + as the value of the object key. + type: object + previous_attributes: + description: Object containing the names of the attributes that have changed, + and their previous values (sent along only with *.updated events). + type: object + required: + - object + title: NotificationEventData + type: object + x-expandableFields: [] + notification_event_request: + description: '' + properties: + id: + description: ID of the API request that caused the event. If null, the event + was automatic (e.g., Stripe's automatic subscription handling). Request + logs are available in the [dashboard](https://dashboard.stripe.com/logs), + but currently not in the API. + maxLength: 5000 + nullable: true + type: string + idempotency_key: + description: 'The idempotency key transmitted during the request, if any. + *Note: This property is populated only for events on or after May 23, + 2017*.' + maxLength: 5000 + nullable: true + type: string + title: NotificationEventRequest + type: object + x-expandableFields: [] + offline_acceptance: + description: '' + properties: {} + title: offline_acceptance + type: object + x-expandableFields: [] + online_acceptance: + description: '' + properties: + ip_address: + description: The IP address from which the Mandate was accepted by the customer. + maxLength: 5000 + nullable: true + type: string + user_agent: + description: The user agent of the browser from which the Mandate was accepted + by the customer. + maxLength: 5000 + nullable: true + type: string + title: online_acceptance + type: object + x-expandableFields: [] + order: + description: |- + Order objects are created to handle end customers' purchases of previously + defined [products](https://stripe.com/docs/api#products). You can create, retrieve, and pay individual orders, as well + as list all orders. Orders are identified by a unique, random ID. + + Related guide: [Tax, Shipping, and Inventory](https://stripe.com/docs/orders). + properties: + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the total amount for the order. + type: integer + amount_returned: + description: The total amount that was returned to the customer. + nullable: true + type: integer + application: + description: ID of the Connect Application that created the order. + maxLength: 5000 + nullable: true + type: string + application_fee: + description: A fee in cents that will be applied to the order and transferred + to the application owner’s Stripe account. The request must be made with + an OAuth key or the Stripe-Account header in order to take an application + fee. For more information, see the application fees documentation. + nullable: true + type: integer + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: The ID of the payment used to pay for the order. Present if + the order status is `paid`, `fulfilled`, or `refunded`. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The customer used for the order. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + email: + description: The email address of the customer placing the order. + maxLength: 5000 + nullable: true + type: string + external_coupon_code: + description: External coupon code to load for this order. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + items: + description: List of items constituting the order. An order can have up + to 25 items. + items: + "$ref": "#/components/schemas/order_item" + type: array + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - order + type: string + returns: + description: A list of returns that have taken place for this order. + nullable: true + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/order_return" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: OrdersResourceOrderReturnList + type: object + x-expandableFields: + - data + selected_shipping_method: + description: The shipping method that is currently selected for this order, + if any. If present, it is equal to one of the `id`s of shipping methods + in the `shipping_methods` array. At order creation time, if there are + multiple shipping methods, Stripe will automatically selected the first + method. + maxLength: 5000 + nullable: true + type: string + shipping: + anyOf: + - "$ref": "#/components/schemas/shipping" + description: The shipping address for the order. Present if the order is + for goods to be shipped. + nullable: true + shipping_methods: + description: A list of supported shipping methods for this order. The desired + shipping method can be specified either by updating the order, or when + paying it. + items: + "$ref": "#/components/schemas/shipping_method" + nullable: true + type: array + status: + description: Current order status. One of `created`, `paid`, `canceled`, + `fulfilled`, or `returned`. More details in the [Orders Guide](https://stripe.com/docs/orders/guide#understanding-order-statuses). + maxLength: 5000 + type: string + status_transitions: + anyOf: + - "$ref": "#/components/schemas/status_transitions" + description: The timestamps at which the order status was updated. + nullable: true + updated: + description: Time at which the object was last updated. Measured in seconds + since the Unix epoch. + format: unix-time + nullable: true + type: integer + upstream_id: + description: The user's order ID if it is different from the Stripe order + ID. + maxLength: 5000 + type: string + required: + - amount + - created + - currency + - id + - items + - livemode + - object + - status + title: Order + type: object + x-expandableFields: + - charge + - customer + - items + - returns + - shipping + - shipping_methods + - status_transitions + x-resourceId: order + order_item: + description: |- + A representation of the constituent items of any given order. Can be used to + represent [SKUs](https://stripe.com/docs/api#skus), shipping costs, or taxes owed on the order. + + Related guide: [Orders](https://stripe.com/docs/orders/guide). + properties: + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the total amount for the line item. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: Description of the line item, meant to be displayable to the + user (e.g., `"Express shipping"`). + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - order_item + type: string + parent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/sku" + description: The ID of the associated object for this line item. Expandable + if not null (e.g., expandable to a SKU). + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/sku" + quantity: + description: A positive integer representing the number of instances of + `parent` that are included in this order item. Applicable/present only + if `type` is `sku`. + nullable: true + type: integer + type: + description: The type of line item. One of `sku`, `tax`, `shipping`, or + `discount`. + maxLength: 5000 + type: string + required: + - amount + - currency + - description + - object + - type + title: OrderItem + type: object + x-expandableFields: + - parent + order_return: + description: |- + A return represents the full or partial return of a number of [order items](https://stripe.com/docs/api#order_items). + Returns always belong to an order, and may optionally contain a refund. + + Related guide: [Handling Returns](https://stripe.com/docs/orders/guide#handling-returns). + properties: + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the total amount for the returned line item. + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + items: + description: The items included in this order return. + items: + "$ref": "#/components/schemas/order_item" + type: array + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - order_return + type: string + order: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/order" + description: The order that this return includes items from. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/order" + refund: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/refund" + description: The ID of the refund issued for this return. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/refund" + required: + - amount + - created + - currency + - id + - items + - livemode + - object + title: OrderReturn + type: object + x-expandableFields: + - items + - order + - refund + x-resourceId: order_return + package_dimensions: + description: '' + properties: + height: + description: Height, in inches. + type: number + length: + description: Length, in inches. + type: number + weight: + description: Weight, in ounces. + type: number + width: + description: Width, in inches. + type: number + required: + - height + - length + - weight + - width + title: PackageDimensions + type: object + x-expandableFields: [] + payment_flows_private_payment_methods_alipay: + description: '' + properties: {} + title: PaymentFlowsPrivatePaymentMethodsAlipay + type: object + x-expandableFields: [] + payment_flows_private_payment_methods_alipay_details: + description: '' + properties: + fingerprint: + description: Uniquely identifies this particular Alipay account. You can + use this attribute to check whether two Alipay accounts are the same. + maxLength: 5000 + nullable: true + type: string + transaction_id: + description: Transaction ID of this particular Alipay transaction. + maxLength: 5000 + nullable: true + type: string + title: PaymentFlowsPrivatePaymentMethodsAlipayDetails + type: object + x-expandableFields: [] + payment_intent: + description: |- + A PaymentIntent guides you through the process of collecting a payment from your customer. + We recommend that you create exactly one PaymentIntent for each order or + customer session in your system. You can reference the PaymentIntent later to + see the history of payment attempts for a particular session. + + A PaymentIntent transitions through + [multiple statuses](https://stripe.com/docs/payments/intents#intent-statuses) + throughout its lifetime as it interfaces with Stripe.js to perform + authentication flows and ultimately creates at most one successful charge. + + Related guide: [Payment Intents API](https://stripe.com/docs/payments/payment-intents). + properties: + amount: + description: Amount intended to be collected by this PaymentIntent. A positive + integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) + (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal + currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). + The amount value supports up to eight digits (e.g., a value of 99999999 + for a USD charge of $999,999.99). + type: integer + amount_capturable: + description: Amount that can be captured from this PaymentIntent. + type: integer + amount_received: + description: Amount that was collected by this PaymentIntent. + type: integer + application: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application" + description: ID of the Connect application that created the PaymentIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application" + application_fee_amount: + description: The amount of the application fee (if any) that will be requested + to be applied to the payment and transferred to the application owner's + Stripe account. The amount of the application fee collected will be capped + at the total payment amount. For more information, see the PaymentIntents + [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts). + nullable: true + type: integer + canceled_at: + description: Populated when `status` is `canceled`, this is the time at + which the PaymentIntent was canceled. Measured in seconds since the Unix + epoch. + format: unix-time + nullable: true + type: integer + cancellation_reason: + description: Reason for cancellation of this PaymentIntent, either user-provided + (`duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned`) or + generated by Stripe internally (`failed_invoice`, `void_invoice`, or `automatic`). + enum: + - abandoned + - automatic + - duplicate + - failed_invoice + - fraudulent + - requested_by_customer + - void_invoice + nullable: true + type: string + capture_method: + description: Controls when the funds will be captured from the customer's + account. + enum: + - automatic + - manual + type: string + charges: + description: Charges that were created by this PaymentIntent, if any. + properties: + data: + description: This list only contains the latest charge, even if there + were previously multiple unsuccessful charges. To view all previous + charges for a PaymentIntent, you can filter the charges list using + the `payment_intent` [parameter](https://stripe.com/docs/api/charges/list#list_charges-payment_intent). + items: + "$ref": "#/components/schemas/charge" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: PaymentFlowsPaymentIntentResourceChargeList + type: object + x-expandableFields: + - data + client_secret: + description: "The client secret of this PaymentIntent. Used for client-side + retrieval using a publishable key. \n\nThe client secret can be used to + complete a payment from your frontend. It should not be stored, logged, + embedded in URLs, or exposed to anyone other than the customer. Make sure + that you have TLS enabled on any page that includes the client secret.\n\nRefer + to our docs to [accept a payment](https://stripe.com/docs/payments/accept-a-payment?integration=elements) + and learn about how `client_secret` should be handled." + maxLength: 5000 + nullable: true + type: string + confirmation_method: + enum: + - automatic + - manual + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: |- + ID of the Customer this PaymentIntent belongs to, if one exists. + + Payment methods attached to other Customers cannot be used with this PaymentIntent. + + If present in combination with [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage), this PaymentIntent's payment method will be attached to the Customer after the PaymentIntent has been confirmed and any required actions from the user are complete. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + description: ID of the invoice that created this PaymentIntent, if it exists. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + last_payment_error: + anyOf: + - "$ref": "#/components/schemas/api_errors" + description: The payment error encountered in the previous PaymentIntent + confirmation. It will be cleared if the PaymentIntent is later updated + for any reason. + nullable: true + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. For more information, + see the [documentation](https://stripe.com/docs/payments/payment-intents/creating-payment-intents#storing-information-in-metadata). + type: object + next_action: + anyOf: + - "$ref": "#/components/schemas/payment_intent_next_action" + description: If present, this property tells you what actions you need to + take in order for your customer to fulfill a payment using the provided + source. + nullable: true + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - payment_intent + type: string + on_behalf_of: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account (if any) for which the funds of the PaymentIntent + are intended. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts) + for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the payment method used in this PaymentIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + payment_method_options: + anyOf: + - "$ref": "#/components/schemas/payment_intent_payment_method_options" + description: Payment-method-specific configuration for this PaymentIntent. + nullable: true + payment_method_types: + description: The list of payment method types (e.g. card) that this PaymentIntent + is allowed to use. + items: + maxLength: 5000 + type: string + type: array + receipt_email: + description: Email address that the receipt for the resulting payment will + be sent to. If `receipt_email` is specified for a payment in live mode, + a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + maxLength: 5000 + nullable: true + type: string + review: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/review" + description: ID of the review associated with this PaymentIntent, if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/review" + setup_future_usage: + description: |- + Indicates that you intend to make future payments with this PaymentIntent's payment method. + + Providing this parameter will [attach the payment method](https://stripe.com/docs/payments/save-during-payment) to the PaymentIntent's Customer, if present, after the PaymentIntent is confirmed and any required actions from the user are complete. If no Customer was provided, the payment method can still be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer after the transaction completes. + + When processing card payments, Stripe also uses `setup_future_usage` to dynamically optimize your payment flow and comply with regional legislation and network rules, such as [SCA](https://stripe.com/docs/strong-customer-authentication). + enum: + - off_session + - on_session + nullable: true + type: string + shipping: + anyOf: + - "$ref": "#/components/schemas/shipping" + description: Shipping information for this PaymentIntent. + nullable: true + statement_descriptor: + description: For non-card charges, you can use this value as the complete + description that appears on your customers’ statements. Must contain at + least one letter, maximum 22 characters. + maxLength: 5000 + nullable: true + type: string + statement_descriptor_suffix: + description: Provides information about a card payment that customers see + on their statements. Concatenated with the prefix (shortened descriptor) + or statement descriptor that’s set on the account to form the complete + statement descriptor. Maximum 22 characters for the concatenated descriptor. + maxLength: 5000 + nullable: true + type: string + status: + description: Status of this PaymentIntent, one of `requires_payment_method`, + `requires_confirmation`, `requires_action`, `processing`, `requires_capture`, + `canceled`, or `succeeded`. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses). + enum: + - canceled + - processing + - requires_action + - requires_capture + - requires_confirmation + - requires_payment_method + - succeeded + type: string + transfer_data: + anyOf: + - "$ref": "#/components/schemas/transfer_data" + description: The data with which to automatically create a Transfer when + the payment is finalized. See the PaymentIntents [use case for connected + accounts](https://stripe.com/docs/payments/connected-accounts) for details. + nullable: true + transfer_group: + description: A string that identifies the resulting payment as part of a + group. See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/connected-accounts) + for details. + maxLength: 5000 + nullable: true + type: string + required: + - amount + - capture_method + - confirmation_method + - created + - currency + - id + - livemode + - object + - payment_method_types + - status + title: PaymentIntent + type: object + x-expandableFields: + - application + - charges + - customer + - invoice + - last_payment_error + - next_action + - on_behalf_of + - payment_method + - payment_method_options + - review + - shipping + - transfer_data + x-resourceId: payment_intent + payment_intent_next_action: + description: '' + properties: + alipay_handle_redirect: + "$ref": "#/components/schemas/payment_intent_next_action_alipay_handle_redirect" + boleto_display_details: + "$ref": "#/components/schemas/payment_intent_next_action_boleto" + oxxo_display_details: + "$ref": "#/components/schemas/payment_intent_next_action_display_oxxo_details" + redirect_to_url: + "$ref": "#/components/schemas/payment_intent_next_action_redirect_to_url" + type: + description: Type of the next action to perform, one of `redirect_to_url`, + `use_stripe_sdk`, `alipay_handle_redirect`, or `oxxo_display_details`. + maxLength: 5000 + type: string + use_stripe_sdk: + description: When confirming a PaymentIntent with Stripe.js, Stripe.js depends + on the contents of this dictionary to invoke authentication flows. The + shape of the contents is subject to change and is only intended to be + used by Stripe.js. + type: object + verify_with_microdeposits: + "$ref": "#/components/schemas/payment_intent_next_action_verify_with_microdeposits" + wechat_pay_display_qr_code: + "$ref": "#/components/schemas/payment_intent_next_action_wechat_pay_display_qr_code" + wechat_pay_redirect_to_android_app: + "$ref": "#/components/schemas/payment_intent_next_action_wechat_pay_redirect_to_android_app" + wechat_pay_redirect_to_ios_app: + "$ref": "#/components/schemas/payment_intent_next_action_wechat_pay_redirect_to_ios_app" + required: + - type + title: PaymentIntentNextAction + type: object + x-expandableFields: + - alipay_handle_redirect + - boleto_display_details + - oxxo_display_details + - redirect_to_url + - verify_with_microdeposits + - wechat_pay_display_qr_code + - wechat_pay_redirect_to_android_app + - wechat_pay_redirect_to_ios_app + payment_intent_next_action_alipay_handle_redirect: + description: '' + properties: + native_data: + description: The native data to be used with Alipay SDK you must redirect + your customer to in order to authenticate the payment in an Android App. + maxLength: 5000 + nullable: true + type: string + native_url: + description: The native URL you must redirect your customer to in order + to authenticate the payment in an iOS App. + maxLength: 5000 + nullable: true + type: string + return_url: + description: If the customer does not exit their browser while authenticating, + they will be redirected to this specified URL after completion. + maxLength: 5000 + nullable: true + type: string + url: + description: The URL you must redirect your customer to in order to authenticate + the payment. + maxLength: 5000 + nullable: true + type: string + title: PaymentIntentNextActionAlipayHandleRedirect + type: object + x-expandableFields: [] + payment_intent_next_action_boleto: + description: '' + properties: + expires_at: + description: The timestamp after which the boleto expires. + format: unix-time + nullable: true + type: integer + hosted_voucher_url: + description: The URL to the hosted boleto voucher page, which allows customers + to view the boleto voucher. + maxLength: 5000 + nullable: true + type: string + number: + description: The boleto number. + maxLength: 5000 + nullable: true + type: string + pdf: + description: The URL to the downloadable boleto voucher PDF. + maxLength: 5000 + nullable: true + type: string + title: payment_intent_next_action_boleto + type: object + x-expandableFields: [] + payment_intent_next_action_display_oxxo_details: + description: '' + properties: + expires_after: + description: The timestamp after which the OXXO voucher expires. + format: unix-time + nullable: true + type: integer + hosted_voucher_url: + description: The URL for the hosted OXXO voucher page, which allows customers + to view and print an OXXO voucher. + maxLength: 5000 + nullable: true + type: string + number: + description: OXXO reference number. + maxLength: 5000 + nullable: true + type: string + title: PaymentIntentNextActionDisplayOxxoDetails + type: object + x-expandableFields: [] + payment_intent_next_action_redirect_to_url: + description: '' + properties: + return_url: + description: If the customer does not exit their browser while authenticating, + they will be redirected to this specified URL after completion. + maxLength: 5000 + nullable: true + type: string + url: + description: The URL you must redirect your customer to in order to authenticate + the payment. + maxLength: 5000 + nullable: true + type: string + title: PaymentIntentNextActionRedirectToUrl + type: object + x-expandableFields: [] + payment_intent_next_action_verify_with_microdeposits: + description: '' + properties: + arrival_date: + description: The timestamp when the microdeposits are expected to land. + format: unix-time + type: integer + hosted_verification_url: + description: The URL for the hosted verification page, which allows customers + to verify their bank account. + maxLength: 5000 + type: string + required: + - arrival_date + - hosted_verification_url + title: PaymentIntentNextActionVerifyWithMicrodeposits + type: object + x-expandableFields: [] + payment_intent_next_action_wechat_pay_display_qr_code: + description: '' + properties: + data: + description: The data being used to generate QR code + maxLength: 5000 + type: string + image_data_url: + description: The base64 image data for a pre-generated QR code + maxLength: 5000 + type: string + required: + - data + - image_data_url + title: PaymentIntentNextActionWechatPayDisplayQrCode + type: object + x-expandableFields: [] + payment_intent_next_action_wechat_pay_redirect_to_android_app: + description: '' + properties: + app_id: + description: app_id is the APP ID registered on WeChat open platform + maxLength: 5000 + type: string + nonce_str: + description: nonce_str is a random string + maxLength: 5000 + type: string + package: + description: package is static value + maxLength: 5000 + type: string + partner_id: + description: an unique merchant ID assigned by Wechat Pay + maxLength: 5000 + type: string + prepay_id: + description: an unique trading ID assigned by Wechat Pay + maxLength: 5000 + type: string + sign: + description: A signature + maxLength: 5000 + type: string + timestamp: + description: Specifies the current time in epoch format + maxLength: 5000 + type: string + required: + - app_id + - nonce_str + - package + - partner_id + - prepay_id + - sign + - timestamp + title: PaymentIntentNextActionWechatPayRedirectToAndroidApp + type: object + x-expandableFields: [] + payment_intent_next_action_wechat_pay_redirect_to_ios_app: + description: '' + properties: + native_url: + description: An universal link that redirect to Wechat Pay APP + maxLength: 5000 + type: string + required: + - native_url + title: PaymentIntentNextActionWechatPayRedirectToIOSApp + type: object + x-expandableFields: [] + payment_intent_payment_method_options: + description: '' + properties: + acss_debit: + "$ref": "#/components/schemas/payment_intent_payment_method_options_acss_debit" + afterpay_clearpay: + "$ref": "#/components/schemas/payment_method_options_afterpay_clearpay" + alipay: + "$ref": "#/components/schemas/payment_method_options_alipay" + bancontact: + "$ref": "#/components/schemas/payment_method_options_bancontact" + boleto: + "$ref": "#/components/schemas/payment_method_options_boleto" + card: + "$ref": "#/components/schemas/payment_intent_payment_method_options_card" + card_present: + "$ref": "#/components/schemas/payment_method_options_card_present" + ideal: + "$ref": "#/components/schemas/payment_method_options_ideal" + oxxo: + "$ref": "#/components/schemas/payment_method_options_oxxo" + p24: + "$ref": "#/components/schemas/payment_method_options_p24" + sepa_debit: + "$ref": "#/components/schemas/payment_intent_payment_method_options_sepa_debit" + sofort: + "$ref": "#/components/schemas/payment_method_options_sofort" + wechat_pay: + "$ref": "#/components/schemas/payment_method_options_wechat_pay" + title: PaymentIntentPaymentMethodOptions + type: object + x-expandableFields: + - acss_debit + - afterpay_clearpay + - alipay + - bancontact + - boleto + - card + - card_present + - ideal + - oxxo + - p24 + - sepa_debit + - sofort + - wechat_pay + payment_intent_payment_method_options_acss_debit: + description: '' + properties: + mandate_options: + "$ref": "#/components/schemas/payment_intent_payment_method_options_mandate_options_acss_debit" + verification_method: + description: Bank account verification method. + enum: + - automatic + - instant + - microdeposits + type: string + x-stripeBypassValidation: true + title: payment_intent_payment_method_options_acss_debit + type: object + x-expandableFields: + - mandate_options + payment_intent_payment_method_options_card: + description: '' + properties: + installments: + anyOf: + - "$ref": "#/components/schemas/payment_method_options_card_installments" + description: |- + Installment details for this payment (Mexico only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + nullable: true + network: + description: Selected network to process this payment intent on. Depends + on the available networks of the card attached to the payment intent. + Can be only set confirm-time. + enum: + - amex + - cartes_bancaires + - diners + - discover + - interac + - jcb + - mastercard + - unionpay + - unknown + - visa + nullable: true + type: string + request_three_d_secure: + description: 'We strongly recommend that you rely on our SCA Engine to automatically + prompt your customers for authentication based on risk level and [other + requirements](https://stripe.com/docs/strong-customer-authentication). + However, if you wish to request 3D Secure based on logic from your own + fraud engine, provide this option. Permitted values include: `automatic` + or `any`. If not provided, defaults to `automatic`. Read our guide on + [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) + for more information on how this configuration interacts with Radar and + our SCA Engine.' + enum: + - any + - automatic + - challenge_only + nullable: true + type: string + title: payment_intent_payment_method_options_card + type: object + x-expandableFields: + - installments + payment_intent_payment_method_options_mandate_options_acss_debit: + description: '' + properties: + custom_mandate_url: + description: A URL for custom mandate text + maxLength: 5000 + type: string + interval_description: + description: Description of the interval. Only required if the 'payment_schedule' + parameter is 'interval' or 'combined'. + maxLength: 5000 + nullable: true + type: string + payment_schedule: + description: Payment schedule for the mandate. + enum: + - combined + - interval + - sporadic + nullable: true + type: string + transaction_type: + description: Transaction type of the mandate. + enum: + - business + - personal + nullable: true + type: string + title: payment_intent_payment_method_options_mandate_options_acss_debit + type: object + x-expandableFields: [] + payment_intent_payment_method_options_mandate_options_sepa_debit: + description: '' + properties: {} + title: payment_intent_payment_method_options_mandate_options_sepa_debit + type: object + x-expandableFields: [] + payment_intent_payment_method_options_sepa_debit: + description: '' + properties: + mandate_options: + "$ref": "#/components/schemas/payment_intent_payment_method_options_mandate_options_sepa_debit" + title: payment_intent_payment_method_options_sepa_debit + type: object + x-expandableFields: + - mandate_options + payment_method: + description: |- + PaymentMethod objects represent your customer's payment instruments. + They can be used with [PaymentIntents](https://stripe.com/docs/payments/payment-intents) to collect payments or saved to + Customer objects to store instrument details for future payments. + + Related guides: [Payment Methods](https://stripe.com/docs/payments/payment-methods) and [More Payment Scenarios](https://stripe.com/docs/payments/more-payment-scenarios). + properties: + acss_debit: + "$ref": "#/components/schemas/payment_method_acss_debit" + afterpay_clearpay: + "$ref": "#/components/schemas/payment_method_afterpay_clearpay" + alipay: + "$ref": "#/components/schemas/payment_flows_private_payment_methods_alipay" + au_becs_debit: + "$ref": "#/components/schemas/payment_method_au_becs_debit" + bacs_debit: + "$ref": "#/components/schemas/payment_method_bacs_debit" + bancontact: + "$ref": "#/components/schemas/payment_method_bancontact" + billing_details: + "$ref": "#/components/schemas/billing_details" + boleto: + "$ref": "#/components/schemas/payment_method_boleto" + card: + "$ref": "#/components/schemas/payment_method_card" + card_present: + "$ref": "#/components/schemas/payment_method_card_present" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + description: The ID of the Customer to which this PaymentMethod is saved. + This will not be set when the PaymentMethod has not been saved to a Customer. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + eps: + "$ref": "#/components/schemas/payment_method_eps" + fpx: + "$ref": "#/components/schemas/payment_method_fpx" + giropay: + "$ref": "#/components/schemas/payment_method_giropay" + grabpay: + "$ref": "#/components/schemas/payment_method_grabpay" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + ideal: + "$ref": "#/components/schemas/payment_method_ideal" + interac_present: + "$ref": "#/components/schemas/payment_method_interac_present" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - payment_method + type: string + oxxo: + "$ref": "#/components/schemas/payment_method_oxxo" + p24: + "$ref": "#/components/schemas/payment_method_p24" + sepa_debit: + "$ref": "#/components/schemas/payment_method_sepa_debit" + sofort: + "$ref": "#/components/schemas/payment_method_sofort" + type: + description: The type of the PaymentMethod. An additional hash is included + on the PaymentMethod with a name matching this value. It contains additional + information specific to the PaymentMethod type. + enum: + - acss_debit + - afterpay_clearpay + - alipay + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - card_present + - eps + - fpx + - giropay + - grabpay + - ideal + - interac_present + - oxxo + - p24 + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + wechat_pay: + "$ref": "#/components/schemas/payment_method_wechat_pay" + required: + - billing_details + - created + - id + - livemode + - object + - type + title: PaymentMethod + type: object + x-expandableFields: + - acss_debit + - afterpay_clearpay + - alipay + - au_becs_debit + - bacs_debit + - bancontact + - billing_details + - boleto + - card + - card_present + - customer + - eps + - fpx + - giropay + - grabpay + - ideal + - interac_present + - oxxo + - p24 + - sepa_debit + - sofort + - wechat_pay + x-resourceId: payment_method + payment_method_acss_debit: + description: '' + properties: + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + institution_number: + description: Institution number of the bank account. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + transit_number: + description: Transit number of the bank account. + maxLength: 5000 + nullable: true + type: string + title: payment_method_acss_debit + type: object + x-expandableFields: [] + payment_method_afterpay_clearpay: + description: '' + properties: {} + title: payment_method_afterpay_clearpay + type: object + x-expandableFields: [] + payment_method_au_becs_debit: + description: '' + properties: + bsb_number: + description: Six-digit number identifying bank and branch associated with + this bank account. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + title: payment_method_au_becs_debit + type: object + x-expandableFields: [] + payment_method_bacs_debit: + description: '' + properties: + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + sort_code: + description: Sort code of the bank account. (e.g., `10-20-30`) + maxLength: 5000 + nullable: true + type: string + title: payment_method_bacs_debit + type: object + x-expandableFields: [] + payment_method_bancontact: + description: '' + properties: {} + title: payment_method_bancontact + type: object + x-expandableFields: [] + payment_method_boleto: + description: '' + properties: + tax_id: + description: Uniquely identifies the customer tax id (CNPJ or CPF) + maxLength: 5000 + type: string + required: + - tax_id + title: payment_method_boleto + type: object + x-expandableFields: [] + payment_method_card: + description: '' + properties: + brand: + description: Card brand. Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, + `unionpay`, `visa`, or `unknown`. + maxLength: 5000 + type: string + checks: + anyOf: + - "$ref": "#/components/schemas/payment_method_card_checks" + description: Checks on Card address and CVC if provided. + nullable: true + country: + description: Two-letter ISO code representing the country of the card. You + could use this attribute to get a sense of the international breakdown + of cards you've collected. + maxLength: 5000 + nullable: true + type: string + exp_month: + description: Two-digit number representing the card's expiration month. + type: integer + exp_year: + description: Four-digit number representing the card's expiration year. + type: integer + fingerprint: + description: |- + Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + + *Starting May 1, 2021, card fingerprint in India for Connect will change to allow two fingerprints for the same card --- one for India and one for the rest of the world.* + maxLength: 5000 + nullable: true + type: string + funding: + description: Card funding type. Can be `credit`, `debit`, `prepaid`, or + `unknown`. + maxLength: 5000 + type: string + generated_from: + anyOf: + - "$ref": "#/components/schemas/payment_method_card_generated_card" + description: Details of the original PaymentMethod that created this object. + nullable: true + last4: + description: The last four digits of the card. + maxLength: 5000 + type: string + networks: + anyOf: + - "$ref": "#/components/schemas/networks" + description: Contains information about card networks that can be used to + process the payment. + nullable: true + three_d_secure_usage: + anyOf: + - "$ref": "#/components/schemas/three_d_secure_usage" + description: Contains details on how this Card maybe be used for 3D Secure + authentication. + nullable: true + wallet: + anyOf: + - "$ref": "#/components/schemas/payment_method_card_wallet" + description: If this Card is part of a card wallet, this contains the details + of the card wallet. + nullable: true + required: + - brand + - exp_month + - exp_year + - funding + - last4 + title: payment_method_card + type: object + x-expandableFields: + - checks + - generated_from + - networks + - three_d_secure_usage + - wallet + payment_method_card_checks: + description: '' + properties: + address_line1_check: + description: If a address line1 was provided, results of the check, one + of `pass`, `fail`, `unavailable`, or `unchecked`. + maxLength: 5000 + nullable: true + type: string + address_postal_code_check: + description: If a address postal code was provided, results of the check, + one of `pass`, `fail`, `unavailable`, or `unchecked`. + maxLength: 5000 + nullable: true + type: string + cvc_check: + description: If a CVC was provided, results of the check, one of `pass`, + `fail`, `unavailable`, or `unchecked`. + maxLength: 5000 + nullable: true + type: string + title: payment_method_card_checks + type: object + x-expandableFields: [] + payment_method_card_generated_card: + description: '' + properties: + charge: + description: The charge that created this object. + maxLength: 5000 + nullable: true + type: string + payment_method_details: + anyOf: + - "$ref": "#/components/schemas/card_generated_from_payment_method_details" + description: Transaction-specific details of the payment method used in + the payment. + nullable: true + setup_attempt: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/setup_attempt" + description: The ID of the SetupAttempt that generated this PaymentMethod, + if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/setup_attempt" + title: payment_method_card_generated_card + type: object + x-expandableFields: + - payment_method_details + - setup_attempt + payment_method_card_present: + description: '' + properties: {} + title: payment_method_card_present + type: object + x-expandableFields: [] + payment_method_card_wallet: + description: '' + properties: + amex_express_checkout: + "$ref": "#/components/schemas/payment_method_card_wallet_amex_express_checkout" + apple_pay: + "$ref": "#/components/schemas/payment_method_card_wallet_apple_pay" + dynamic_last4: + description: "(For tokenized numbers only.) The last four digits of the + device account number." + maxLength: 5000 + nullable: true + type: string + google_pay: + "$ref": "#/components/schemas/payment_method_card_wallet_google_pay" + masterpass: + "$ref": "#/components/schemas/payment_method_card_wallet_masterpass" + samsung_pay: + "$ref": "#/components/schemas/payment_method_card_wallet_samsung_pay" + type: + description: The type of the card wallet, one of `amex_express_checkout`, + `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, or `visa_checkout`. + An additional hash is included on the Wallet subhash with a name matching + this value. It contains additional information specific to the card wallet + type. + enum: + - amex_express_checkout + - apple_pay + - google_pay + - masterpass + - samsung_pay + - visa_checkout + type: string + visa_checkout: + "$ref": "#/components/schemas/payment_method_card_wallet_visa_checkout" + required: + - type + title: payment_method_card_wallet + type: object + x-expandableFields: + - amex_express_checkout + - apple_pay + - google_pay + - masterpass + - samsung_pay + - visa_checkout + payment_method_card_wallet_amex_express_checkout: + description: '' + properties: {} + title: payment_method_card_wallet_amex_express_checkout + type: object + x-expandableFields: [] + payment_method_card_wallet_apple_pay: + description: '' + properties: {} + title: payment_method_card_wallet_apple_pay + type: object + x-expandableFields: [] + payment_method_card_wallet_google_pay: + description: '' + properties: {} + title: payment_method_card_wallet_google_pay + type: object + x-expandableFields: [] + payment_method_card_wallet_masterpass: + description: '' + properties: + billing_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified billing address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + email: + description: Owner's verified email. Values are verified or provided by + the wallet directly (if supported) at the time of authorization or settlement. + They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + name: + description: Owner's verified full name. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + shipping_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified shipping address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + title: payment_method_card_wallet_masterpass + type: object + x-expandableFields: + - billing_address + - shipping_address + payment_method_card_wallet_samsung_pay: + description: '' + properties: {} + title: payment_method_card_wallet_samsung_pay + type: object + x-expandableFields: [] + payment_method_card_wallet_visa_checkout: + description: '' + properties: + billing_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified billing address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + email: + description: Owner's verified email. Values are verified or provided by + the wallet directly (if supported) at the time of authorization or settlement. + They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + name: + description: Owner's verified full name. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + shipping_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified shipping address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + title: payment_method_card_wallet_visa_checkout + type: object + x-expandableFields: + - billing_address + - shipping_address + payment_method_details: + description: '' + properties: + ach_credit_transfer: + "$ref": "#/components/schemas/payment_method_details_ach_credit_transfer" + ach_debit: + "$ref": "#/components/schemas/payment_method_details_ach_debit" + acss_debit: + "$ref": "#/components/schemas/payment_method_details_acss_debit" + afterpay_clearpay: + "$ref": "#/components/schemas/payment_method_details_afterpay_clearpay" + alipay: + "$ref": "#/components/schemas/payment_flows_private_payment_methods_alipay_details" + au_becs_debit: + "$ref": "#/components/schemas/payment_method_details_au_becs_debit" + bacs_debit: + "$ref": "#/components/schemas/payment_method_details_bacs_debit" + bancontact: + "$ref": "#/components/schemas/payment_method_details_bancontact" + boleto: + "$ref": "#/components/schemas/payment_method_details_boleto" + card: + "$ref": "#/components/schemas/payment_method_details_card" + card_present: + "$ref": "#/components/schemas/payment_method_details_card_present" + eps: + "$ref": "#/components/schemas/payment_method_details_eps" + fpx: + "$ref": "#/components/schemas/payment_method_details_fpx" + giropay: + "$ref": "#/components/schemas/payment_method_details_giropay" + grabpay: + "$ref": "#/components/schemas/payment_method_details_grabpay" + ideal: + "$ref": "#/components/schemas/payment_method_details_ideal" + interac_present: + "$ref": "#/components/schemas/payment_method_details_interac_present" + klarna: + "$ref": "#/components/schemas/payment_method_details_klarna" + multibanco: + "$ref": "#/components/schemas/payment_method_details_multibanco" + oxxo: + "$ref": "#/components/schemas/payment_method_details_oxxo" + p24: + "$ref": "#/components/schemas/payment_method_details_p24" + sepa_debit: + "$ref": "#/components/schemas/payment_method_details_sepa_debit" + sofort: + "$ref": "#/components/schemas/payment_method_details_sofort" + stripe_account: + "$ref": "#/components/schemas/payment_method_details_stripe_account" + type: + description: |- + The type of transaction-specific details of the payment method used in the payment, one of `ach_credit_transfer`, `ach_debit`, `acss_debit`, `alipay`, `au_becs_debit`, `bancontact`, `card`, `card_present`, `eps`, `giropay`, `ideal`, `klarna`, `multibanco`, `p24`, `sepa_debit`, `sofort`, `stripe_account`, or `wechat`. + An additional hash is included on `payment_method_details` with a name matching this value. + It contains information specific to the payment method. + maxLength: 5000 + type: string + wechat: + "$ref": "#/components/schemas/payment_method_details_wechat" + wechat_pay: + "$ref": "#/components/schemas/payment_method_details_wechat_pay" + required: + - type + title: payment_method_details + type: object + x-expandableFields: + - ach_credit_transfer + - ach_debit + - acss_debit + - afterpay_clearpay + - alipay + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - card_present + - eps + - fpx + - giropay + - grabpay + - ideal + - interac_present + - klarna + - multibanco + - oxxo + - p24 + - sepa_debit + - sofort + - stripe_account + - wechat + - wechat_pay + payment_method_details_ach_credit_transfer: + description: '' + properties: + account_number: + description: Account number to transfer funds to. + maxLength: 5000 + nullable: true + type: string + bank_name: + description: Name of the bank associated with the routing number. + maxLength: 5000 + nullable: true + type: string + routing_number: + description: Routing transit number for the bank account to transfer funds + to. + maxLength: 5000 + nullable: true + type: string + swift_code: + description: SWIFT code of the bank associated with the routing number. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_ach_credit_transfer + type: object + x-expandableFields: [] + payment_method_details_ach_debit: + description: '' + properties: + account_holder_type: + description: Type of entity that holds the account. This can be either `individual` + or `company`. + enum: + - company + - individual + nullable: true + type: string + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country the bank account + is located in. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + routing_number: + description: Routing transit number of the bank account. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_ach_debit + type: object + x-expandableFields: [] + payment_method_details_acss_debit: + description: '' + properties: + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + institution_number: + description: Institution number of the bank account + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + mandate: + description: ID of the mandate used to make this payment. + maxLength: 5000 + type: string + transit_number: + description: Transit number of the bank account. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_acss_debit + type: object + x-expandableFields: [] + payment_method_details_afterpay_clearpay: + description: '' + properties: + reference: + description: Order identifier shown to the merchant in Afterpay’s online + portal. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_afterpay_clearpay + type: object + x-expandableFields: [] + payment_method_details_au_becs_debit: + description: '' + properties: + bsb_number: + description: Bank-State-Branch number of the bank account. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + mandate: + description: ID of the mandate used to make this payment. + maxLength: 5000 + type: string + title: payment_method_details_au_becs_debit + type: object + x-expandableFields: [] + payment_method_details_bacs_debit: + description: '' + properties: + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four digits of the bank account number. + maxLength: 5000 + nullable: true + type: string + mandate: + description: ID of the mandate used to make this payment. + maxLength: 5000 + nullable: true + type: string + sort_code: + description: Sort code of the bank account. (e.g., `10-20-30`) + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_bacs_debit + type: object + x-expandableFields: [] + payment_method_details_bancontact: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bic: + description: Bank Identifier Code of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + generated_sepa_debit: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the SEPA Direct Debit PaymentMethod which was generated + by this Charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + generated_sepa_debit_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: The mandate for the SEPA Direct Debit PaymentMethod which was + generated by this Charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + iban_last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + preferred_language: + description: |- + Preferred language of the Bancontact authorization page that the customer is redirected to. + Can be one of `en`, `de`, `fr`, or `nl` + enum: + - de + - en + - fr + - nl + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by Bancontact directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_bancontact + type: object + x-expandableFields: + - generated_sepa_debit + - generated_sepa_debit_mandate + payment_method_details_boleto: + description: '' + properties: + tax_id: + description: Uniquely identifies this customer tax_id (CNPJ or CPF) + maxLength: 5000 + type: string + required: + - tax_id + title: payment_method_details_boleto + type: object + x-expandableFields: [] + payment_method_details_card: + description: '' + properties: + brand: + description: Card brand. Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, + `unionpay`, `visa`, or `unknown`. + maxLength: 5000 + nullable: true + type: string + checks: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_card_checks" + description: Check results by Card networks on Card address and CVC at time + of payment. + nullable: true + country: + description: Two-letter ISO code representing the country of the card. You + could use this attribute to get a sense of the international breakdown + of cards you've collected. + maxLength: 5000 + nullable: true + type: string + exp_month: + description: Two-digit number representing the card's expiration month. + type: integer + exp_year: + description: Four-digit number representing the card's expiration year. + type: integer + fingerprint: + description: |- + Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + + *Starting May 1, 2021, card fingerprint in India for Connect will change to allow two fingerprints for the same card --- one for India and one for the rest of the world.* + maxLength: 5000 + nullable: true + type: string + funding: + description: Card funding type. Can be `credit`, `debit`, `prepaid`, or + `unknown`. + maxLength: 5000 + nullable: true + type: string + installments: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_card_installments" + description: |- + Installment details for this payment (Mexico only). + + For more information, see the [installments integration guide](https://stripe.com/docs/payments/installments). + nullable: true + last4: + description: The last four digits of the card. + maxLength: 5000 + nullable: true + type: string + network: + description: Identifies which network this charge was processed on. Can + be `amex`, `cartes_bancaires`, `diners`, `discover`, `interac`, `jcb`, + `mastercard`, `unionpay`, `visa`, or `unknown`. + maxLength: 5000 + nullable: true + type: string + three_d_secure: + anyOf: + - "$ref": "#/components/schemas/three_d_secure_details" + description: Populated if this transaction used 3D Secure authentication. + nullable: true + wallet: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_card_wallet" + description: If this Card is part of a card wallet, this contains the details + of the card wallet. + nullable: true + required: + - exp_month + - exp_year + title: payment_method_details_card + type: object + x-expandableFields: + - checks + - installments + - three_d_secure + - wallet + payment_method_details_card_checks: + description: '' + properties: + address_line1_check: + description: If a address line1 was provided, results of the check, one + of `pass`, `fail`, `unavailable`, or `unchecked`. + maxLength: 5000 + nullable: true + type: string + address_postal_code_check: + description: If a address postal code was provided, results of the check, + one of `pass`, `fail`, `unavailable`, or `unchecked`. + maxLength: 5000 + nullable: true + type: string + cvc_check: + description: If a CVC was provided, results of the check, one of `pass`, + `fail`, `unavailable`, or `unchecked`. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_card_checks + type: object + x-expandableFields: [] + payment_method_details_card_installments: + description: '' + properties: + plan: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_card_installments_plan" + description: Installment plan selected for the payment. + nullable: true + title: payment_method_details_card_installments + type: object + x-expandableFields: + - plan + payment_method_details_card_installments_plan: + description: '' + properties: + count: + description: For `fixed_count` installment plans, this is the number of + installment payments your customer will make to their credit card. + nullable: true + type: integer + interval: + description: |- + For `fixed_count` installment plans, this is the interval between installment payments your customer will make to their credit card. + One of `month`. + enum: + - month + nullable: true + type: string + type: + description: Type of installment plan, one of `fixed_count`. + enum: + - fixed_count + type: string + required: + - type + title: payment_method_details_card_installments_plan + type: object + x-expandableFields: [] + payment_method_details_card_present: + description: '' + properties: + brand: + description: Card brand. Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, + `unionpay`, `visa`, or `unknown`. + maxLength: 5000 + nullable: true + type: string + cardholder_name: + description: The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) + format. May include alphanumeric characters, special characters and first/last + name separator (`/`). + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country of the card. You + could use this attribute to get a sense of the international breakdown + of cards you've collected. + maxLength: 5000 + nullable: true + type: string + emv_auth_data: + description: Authorization response cryptogram. + maxLength: 5000 + nullable: true + type: string + exp_month: + description: Two-digit number representing the card's expiration month. + type: integer + exp_year: + description: Four-digit number representing the card's expiration year. + type: integer + fingerprint: + description: |- + Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + + *Starting May 1, 2021, card fingerprint in India for Connect will change to allow two fingerprints for the same card --- one for India and one for the rest of the world.* + maxLength: 5000 + nullable: true + type: string + funding: + description: Card funding type. Can be `credit`, `debit`, `prepaid`, or + `unknown`. + maxLength: 5000 + nullable: true + type: string + generated_card: + description: ID of a card PaymentMethod generated from the card_present + PaymentMethod that may be attached to a Customer for future transactions. + Only present if it was possible to generate a card PaymentMethod. + maxLength: 5000 + nullable: true + type: string + last4: + description: The last four digits of the card. + maxLength: 5000 + nullable: true + type: string + network: + description: Identifies which network this charge was processed on. Can + be `amex`, `cartes_bancaires`, `diners`, `discover`, `interac`, `jcb`, + `mastercard`, `unionpay`, `visa`, or `unknown`. + maxLength: 5000 + nullable: true + type: string + read_method: + description: How card details were read in this transaction. + enum: + - contact_emv + - contactless_emv + - contactless_magstripe_mode + - magnetic_stripe_fallback + - magnetic_stripe_track2 + nullable: true + type: string + receipt: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_card_present_receipt" + description: A collection of fields required to be displayed on receipts. + Only required for EMV transactions. + nullable: true + required: + - exp_month + - exp_year + title: payment_method_details_card_present + type: object + x-expandableFields: + - receipt + payment_method_details_card_present_receipt: + description: '' + properties: + account_type: + description: The type of account being debited or credited + enum: + - checking + - credit + - prepaid + - unknown + type: string + x-stripeBypassValidation: true + application_cryptogram: + description: EMV tag 9F26, cryptogram generated by the integrated circuit + chip. + maxLength: 5000 + nullable: true + type: string + application_preferred_name: + description: Mnenomic of the Application Identifier. + maxLength: 5000 + nullable: true + type: string + authorization_code: + description: Identifier for this transaction. + maxLength: 5000 + nullable: true + type: string + authorization_response_code: + description: EMV tag 8A. A code returned by the card issuer. + maxLength: 5000 + nullable: true + type: string + cardholder_verification_method: + description: How the cardholder verified ownership of the card. + maxLength: 5000 + nullable: true + type: string + dedicated_file_name: + description: EMV tag 84. Similar to the application identifier stored on + the integrated circuit chip. + maxLength: 5000 + nullable: true + type: string + terminal_verification_results: + description: The outcome of a series of EMV functions performed by the card + reader. + maxLength: 5000 + nullable: true + type: string + transaction_status_information: + description: An indication of various EMV functions performed during the + transaction. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_card_present_receipt + type: object + x-expandableFields: [] + payment_method_details_card_wallet: + description: '' + properties: + amex_express_checkout: + "$ref": "#/components/schemas/payment_method_details_card_wallet_amex_express_checkout" + apple_pay: + "$ref": "#/components/schemas/payment_method_details_card_wallet_apple_pay" + dynamic_last4: + description: "(For tokenized numbers only.) The last four digits of the + device account number." + maxLength: 5000 + nullable: true + type: string + google_pay: + "$ref": "#/components/schemas/payment_method_details_card_wallet_google_pay" + masterpass: + "$ref": "#/components/schemas/payment_method_details_card_wallet_masterpass" + samsung_pay: + "$ref": "#/components/schemas/payment_method_details_card_wallet_samsung_pay" + type: + description: The type of the card wallet, one of `amex_express_checkout`, + `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, or `visa_checkout`. + An additional hash is included on the Wallet subhash with a name matching + this value. It contains additional information specific to the card wallet + type. + enum: + - amex_express_checkout + - apple_pay + - google_pay + - masterpass + - samsung_pay + - visa_checkout + type: string + visa_checkout: + "$ref": "#/components/schemas/payment_method_details_card_wallet_visa_checkout" + required: + - type + title: payment_method_details_card_wallet + type: object + x-expandableFields: + - amex_express_checkout + - apple_pay + - google_pay + - masterpass + - samsung_pay + - visa_checkout + payment_method_details_card_wallet_amex_express_checkout: + description: '' + properties: {} + title: payment_method_details_card_wallet_amex_express_checkout + type: object + x-expandableFields: [] + payment_method_details_card_wallet_apple_pay: + description: '' + properties: {} + title: payment_method_details_card_wallet_apple_pay + type: object + x-expandableFields: [] + payment_method_details_card_wallet_google_pay: + description: '' + properties: {} + title: payment_method_details_card_wallet_google_pay + type: object + x-expandableFields: [] + payment_method_details_card_wallet_masterpass: + description: '' + properties: + billing_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified billing address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + email: + description: Owner's verified email. Values are verified or provided by + the wallet directly (if supported) at the time of authorization or settlement. + They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + name: + description: Owner's verified full name. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + shipping_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified shipping address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + title: payment_method_details_card_wallet_masterpass + type: object + x-expandableFields: + - billing_address + - shipping_address + payment_method_details_card_wallet_samsung_pay: + description: '' + properties: {} + title: payment_method_details_card_wallet_samsung_pay + type: object + x-expandableFields: [] + payment_method_details_card_wallet_visa_checkout: + description: '' + properties: + billing_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified billing address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + email: + description: Owner's verified email. Values are verified or provided by + the wallet directly (if supported) at the time of authorization or settlement. + They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + name: + description: Owner's verified full name. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + shipping_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's verified shipping address. Values are verified or provided + by the wallet directly (if supported) at the time of authorization or + settlement. They cannot be set or mutated. + nullable: true + title: payment_method_details_card_wallet_visa_checkout + type: object + x-expandableFields: + - billing_address + - shipping_address + payment_method_details_eps: + description: '' + properties: + bank: + description: The customer's bank. Should be one of `arzte_und_apotheker_bank`, + `austrian_anadi_bank_ag`, `bank_austria`, `bankhaus_carl_spangler`, `bankhaus_schelhammer_und_schattera_ag`, + `bawag_psk_ag`, `bks_bank_ag`, `brull_kallmus_bank_ag`, `btv_vier_lander_bank`, + `capital_bank_grawe_gruppe_ag`, `dolomitenbank`, `easybank_ag`, `erste_bank_und_sparkassen`, + `hypo_alpeadriabank_international_ag`, `hypo_noe_lb_fur_niederosterreich_u_wien`, + `hypo_oberosterreich_salzburg_steiermark`, `hypo_tirol_bank_ag`, `hypo_vorarlberg_bank_ag`, + `hypo_bank_burgenland_aktiengesellschaft`, `marchfelder_bank`, `oberbank_ag`, + `raiffeisen_bankengruppe_osterreich`, `schoellerbank_ag`, `sparda_bank_wien`, + `volksbank_gruppe`, `volkskreditbank_ag`, or `vr_bank_braunau`. + enum: + - arzte_und_apotheker_bank + - austrian_anadi_bank_ag + - bank_austria + - bankhaus_carl_spangler + - bankhaus_schelhammer_und_schattera_ag + - bawag_psk_ag + - bks_bank_ag + - brull_kallmus_bank_ag + - btv_vier_lander_bank + - capital_bank_grawe_gruppe_ag + - dolomitenbank + - easybank_ag + - erste_bank_und_sparkassen + - hypo_alpeadriabank_international_ag + - hypo_bank_burgenland_aktiengesellschaft + - hypo_noe_lb_fur_niederosterreich_u_wien + - hypo_oberosterreich_salzburg_steiermark + - hypo_tirol_bank_ag + - hypo_vorarlberg_bank_ag + - marchfelder_bank + - oberbank_ag + - raiffeisen_bankengruppe_osterreich + - schoellerbank_ag + - sparda_bank_wien + - volksbank_gruppe + - volkskreditbank_ag + - vr_bank_braunau + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by EPS directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + EPS rarely provides this information so the attribute is usually empty. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_eps + type: object + x-expandableFields: [] + payment_method_details_fpx: + description: '' + properties: + bank: + description: The customer's bank. Can be one of `affin_bank`, `alliance_bank`, + `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, + `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, + `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, or `pb_enterprise`. + enum: + - affin_bank + - alliance_bank + - ambank + - bank_islam + - bank_muamalat + - bank_rakyat + - bsn + - cimb + - deutsche_bank + - hong_leong_bank + - hsbc + - kfh + - maybank2e + - maybank2u + - ocbc + - pb_enterprise + - public_bank + - rhb + - standard_chartered + - uob + type: string + transaction_id: + description: Unique transaction id generated by FPX for every request from + the merchant + maxLength: 5000 + nullable: true + type: string + required: + - bank + title: payment_method_details_fpx + type: object + x-expandableFields: [] + payment_method_details_giropay: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bic: + description: Bank Identifier Code of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by Giropay directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Giropay rarely provides this information so the attribute is usually empty. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_giropay + type: object + x-expandableFields: [] + payment_method_details_grabpay: + description: '' + properties: + transaction_id: + description: Unique transaction id generated by GrabPay + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_grabpay + type: object + x-expandableFields: [] + payment_method_details_ideal: + description: '' + properties: + bank: + description: The customer's bank. Can be one of `abn_amro`, `asn_bank`, + `bunq`, `handelsbanken`, `ing`, `knab`, `moneyou`, `rabobank`, `regiobank`, + `revolut`, `sns_bank`, `triodos_bank`, or `van_lanschot`. + enum: + - abn_amro + - asn_bank + - bunq + - handelsbanken + - ing + - knab + - moneyou + - rabobank + - regiobank + - revolut + - sns_bank + - triodos_bank + - van_lanschot + nullable: true + type: string + bic: + description: The Bank Identifier Code of the customer's bank. + enum: + - ABNANL2A + - ASNBNL21 + - BUNQNL2A + - FVLBNL22 + - HANDNL2A + - INGBNL2A + - KNABNL2H + - MOYONL21 + - RABONL2U + - RBRBNL21 + - REVOLT21 + - SNSBNL2A + - TRIONL2U + nullable: true + type: string + generated_sepa_debit: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the SEPA Direct Debit PaymentMethod which was generated + by this Charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + generated_sepa_debit_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: The mandate for the SEPA Direct Debit PaymentMethod which was + generated by this Charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + iban_last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by iDEAL directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_ideal + type: object + x-expandableFields: + - generated_sepa_debit + - generated_sepa_debit_mandate + payment_method_details_interac_present: + description: '' + properties: + brand: + description: Card brand. Can be `interac`, `mastercard` or `visa`. + maxLength: 5000 + nullable: true + type: string + cardholder_name: + description: The cardholder name as read from the card, in [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) + format. May include alphanumeric characters, special characters and first/last + name separator (`/`). + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country of the card. You + could use this attribute to get a sense of the international breakdown + of cards you've collected. + maxLength: 5000 + nullable: true + type: string + emv_auth_data: + description: Authorization response cryptogram. + maxLength: 5000 + nullable: true + type: string + exp_month: + description: Two-digit number representing the card's expiration month. + type: integer + exp_year: + description: Four-digit number representing the card's expiration year. + type: integer + fingerprint: + description: |- + Uniquely identifies this particular card number. You can use this attribute to check whether two customers who’ve signed up with you are using the same card number, for example. For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + + *Starting May 1, 2021, card fingerprint in India for Connect will change to allow two fingerprints for the same card --- one for India and one for the rest of the world.* + maxLength: 5000 + nullable: true + type: string + funding: + description: Card funding type. Can be `credit`, `debit`, `prepaid`, or + `unknown`. + maxLength: 5000 + nullable: true + type: string + generated_card: + description: ID of a card PaymentMethod generated from the card_present + PaymentMethod that may be attached to a Customer for future transactions. + Only present if it was possible to generate a card PaymentMethod. + maxLength: 5000 + nullable: true + type: string + last4: + description: The last four digits of the card. + maxLength: 5000 + nullable: true + type: string + network: + description: Identifies which network this charge was processed on. Can + be `amex`, `cartes_bancaires`, `diners`, `discover`, `interac`, `jcb`, + `mastercard`, `unionpay`, `visa`, or `unknown`. + maxLength: 5000 + nullable: true + type: string + preferred_locales: + description: EMV tag 5F2D. Preferred languages specified by the integrated + circuit chip. + items: + maxLength: 5000 + type: string + nullable: true + type: array + read_method: + description: How card details were read in this transaction. + enum: + - contact_emv + - contactless_emv + - contactless_magstripe_mode + - magnetic_stripe_fallback + - magnetic_stripe_track2 + nullable: true + type: string + receipt: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_interac_present_receipt" + description: A collection of fields required to be displayed on receipts. + Only required for EMV transactions. + nullable: true + required: + - exp_month + - exp_year + title: payment_method_details_interac_present + type: object + x-expandableFields: + - receipt + payment_method_details_interac_present_receipt: + description: '' + properties: + account_type: + description: The type of account being debited or credited + enum: + - checking + - savings + - unknown + type: string + x-stripeBypassValidation: true + application_cryptogram: + description: EMV tag 9F26, cryptogram generated by the integrated circuit + chip. + maxLength: 5000 + nullable: true + type: string + application_preferred_name: + description: Mnenomic of the Application Identifier. + maxLength: 5000 + nullable: true + type: string + authorization_code: + description: Identifier for this transaction. + maxLength: 5000 + nullable: true + type: string + authorization_response_code: + description: EMV tag 8A. A code returned by the card issuer. + maxLength: 5000 + nullable: true + type: string + cardholder_verification_method: + description: How the cardholder verified ownership of the card. + maxLength: 5000 + nullable: true + type: string + dedicated_file_name: + description: EMV tag 84. Similar to the application identifier stored on + the integrated circuit chip. + maxLength: 5000 + nullable: true + type: string + terminal_verification_results: + description: The outcome of a series of EMV functions performed by the card + reader. + maxLength: 5000 + nullable: true + type: string + transaction_status_information: + description: An indication of various EMV functions performed during the + transaction. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_interac_present_receipt + type: object + x-expandableFields: [] + payment_method_details_klarna: + description: '' + properties: {} + title: payment_method_details_klarna + type: object + x-expandableFields: [] + payment_method_details_multibanco: + description: '' + properties: + entity: + description: Entity number associated with this Multibanco payment. + maxLength: 5000 + nullable: true + type: string + reference: + description: Reference number associated with this Multibanco payment. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_multibanco + type: object + x-expandableFields: [] + payment_method_details_oxxo: + description: '' + properties: + number: + description: OXXO reference number + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_oxxo + type: object + x-expandableFields: [] + payment_method_details_p24: + description: '' + properties: + bank: + description: The customer's bank. Can be one of `ing`, `citi_handlowy`, + `tmobile_usbugi_bankowe`, `plus_bank`, `etransfer_pocztowy24`, `banki_spbdzielcze`, + `bank_nowy_bfg_sa`, `getin_bank`, `blik`, `noble_pay`, `ideabank`, `envelobank`, + `santander_przelew24`, `nest_przelew`, `mbank_mtransfer`, `inteligo`, + `pbac_z_ipko`, `bnp_paribas`, `credit_agricole`, `toyota_bank`, `bank_pekao_sa`, + `volkswagen_bank`, `bank_millennium`, `alior_bank`, or `boz`. + enum: + - alior_bank + - bank_millennium + - bank_nowy_bfg_sa + - bank_pekao_sa + - banki_spbdzielcze + - blik + - bnp_paribas + - boz + - citi_handlowy + - credit_agricole + - envelobank + - etransfer_pocztowy24 + - getin_bank + - ideabank + - ing + - inteligo + - mbank_mtransfer + - nest_przelew + - noble_pay + - pbac_z_ipko + - plus_bank + - santander_przelew24 + - tmobile_usbugi_bankowe + - toyota_bank + - volkswagen_bank + nullable: true + type: string + reference: + description: Unique reference for this Przelewy24 payment. + maxLength: 5000 + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by Przelewy24 directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + Przelewy24 rarely provides this information so the attribute is usually empty. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_p24 + type: object + x-expandableFields: [] + payment_method_details_sepa_debit: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + branch_code: + description: Branch code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country the bank account + is located in. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + mandate: + description: ID of the mandate used to make this payment. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_sepa_debit + type: object + x-expandableFields: [] + payment_method_details_sofort: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bic: + description: Bank Identifier Code of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country the bank account + is located in. + maxLength: 5000 + nullable: true + type: string + generated_sepa_debit: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the SEPA Direct Debit PaymentMethod which was generated + by this Charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + generated_sepa_debit_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: The mandate for the SEPA Direct Debit PaymentMethod which was + generated by this Charge. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + iban_last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + preferred_language: + description: |- + Preferred language of the SOFORT authorization page that the customer is redirected to. + Can be one of `de`, `en`, `es`, `fr`, `it`, `nl`, or `pl` + enum: + - de + - en + - es + - fr + - it + - nl + - pl + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by SOFORT directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_sofort + type: object + x-expandableFields: + - generated_sepa_debit + - generated_sepa_debit_mandate + payment_method_details_stripe_account: + description: '' + properties: {} + title: payment_method_details_stripe_account + type: object + x-expandableFields: [] + payment_method_details_wechat: + description: '' + properties: {} + title: payment_method_details_wechat + type: object + x-expandableFields: [] + payment_method_details_wechat_pay: + description: '' + properties: + fingerprint: + description: Uniquely identifies this particular WeChat Pay account. You + can use this attribute to check whether two WeChat accounts are the same. + maxLength: 5000 + nullable: true + type: string + transaction_id: + description: Transaction ID of this particular WeChat Pay transaction. + maxLength: 5000 + nullable: true + type: string + title: payment_method_details_wechat_pay + type: object + x-expandableFields: [] + payment_method_eps: + description: '' + properties: + bank: + description: The customer's bank. Should be one of `arzte_und_apotheker_bank`, + `austrian_anadi_bank_ag`, `bank_austria`, `bankhaus_carl_spangler`, `bankhaus_schelhammer_und_schattera_ag`, + `bawag_psk_ag`, `bks_bank_ag`, `brull_kallmus_bank_ag`, `btv_vier_lander_bank`, + `capital_bank_grawe_gruppe_ag`, `dolomitenbank`, `easybank_ag`, `erste_bank_und_sparkassen`, + `hypo_alpeadriabank_international_ag`, `hypo_noe_lb_fur_niederosterreich_u_wien`, + `hypo_oberosterreich_salzburg_steiermark`, `hypo_tirol_bank_ag`, `hypo_vorarlberg_bank_ag`, + `hypo_bank_burgenland_aktiengesellschaft`, `marchfelder_bank`, `oberbank_ag`, + `raiffeisen_bankengruppe_osterreich`, `schoellerbank_ag`, `sparda_bank_wien`, + `volksbank_gruppe`, `volkskreditbank_ag`, or `vr_bank_braunau`. + enum: + - arzte_und_apotheker_bank + - austrian_anadi_bank_ag + - bank_austria + - bankhaus_carl_spangler + - bankhaus_schelhammer_und_schattera_ag + - bawag_psk_ag + - bks_bank_ag + - brull_kallmus_bank_ag + - btv_vier_lander_bank + - capital_bank_grawe_gruppe_ag + - dolomitenbank + - easybank_ag + - erste_bank_und_sparkassen + - hypo_alpeadriabank_international_ag + - hypo_bank_burgenland_aktiengesellschaft + - hypo_noe_lb_fur_niederosterreich_u_wien + - hypo_oberosterreich_salzburg_steiermark + - hypo_tirol_bank_ag + - hypo_vorarlberg_bank_ag + - marchfelder_bank + - oberbank_ag + - raiffeisen_bankengruppe_osterreich + - schoellerbank_ag + - sparda_bank_wien + - volksbank_gruppe + - volkskreditbank_ag + - vr_bank_braunau + nullable: true + type: string + title: payment_method_eps + type: object + x-expandableFields: [] + payment_method_fpx: + description: '' + properties: + bank: + description: The customer's bank, if provided. Can be one of `affin_bank`, + `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, + `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, + `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, + or `pb_enterprise`. + enum: + - affin_bank + - alliance_bank + - ambank + - bank_islam + - bank_muamalat + - bank_rakyat + - bsn + - cimb + - deutsche_bank + - hong_leong_bank + - hsbc + - kfh + - maybank2e + - maybank2u + - ocbc + - pb_enterprise + - public_bank + - rhb + - standard_chartered + - uob + type: string + required: + - bank + title: payment_method_fpx + type: object + x-expandableFields: [] + payment_method_giropay: + description: '' + properties: {} + title: payment_method_giropay + type: object + x-expandableFields: [] + payment_method_grabpay: + description: '' + properties: {} + title: payment_method_grabpay + type: object + x-expandableFields: [] + payment_method_ideal: + description: '' + properties: + bank: + description: The customer's bank, if provided. Can be one of `abn_amro`, + `asn_bank`, `bunq`, `handelsbanken`, `ing`, `knab`, `moneyou`, `rabobank`, + `regiobank`, `revolut`, `sns_bank`, `triodos_bank`, or `van_lanschot`. + enum: + - abn_amro + - asn_bank + - bunq + - handelsbanken + - ing + - knab + - moneyou + - rabobank + - regiobank + - revolut + - sns_bank + - triodos_bank + - van_lanschot + nullable: true + type: string + bic: + description: The Bank Identifier Code of the customer's bank, if the bank + was provided. + enum: + - ABNANL2A + - ASNBNL21 + - BUNQNL2A + - FVLBNL22 + - HANDNL2A + - INGBNL2A + - KNABNL2H + - MOYONL21 + - RABONL2U + - RBRBNL21 + - REVOLT21 + - SNSBNL2A + - TRIONL2U + nullable: true + type: string + title: payment_method_ideal + type: object + x-expandableFields: [] + payment_method_interac_present: + description: '' + properties: {} + title: payment_method_interac_present + type: object + x-expandableFields: [] + payment_method_options_afterpay_clearpay: + description: '' + properties: + reference: + description: |- + Order identifier shown to the merchant in Afterpay’s online portal. We recommend using a value that helps you answer any questions a customer might have about + the payment. The identifier is limited to 128 characters and may contain only letters, digits, underscores, backslashes and dashes. + maxLength: 5000 + nullable: true + type: string + title: payment_method_options_afterpay_clearpay + type: object + x-expandableFields: [] + payment_method_options_alipay: + description: '' + properties: {} + title: payment_method_options_alipay + type: object + x-expandableFields: [] + payment_method_options_bancontact: + description: '' + properties: + preferred_language: + description: Preferred language of the Bancontact authorization page that + the customer is redirected to. + enum: + - de + - en + - fr + - nl + type: string + required: + - preferred_language + title: payment_method_options_bancontact + type: object + x-expandableFields: [] + payment_method_options_boleto: + description: '' + properties: + expires_after_days: + description: The number of calendar days before a Boleto voucher expires. + For example, if you create a Boleto voucher on Monday and you set expires_after_days + to 2, the Boleto voucher will expire on Wednesday at 23:59 America/Sao_Paulo + time. + type: integer + required: + - expires_after_days + title: payment_method_options_boleto + type: object + x-expandableFields: [] + payment_method_options_card_installments: + description: '' + properties: + available_plans: + description: Installment plans that may be selected for this PaymentIntent. + items: + "$ref": "#/components/schemas/payment_method_details_card_installments_plan" + nullable: true + type: array + enabled: + description: Whether Installments are enabled for this PaymentIntent. + type: boolean + plan: + anyOf: + - "$ref": "#/components/schemas/payment_method_details_card_installments_plan" + description: Installment plan selected for this PaymentIntent. + nullable: true + required: + - enabled + title: payment_method_options_card_installments + type: object + x-expandableFields: + - available_plans + - plan + payment_method_options_card_present: + description: '' + properties: {} + title: payment_method_options_card_present + type: object + x-expandableFields: [] + payment_method_options_ideal: + description: '' + properties: {} + title: payment_method_options_ideal + type: object + x-expandableFields: [] + payment_method_options_oxxo: + description: '' + properties: + expires_after_days: + description: The number of calendar days before an OXXO invoice expires. + For example, if you create an OXXO invoice on Monday and you set expires_after_days + to 2, the OXXO invoice will expire on Wednesday at 23:59 America/Mexico_City + time. + type: integer + required: + - expires_after_days + title: payment_method_options_oxxo + type: object + x-expandableFields: [] + payment_method_options_p24: + description: '' + properties: {} + title: payment_method_options_p24 + type: object + x-expandableFields: [] + payment_method_options_sofort: + description: '' + properties: + preferred_language: + description: Preferred language of the SOFORT authorization page that the + customer is redirected to. + enum: + - de + - en + - es + - fr + - it + - nl + - pl + nullable: true + type: string + title: payment_method_options_sofort + type: object + x-expandableFields: [] + payment_method_options_wechat_pay: + description: '' + properties: + app_id: + description: The app ID registered with WeChat Pay. Only required when client + is ios or android. + maxLength: 5000 + nullable: true + type: string + client: + description: The client type that the end customer will pay from + enum: + - android + - ios + - web + nullable: true + type: string + x-stripeBypassValidation: true + title: payment_method_options_wechat_pay + type: object + x-expandableFields: [] + payment_method_oxxo: + description: '' + properties: {} + title: payment_method_oxxo + type: object + x-expandableFields: [] + payment_method_p24: + description: '' + properties: + bank: + description: The customer's bank, if provided. + enum: + - alior_bank + - bank_millennium + - bank_nowy_bfg_sa + - bank_pekao_sa + - banki_spbdzielcze + - blik + - bnp_paribas + - boz + - citi_handlowy + - credit_agricole + - envelobank + - etransfer_pocztowy24 + - getin_bank + - ideabank + - ing + - inteligo + - mbank_mtransfer + - nest_przelew + - noble_pay + - pbac_z_ipko + - plus_bank + - santander_przelew24 + - tmobile_usbugi_bankowe + - toyota_bank + - volkswagen_bank + nullable: true + type: string + title: payment_method_p24 + type: object + x-expandableFields: [] + payment_method_sepa_debit: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + branch_code: + description: Branch code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country the bank account + is located in. + maxLength: 5000 + nullable: true + type: string + fingerprint: + description: Uniquely identifies this particular bank account. You can use + this attribute to check whether two bank accounts are the same. + maxLength: 5000 + nullable: true + type: string + generated_from: + anyOf: + - "$ref": "#/components/schemas/sepa_debit_generated_from" + description: Information about the object that generated this PaymentMethod. + nullable: true + last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + title: payment_method_sepa_debit + type: object + x-expandableFields: + - generated_from + payment_method_sofort: + description: '' + properties: + country: + description: Two-letter ISO code representing the country the bank account + is located in. + maxLength: 5000 + nullable: true + type: string + title: payment_method_sofort + type: object + x-expandableFields: [] + payment_method_wechat_pay: + description: '' + properties: {} + title: payment_method_wechat_pay + type: object + x-expandableFields: [] + payment_pages_checkout_session_automatic_tax: + description: '' + properties: + enabled: + description: Indicates whether automatic tax is enabled for the session + type: boolean + status: + description: The status of the most recent automated tax calculation for + this session. + enum: + - complete + - failed + - requires_location_inputs + nullable: true + type: string + required: + - enabled + title: PaymentPagesCheckoutSessionAutomaticTax + type: object + x-expandableFields: [] + payment_pages_checkout_session_customer_details: + description: '' + properties: + email: + description: The customer’s email at time of checkout. + maxLength: 5000 + nullable: true + type: string + tax_exempt: + description: The customer’s tax exempt status at time of checkout. + enum: + - exempt + - none + - reverse + nullable: true + type: string + tax_ids: + description: The customer’s tax IDs at time of checkout. + items: + "$ref": "#/components/schemas/payment_pages_checkout_session_tax_id" + nullable: true + type: array + title: PaymentPagesCheckoutSessionCustomerDetails + type: object + x-expandableFields: + - tax_ids + payment_pages_checkout_session_tax_id: + description: '' + properties: + type: + description: The type of the tax ID, one of `eu_vat`, `br_cnpj`, `br_cpf`, + `gb_vat`, `nz_gst`, `au_abn`, `au_arn`, `in_gst`, `no_vat`, `za_vat`, + `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ru_kpp`, `ca_bn`, `hk_br`, `es_cif`, + `tw_vat`, `th_vat`, `jp_cn`, `jp_rn`, `li_uid`, `my_itn`, `us_ein`, `kr_brn`, + `ca_qst`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, `my_sst`, + `sg_gst`, `ae_trn`, `cl_tin`, `sa_vat`, `id_npwp`, `my_frp`, `il_vat`, + or `unknown` + enum: + - ae_trn + - au_abn + - au_arn + - br_cnpj + - br_cpf + - ca_bn + - ca_gst_hst + - ca_pst_bc + - ca_pst_mb + - ca_pst_sk + - ca_qst + - ch_vat + - cl_tin + - es_cif + - eu_vat + - gb_vat + - hk_br + - id_npwp + - il_vat + - in_gst + - jp_cn + - jp_rn + - kr_brn + - li_uid + - mx_rfc + - my_frp + - my_itn + - my_sst + - no_vat + - nz_gst + - ru_inn + - ru_kpp + - sa_vat + - sg_gst + - sg_uen + - th_vat + - tw_vat + - unknown + - us_ein + - za_vat + type: string + value: + description: The value of the tax ID. + maxLength: 5000 + nullable: true + type: string + required: + - type + title: PaymentPagesCheckoutSessionTaxID + type: object + x-expandableFields: [] + payment_pages_checkout_session_tax_id_collection: + description: '' + properties: + enabled: + description: Indicates whether tax ID collection is enabled for the session + type: boolean + required: + - enabled + title: PaymentPagesCheckoutSessionTaxIDCollection + type: object + x-expandableFields: [] + payment_pages_checkout_session_total_details: + description: '' + properties: + amount_discount: + description: This is the sum of all the line item discounts. + type: integer + amount_shipping: + description: This is the sum of all the line item shipping amounts. + nullable: true + type: integer + amount_tax: + description: This is the sum of all the line item tax amounts. + type: integer + breakdown: + "$ref": "#/components/schemas/payment_pages_checkout_session_total_details_resource_breakdown" + required: + - amount_discount + - amount_tax + title: PaymentPagesCheckoutSessionTotalDetails + type: object + x-expandableFields: + - breakdown + payment_pages_checkout_session_total_details_resource_breakdown: + description: '' + properties: + discounts: + description: The aggregated line item discounts. + items: + "$ref": "#/components/schemas/line_items_discount_amount" + type: array + taxes: + description: The aggregated line item tax amounts by rate. + items: + "$ref": "#/components/schemas/line_items_tax_amount" + type: array + required: + - discounts + - taxes + title: PaymentPagesCheckoutSessionTotalDetailsResourceBreakdown + type: object + x-expandableFields: + - discounts + - taxes + payment_pages_payment_page_resources_shipping_address_collection: + description: '' + properties: + allowed_countries: + description: |- + An array of two-letter ISO country codes representing which countries Checkout should provide as options for + shipping locations. Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. + items: + enum: + - AC + - AD + - AE + - AF + - AG + - AI + - AL + - AM + - AO + - AQ + - AR + - AT + - AU + - AW + - AX + - AZ + - BA + - BB + - BD + - BE + - BF + - BG + - BH + - BI + - BJ + - BL + - BM + - BN + - BO + - BQ + - BR + - BS + - BT + - BV + - BW + - BY + - BZ + - CA + - CD + - CF + - CG + - CH + - CI + - CK + - CL + - CM + - CN + - CO + - CR + - CV + - CW + - CY + - CZ + - DE + - DJ + - DK + - DM + - DO + - DZ + - EC + - EE + - EG + - EH + - ER + - ES + - ET + - FI + - FJ + - FK + - FO + - FR + - GA + - GB + - GD + - GE + - GF + - GG + - GH + - GI + - GL + - GM + - GN + - GP + - GQ + - GR + - GS + - GT + - GU + - GW + - GY + - HK + - HN + - HR + - HT + - HU + - ID + - IE + - IL + - IM + - IN + - IO + - IQ + - IS + - IT + - JE + - JM + - JO + - JP + - KE + - KG + - KH + - KI + - KM + - KN + - KR + - KW + - KY + - KZ + - LA + - LB + - LC + - LI + - LK + - LR + - LS + - LT + - LU + - LV + - LY + - MA + - MC + - MD + - ME + - MF + - MG + - MK + - ML + - MM + - MN + - MO + - MQ + - MR + - MS + - MT + - MU + - MV + - MW + - MX + - MY + - MZ + - NA + - NC + - NE + - NG + - NI + - NL + - 'NO' + - NP + - NR + - NU + - NZ + - OM + - PA + - PE + - PF + - PG + - PH + - PK + - PL + - PM + - PN + - PR + - PS + - PT + - PY + - QA + - RE + - RO + - RS + - RU + - RW + - SA + - SB + - SC + - SE + - SG + - SH + - SI + - SJ + - SK + - SL + - SM + - SN + - SO + - SR + - SS + - ST + - SV + - SX + - SZ + - TA + - TC + - TD + - TF + - TG + - TH + - TJ + - TK + - TL + - TM + - TN + - TO + - TR + - TT + - TV + - TW + - TZ + - UA + - UG + - US + - UY + - UZ + - VA + - VC + - VE + - VG + - VN + - VU + - WF + - WS + - XK + - YE + - YT + - ZA + - ZM + - ZW + - ZZ + type: string + type: array + required: + - allowed_countries + title: PaymentPagesPaymentPageResourcesShippingAddressCollection + type: object + x-expandableFields: [] + payment_source: + anyOf: + - "$ref": "#/components/schemas/account" + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + title: Polymorphic + x-resourceId: payment_source + payout: + description: |- + A `Payout` object is created when you receive funds from Stripe, or when you + initiate a payout to either a bank account or debit card of a [connected + Stripe account](/docs/connect/bank-debit-card-payouts). You can retrieve individual payouts, + as well as list all payouts. Payouts are made on [varying + schedules](/docs/connect/manage-payout-schedule), depending on your country and + industry. + + Related guide: [Receiving Payouts](https://stripe.com/docs/payouts). + properties: + amount: + description: Amount (in %s) to be transferred to your bank account or debit + card. + type: integer + arrival_date: + description: Date the payout is expected to arrive in the bank. This factors + in delays like weekends or bank holidays. + format: unix-time + type: integer + automatic: + description: Returns `true` if the payout was created by an [automated payout + schedule](https://stripe.com/docs/payouts#payout-schedule), and `false` + if it was [requested manually](https://stripe.com/docs/payouts#manual-payouts). + type: boolean + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: ID of the balance transaction that describes the impact of + this payout on your account balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/deleted_bank_account" + - "$ref": "#/components/schemas/deleted_card" + description: ID of the bank account or card the payout was sent to. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/deleted_bank_account" + - "$ref": "#/components/schemas/deleted_card" + failure_balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: If the payout failed or was canceled, this will be the ID of + the balance transaction that reversed the initial balance transaction, + and puts the funds from the failed payout back in your balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + failure_code: + description: Error code explaining reason for payout failure if available. + See [Types of payout failures](https://stripe.com/docs/api#payout_failures) + for a list of failure codes. + maxLength: 5000 + nullable: true + type: string + failure_message: + description: Message to user further explaining reason for payout failure + if available. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + method: + description: The method used to send this payout, which can be `standard` + or `instant`. `instant` is only supported for payouts to debit cards. + (See [Instant payouts for marketplaces](https://stripe.com/blog/instant-payouts-for-marketplaces) + for more information.) + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - payout + type: string + original_payout: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payout" + description: If the payout reverses another, this is the ID of the original + payout. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payout" + reversed_by: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payout" + description: If the payout was reversed, this is the ID of the payout that + reverses this payout. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payout" + source_type: + description: The source balance this payout came from. One of `card`, `fpx`, + or `bank_account`. + maxLength: 5000 + type: string + statement_descriptor: + description: Extra information about a payout to be displayed on the user's + bank statement. + maxLength: 5000 + nullable: true + type: string + status: + description: 'Current status of the payout: `paid`, `pending`, `in_transit`, + `canceled` or `failed`. A payout is `pending` until it is submitted to + the bank, when it becomes `in_transit`. The status then changes to `paid` + if the transaction goes through, or to `failed` or `canceled` (within + 5 business days). Some failed payouts may initially show as `paid` but + then change to `failed`.' + maxLength: 5000 + type: string + type: + description: Can be `bank_account` or `card`. + enum: + - bank_account + - card + type: string + required: + - amount + - arrival_date + - automatic + - created + - currency + - id + - livemode + - method + - object + - source_type + - status + - type + title: Payout + type: object + x-expandableFields: + - balance_transaction + - destination + - failure_balance_transaction + - original_payout + - reversed_by + x-resourceId: payout + period: + description: '' + properties: + end: + description: The end date of this usage period. All usage up to and including + this point in time is included. + format: unix-time + nullable: true + type: integer + start: + description: The start date of this usage period. All usage after this point + in time is included. + format: unix-time + nullable: true + type: integer + title: Period + type: object + x-expandableFields: [] + person: + description: |- + This is an object representing a person associated with a Stripe account. + + A platform cannot access a Standard or Express account's persons after the account starts onboarding, such as after generating an account link for the account. + See the [Standard onboarding](https://stripe.com/docs/connect/standard-accounts) or [Express onboarding documentation](https://stripe.com/docs/connect/express-accounts) for information about platform pre-filling and account onboarding steps. + + Related guide: [Handling Identity Verification with the API](https://stripe.com/docs/connect/identity-verification-api#person-information). + properties: + account: + description: The account the person is associated with. + maxLength: 5000 + type: string + address: + "$ref": "#/components/schemas/address" + address_kana: + anyOf: + - "$ref": "#/components/schemas/legal_entity_japan_address" + nullable: true + address_kanji: + anyOf: + - "$ref": "#/components/schemas/legal_entity_japan_address" + nullable: true + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + dob: + "$ref": "#/components/schemas/legal_entity_dob" + email: + description: The person's email address. + maxLength: 5000 + nullable: true + type: string + first_name: + description: The person's first name. + maxLength: 5000 + nullable: true + type: string + first_name_kana: + description: The Kana variation of the person's first name (Japan only). + maxLength: 5000 + nullable: true + type: string + first_name_kanji: + description: The Kanji variation of the person's first name (Japan only). + maxLength: 5000 + nullable: true + type: string + gender: + description: The person's gender (International regulations require either + "male" or "female"). + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + id_number_provided: + description: Whether the person's `id_number` was provided. + type: boolean + last_name: + description: The person's last name. + maxLength: 5000 + nullable: true + type: string + last_name_kana: + description: The Kana variation of the person's last name (Japan only). + maxLength: 5000 + nullable: true + type: string + last_name_kanji: + description: The Kanji variation of the person's last name (Japan only). + maxLength: 5000 + nullable: true + type: string + maiden_name: + description: The person's maiden name. + maxLength: 5000 + nullable: true + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + nationality: + description: The country where the person is a national. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - person + type: string + phone: + description: The person's phone number. + maxLength: 5000 + nullable: true + type: string + political_exposure: + description: Indicates if the person or any of their representatives, family + members, or other closely related persons, declares that they hold or + have held an important public job or function, in any jurisdiction. + enum: + - existing + - none + type: string + relationship: + "$ref": "#/components/schemas/person_relationship" + requirements: + anyOf: + - "$ref": "#/components/schemas/person_requirements" + nullable: true + ssn_last_4_provided: + description: Whether the last four digits of the person's Social Security + number have been provided (U.S. only). + type: boolean + verification: + "$ref": "#/components/schemas/legal_entity_person_verification" + required: + - account + - created + - id + - object + title: Person + type: object + x-expandableFields: + - address + - address_kana + - address_kanji + - dob + - relationship + - requirements + - verification + x-resourceId: person + person_relationship: + description: '' + properties: + director: + description: Whether the person is a director of the account's legal entity. + Currently only required for accounts in the EU. Directors are typically + members of the governing board of the company, or responsible for ensuring + the company meets its regulatory obligations. + nullable: true + type: boolean + executive: + description: Whether the person has significant responsibility to control, + manage, or direct the organization. + nullable: true + type: boolean + owner: + description: Whether the person is an owner of the account’s legal entity. + nullable: true + type: boolean + percent_ownership: + description: The percent owned by the person of the account's legal entity. + nullable: true + type: number + representative: + description: Whether the person is authorized as the primary representative + of the account. This is the person nominated by the business to provide + information about themselves, and general information about the account. + There can only be one representative at any given time. At the time the + account is created, this person should be set to the person responsible + for opening the account. + nullable: true + type: boolean + title: + description: The person's title (e.g., CEO, Support Engineer). + maxLength: 5000 + nullable: true + type: string + title: PersonRelationship + type: object + x-expandableFields: [] + person_requirements: + description: '' + properties: + currently_due: + description: Fields that need to be collected to keep the person's account + enabled. If not collected by the account's `current_deadline`, these fields + appear in `past_due` as well, and the account is disabled. + items: + maxLength: 5000 + type: string + type: array + errors: + description: Fields that are `currently_due` and need to be collected again + because validation or verification failed. + items: + "$ref": "#/components/schemas/account_requirements_error" + type: array + eventually_due: + description: Fields that need to be collected assuming all volume thresholds + are reached. As they become required, they appear in `currently_due` as + well, and the account's `current_deadline` becomes set. + items: + maxLength: 5000 + type: string + type: array + past_due: + description: Fields that weren't collected by the account's `current_deadline`. + These fields need to be collected to enable the person's account. + items: + maxLength: 5000 + type: string + type: array + pending_verification: + description: Fields that may become required depending on the results of + verification or review. Will be an empty array unless an asynchronous + verification is pending. If verification fails, these fields move to `eventually_due`, + `currently_due`, or `past_due`. + items: + maxLength: 5000 + type: string + type: array + required: + - currently_due + - errors + - eventually_due + - past_due + - pending_verification + title: PersonRequirements + type: object + x-expandableFields: + - errors + plan: + description: |- + You can now model subscriptions more flexibly using the [Prices API](https://stripe.com/docs/api#prices). It replaces the Plans API and is backwards compatible to simplify your migration. + + Plans define the base price, currency, and billing cycle for recurring purchases of products. + [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and plans help you track pricing. Different physical goods or levels of service should be represented by products, and pricing options should be represented by plans. This approach lets you change prices without having to change your provisioning scheme. + + For example, you might have a single "gold" product that has plans for $10/month, $100/year, €9/month, and €90/year. + + Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription) and more about [products and prices](https://stripe.com/docs/billing/prices-guide). + properties: + active: + description: Whether the plan can be used for new purchases. + type: boolean + aggregate_usage: + description: Specifies a usage aggregation strategy for plans of `usage_type=metered`. + Allowed values are `sum` for summing up all usage during a period, `last_during_period` + for using the last usage record reported within a period, `last_ever` + for using the last usage record ever (across period bounds) or `max` which + uses the usage record with the maximum reported usage during a period. + Defaults to `sum`. + enum: + - last_during_period + - last_ever + - max + - sum + nullable: true + type: string + amount: + description: The unit amount in %s to be charged, represented as a whole + integer if possible. Only set if `billing_scheme=per_unit`. + nullable: true + type: integer + amount_decimal: + description: The unit amount in %s to be charged, represented as a decimal + string with at most 12 decimal places. Only set if `billing_scheme=per_unit`. + format: decimal + nullable: true + type: string + billing_scheme: + description: Describes how to compute the price per period. Either `per_unit` + or `tiered`. `per_unit` indicates that the fixed amount (specified in + `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), + or per unit of total usage (for plans with `usage_type=metered`). `tiered` + indicates that the unit pricing will be computed using a tiering strategy + as defined using the `tiers` and `tiers_mode` attributes. + enum: + - per_unit + - tiered + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + interval: + description: The frequency at which a subscription is billed. One of `day`, + `week`, `month` or `year`. + enum: + - day + - month + - week + - year + type: string + interval_count: + description: The number of intervals (specified in the `interval` attribute) + between subscription billings. For example, `interval=month` and `interval_count=3` + bills every 3 months. + type: integer + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + nickname: + description: A brief description of the plan, hidden from customers. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - plan + type: string + product: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/product" + - "$ref": "#/components/schemas/deleted_product" + description: The product whose pricing this plan determines. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/product" + - "$ref": "#/components/schemas/deleted_product" + tiers: + description: Each element represents a pricing tier. This parameter requires + `billing_scheme` to be set to `tiered`. See also the documentation for + `billing_scheme`. + items: + "$ref": "#/components/schemas/plan_tier" + type: array + tiers_mode: + description: Defines if the tiering price should be `graduated` or `volume` + based. In `volume`-based tiering, the maximum quantity within a period + determines the per unit price. In `graduated` tiering, pricing can change + as the quantity grows. + enum: + - graduated + - volume + nullable: true + type: string + transform_usage: + anyOf: + - "$ref": "#/components/schemas/transform_usage" + description: Apply a transformation to the reported usage or set quantity + before computing the amount billed. Cannot be combined with `tiers`. + nullable: true + trial_period_days: + description: Default number of trial days when subscribing a customer to + this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + nullable: true + type: integer + usage_type: + description: Configures how the quantity per period should be determined. + Can be either `metered` or `licensed`. `licensed` automatically bills + the `quantity` set when adding it to a subscription. `metered` aggregates + the total usage based on usage records. Defaults to `licensed`. + enum: + - licensed + - metered + type: string + required: + - active + - billing_scheme + - created + - currency + - id + - interval + - interval_count + - livemode + - object + - usage_type + title: Plan + type: object + x-expandableFields: + - product + - tiers + - transform_usage + x-resourceId: plan + plan_tier: + description: '' + properties: + flat_amount: + description: Price for the entire tier. + nullable: true + type: integer + flat_amount_decimal: + description: Same as `flat_amount`, but contains a decimal value with at + most 12 decimal places. + format: decimal + nullable: true + type: string + unit_amount: + description: Per unit price for units relevant to the tier. + nullable: true + type: integer + unit_amount_decimal: + description: Same as `unit_amount`, but contains a decimal value with at + most 12 decimal places. + format: decimal + nullable: true + type: string + up_to: + description: Up to and including to this quantity will be contained in the + tier. + nullable: true + type: integer + title: PlanTier + type: object + x-expandableFields: [] + platform_tax_fee: + description: '' + properties: + account: + description: The Connected account that incurred this charge. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - platform_tax_fee + type: string + source_transaction: + description: The payment object that caused this tax to be inflicted. + maxLength: 5000 + type: string + type: + description: The type of tax (VAT). + maxLength: 5000 + type: string + required: + - account + - id + - object + - source_transaction + - type + title: PlatformTax + type: object + x-expandableFields: [] + portal_business_profile: + description: '' + properties: + headline: + description: The messaging shown to customers in the portal. + maxLength: 5000 + nullable: true + type: string + privacy_policy_url: + description: A link to the business’s publicly available privacy policy. + maxLength: 5000 + type: string + terms_of_service_url: + description: A link to the business’s publicly available terms of service. + maxLength: 5000 + type: string + required: + - privacy_policy_url + - terms_of_service_url + title: PortalBusinessProfile + type: object + x-expandableFields: [] + portal_customer_update: + description: '' + properties: + allowed_updates: + description: The types of customer updates that are supported. When empty, + customers are not updateable. + items: + enum: + - address + - email + - phone + - shipping + - tax_id + type: string + type: array + enabled: + description: Whether the feature is enabled. + type: boolean + required: + - allowed_updates + - enabled + title: PortalCustomerUpdate + type: object + x-expandableFields: [] + portal_features: + description: '' + properties: + customer_update: + "$ref": "#/components/schemas/portal_customer_update" + invoice_history: + "$ref": "#/components/schemas/portal_invoice_list" + payment_method_update: + "$ref": "#/components/schemas/portal_payment_method_update" + subscription_cancel: + "$ref": "#/components/schemas/portal_subscription_cancel" + subscription_pause: + "$ref": "#/components/schemas/portal_subscription_pause" + subscription_update: + "$ref": "#/components/schemas/portal_subscription_update" + required: + - customer_update + - invoice_history + - payment_method_update + - subscription_cancel + - subscription_pause + - subscription_update + title: PortalFeatures + type: object + x-expandableFields: + - customer_update + - invoice_history + - payment_method_update + - subscription_cancel + - subscription_pause + - subscription_update + portal_invoice_list: + description: '' + properties: + enabled: + description: Whether the feature is enabled. + type: boolean + required: + - enabled + title: PortalInvoiceList + type: object + x-expandableFields: [] + portal_payment_method_update: + description: '' + properties: + enabled: + description: Whether the feature is enabled. + type: boolean + required: + - enabled + title: PortalPaymentMethodUpdate + type: object + x-expandableFields: [] + portal_subscription_cancel: + description: '' + properties: + cancellation_reason: + "$ref": "#/components/schemas/portal_subscription_cancellation_reason" + enabled: + description: Whether the feature is enabled. + type: boolean + mode: + description: Whether to cancel subscriptions immediately or at the end of + the billing period. + enum: + - at_period_end + - immediately + type: string + proration_behavior: + description: Whether to create prorations when canceling subscriptions. + Possible values are `none` and `create_prorations`. + enum: + - always_invoice + - create_prorations + - none + type: string + required: + - enabled + - mode + - proration_behavior + title: PortalSubscriptionCancel + type: object + x-expandableFields: + - cancellation_reason + portal_subscription_cancellation_reason: + description: '' + properties: + enabled: + description: Whether the feature is enabled. + type: boolean + options: + description: Which cancellation reasons will be given as options to the + customer. + items: + enum: + - customer_service + - low_quality + - missing_features + - other + - switched_service + - too_complex + - too_expensive + - unused + type: string + type: array + required: + - enabled + - options + title: PortalSubscriptionCancellationReason + type: object + x-expandableFields: [] + portal_subscription_pause: + description: '' + properties: + enabled: + description: Whether the feature is enabled. + type: boolean + required: + - enabled + title: PortalSubscriptionPause + type: object + x-expandableFields: [] + portal_subscription_update: + description: '' + properties: + default_allowed_updates: + description: The types of subscription updates that are supported for items + listed in the `products` attribute. When empty, subscriptions are not + updateable. + items: + enum: + - price + - promotion_code + - quantity + type: string + type: array + enabled: + description: Whether the feature is enabled. + type: boolean + products: + description: The list of products that support subscription updates. + items: + "$ref": "#/components/schemas/portal_subscription_update_product" + nullable: true + type: array + proration_behavior: + description: Determines how to handle prorations resulting from subscription + updates. Valid values are `none`, `create_prorations`, and `always_invoice`. + enum: + - always_invoice + - create_prorations + - none + type: string + required: + - default_allowed_updates + - enabled + - proration_behavior + title: PortalSubscriptionUpdate + type: object + x-expandableFields: + - products + portal_subscription_update_product: + description: '' + properties: + prices: + description: The list of price IDs which, when subscribed to, a subscription + can be updated. + items: + maxLength: 5000 + type: string + type: array + product: + description: The product ID. + maxLength: 5000 + type: string + required: + - prices + - product + title: PortalSubscriptionUpdateProduct + type: object + x-expandableFields: [] + price: + description: |- + Prices define the unit cost, currency, and (optional) billing cycle for both recurring and one-time purchases of products. + [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and prices help you track payment terms. Different physical goods or levels of service should be represented by products, and pricing options should be represented by prices. This approach lets you change prices without having to change your provisioning scheme. + + For example, you might have a single "gold" product that has prices for $10/month, $100/year, and €9 once. + + Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription), [create an invoice](https://stripe.com/docs/billing/invoices/create), and more about [products and prices](https://stripe.com/docs/billing/prices-guide). + properties: + active: + description: Whether the price can be used for new purchases. + type: boolean + billing_scheme: + description: Describes how to compute the price per period. Either `per_unit` + or `tiered`. `per_unit` indicates that the fixed amount (specified in + `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` + (for prices with `usage_type=licensed`), or per unit of total usage (for + prices with `usage_type=metered`). `tiered` indicates that the unit pricing + will be computed using a tiering strategy as defined using the `tiers` + and `tiers_mode` attributes. + enum: + - per_unit + - tiered + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + lookup_key: + description: A lookup key used to retrieve prices dynamically from a static + string. + maxLength: 5000 + nullable: true + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + nickname: + description: A brief description of the price, hidden from customers. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - price + type: string + product: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/product" + - "$ref": "#/components/schemas/deleted_product" + description: The ID of the product this price is associated with. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/product" + - "$ref": "#/components/schemas/deleted_product" + recurring: + anyOf: + - "$ref": "#/components/schemas/recurring" + description: The recurring components of a price such as `interval` and + `usage_type`. + nullable: true + tax_behavior: + description: Specifies whether the price is considered inclusive of taxes + or exclusive of taxes. One of `inclusive`, `exclusive`, or `unspecified`. + Once specified as either `inclusive` or `exclusive`, it cannot be changed. + enum: + - exclusive + - inclusive + - unspecified + nullable: true + type: string + tiers: + description: Each element represents a pricing tier. This parameter requires + `billing_scheme` to be set to `tiered`. See also the documentation for + `billing_scheme`. + items: + "$ref": "#/components/schemas/price_tier" + type: array + tiers_mode: + description: Defines if the tiering price should be `graduated` or `volume` + based. In `volume`-based tiering, the maximum quantity within a period + determines the per unit price. In `graduated` tiering, pricing can change + as the quantity grows. + enum: + - graduated + - volume + nullable: true + type: string + transform_quantity: + anyOf: + - "$ref": "#/components/schemas/transform_quantity" + description: Apply a transformation to the reported usage or set quantity + before computing the amount billed. Cannot be combined with `tiers`. + nullable: true + type: + description: One of `one_time` or `recurring` depending on whether the price + is for a one-time purchase or a recurring (subscription) purchase. + enum: + - one_time + - recurring + type: string + unit_amount: + description: The unit amount in %s to be charged, represented as a whole + integer if possible. Only set if `billing_scheme=per_unit`. + nullable: true + type: integer + unit_amount_decimal: + description: The unit amount in %s to be charged, represented as a decimal + string with at most 12 decimal places. Only set if `billing_scheme=per_unit`. + format: decimal + nullable: true + type: string + required: + - active + - billing_scheme + - created + - currency + - id + - livemode + - metadata + - object + - product + - type + title: Price + type: object + x-expandableFields: + - product + - recurring + - tiers + - transform_quantity + x-resourceId: price + price_tier: + description: '' + properties: + flat_amount: + description: Price for the entire tier. + nullable: true + type: integer + flat_amount_decimal: + description: Same as `flat_amount`, but contains a decimal value with at + most 12 decimal places. + format: decimal + nullable: true + type: string + unit_amount: + description: Per unit price for units relevant to the tier. + nullable: true + type: integer + unit_amount_decimal: + description: Same as `unit_amount`, but contains a decimal value with at + most 12 decimal places. + format: decimal + nullable: true + type: string + up_to: + description: Up to and including to this quantity will be contained in the + tier. + nullable: true + type: integer + title: PriceTier + type: object + x-expandableFields: [] + product: + description: |- + Products describe the specific goods or services you offer to your customers. + For example, you might offer a Standard and Premium version of your goods or service; each version would be a separate Product. + They can be used in conjunction with [Prices](https://stripe.com/docs/api#prices) to configure pricing in Checkout and Subscriptions. + + Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription) or accept [one-time payments with Checkout](https://stripe.com/docs/payments/checkout/client#create-products) and more about [Products and Prices](https://stripe.com/docs/billing/prices-guide) + properties: + active: + description: Whether the product is currently available for purchase. + type: boolean + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + description: + description: The product's description, meant to be displayable to the customer. + Use this field to optionally store a long form explanation of the product + being sold for your own rendering purposes. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + images: + description: A list of up to 8 URLs of images for this product, meant to + be displayable to the customer. + items: + maxLength: 5000 + type: string + type: array + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + name: + description: The product's name, meant to be displayable to the customer. + Whenever this product is sold via a subscription, name will show up on + associated invoice line item descriptions. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - product + type: string + package_dimensions: + anyOf: + - "$ref": "#/components/schemas/package_dimensions" + description: The dimensions of this product for shipping purposes. + nullable: true + shippable: + description: Whether this product is shipped (i.e., physical goods). + nullable: true + type: boolean + statement_descriptor: + description: Extra information about a product which will appear on your + customer's credit card statement. In the case that multiple products are + billed at once, the first statement descriptor will be used. + maxLength: 5000 + nullable: true + type: string + tax_code: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/tax_code" + description: A [tax code](https://stripe.com/docs/tax/tax-codes) ID. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/tax_code" + unit_label: + description: A label that represents units of this product in Stripe and + on customers’ receipts and invoices. When set, this will be included in + associated invoice line item descriptions. + maxLength: 5000 + nullable: true + type: string + updated: + description: Time at which the object was last updated. Measured in seconds + since the Unix epoch. + format: unix-time + type: integer + url: + description: A URL of a publicly-accessible webpage for this product. + maxLength: 2048 + nullable: true + type: string + required: + - active + - created + - id + - images + - livemode + - metadata + - name + - object + - updated + title: Product + type: object + x-expandableFields: + - package_dimensions + - tax_code + x-resourceId: product + promotion_code: + description: |- + A Promotion Code represents a customer-redeemable code for a coupon. It can be used to + create multiple codes for a single coupon. + properties: + active: + description: Whether the promotion code is currently active. A promotion + code is only active if the coupon is also valid. + type: boolean + code: + description: The customer-facing code. Regardless of case, this code must + be unique across all active promotion codes for each customer. + maxLength: 5000 + type: string + coupon: + "$ref": "#/components/schemas/coupon" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The customer that this promotion code can be used by. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + expires_at: + description: Date at which the promotion code can no longer be redeemed. + format: unix-time + nullable: true + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + max_redemptions: + description: Maximum number of times this promotion code can be redeemed. + nullable: true + type: integer + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - promotion_code + type: string + restrictions: + "$ref": "#/components/schemas/promotion_codes_resource_restrictions" + times_redeemed: + description: Number of times this promotion code has been used. + type: integer + required: + - active + - code + - coupon + - created + - id + - livemode + - object + - restrictions + - times_redeemed + title: PromotionCode + type: object + x-expandableFields: + - coupon + - customer + - restrictions + x-resourceId: promotion_code + promotion_codes_resource_restrictions: + description: '' + properties: + first_time_transaction: + description: A Boolean indicating if the Promotion Code should only be redeemed + for Customers without any successful payments or invoices + type: boolean + minimum_amount: + description: Minimum amount required to redeem this Promotion Code into + a Coupon (e.g., a purchase must be $100 or more to work). + nullable: true + type: integer + minimum_amount_currency: + description: Three-letter [ISO code](https://stripe.com/docs/currencies) + for minimum_amount + maxLength: 5000 + nullable: true + type: string + required: + - first_time_transaction + title: PromotionCodesResourceRestrictions + type: object + x-expandableFields: [] + quote: + description: |- + A Quote is a way to model prices that you'd like to provide to a customer. + Once accepted, it will automatically create an invoice, subscription or subscription schedule. + properties: + amount_subtotal: + description: Total before any discounts or taxes are applied. + type: integer + amount_total: + description: Total after discounts and taxes are applied. + type: integer + application_fee_amount: + description: The amount of the application fee (if any) that will be requested + to be applied to the payment and transferred to the application owner's + Stripe account. Only applicable if there are no line items with recurring + prices on the quote. + nullable: true + type: integer + application_fee_percent: + description: A non-negative decimal between 0 and 100, with at most two + decimal places. This represents the percentage of the subscription invoice + subtotal that will be transferred to the application owner's Stripe account. + Only applicable if there are line items with recurring prices on the quote. + nullable: true + type: number + automatic_tax: + "$ref": "#/components/schemas/quotes_resource_automatic_tax" + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When charging + automatically, Stripe will attempt to pay invoices at the end of the subscription + cycle or on finalization using the default payment method attached to + the subscription or customer. When sending an invoice, Stripe will email + your customer an invoice with payment instructions. Defaults to `charge_automatically`. + enum: + - charge_automatically + - send_invoice + type: string + computed: + "$ref": "#/components/schemas/quotes_resource_computed" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + maxLength: 5000 + nullable: true + type: string + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The customer which this quote belongs to. A customer is required + before finalizing the quote. Once specified, it cannot be changed. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + default_tax_rates: + description: The tax rates applied to this quote. + items: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/tax_rate" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/tax_rate" + type: array + description: + description: A description that will be displayed on the quote PDF. + maxLength: 5000 + nullable: true + type: string + discounts: + description: The discounts applied to this quote. + items: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/discount" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/discount" + type: array + expires_at: + description: The date on which the quote will be canceled if in `open` or + `draft` status. Measured in seconds since the Unix epoch. + format: unix-time + type: integer + footer: + description: A footer that will be displayed on the quote PDF. + maxLength: 5000 + nullable: true + type: string + from_quote: + anyOf: + - "$ref": "#/components/schemas/quotes_resource_from_quote" + description: Details of the quote that was cloned. See the [cloning documentation](https://stripe.com/docs/quotes/clone) + for more details. + nullable: true + header: + description: A header that will be displayed on the quote PDF. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + - "$ref": "#/components/schemas/deleted_invoice" + description: The invoice that was created from this quote. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + - "$ref": "#/components/schemas/deleted_invoice" + invoice_settings: + anyOf: + - "$ref": "#/components/schemas/invoice_setting_quote_setting" + description: All invoices will be billed using the specified settings. + nullable: true + line_items: + description: A list of items the customer is being quoted for. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: QuotesResourceListLineItems + type: object + x-expandableFields: + - data + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + number: + description: A unique number that identifies this particular quote. This + number is assigned once the quote is [finalized](https://stripe.com/docs/quotes/overview#finalize). + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - quote + type: string + on_behalf_of: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account on behalf of which to charge. See the [Connect + documentation](https://support.stripe.com/questions/sending-invoices-on-behalf-of-connected-accounts) + for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + status: + description: The status of the quote. + enum: + - accepted + - canceled + - draft + - open + type: string + status_transitions: + "$ref": "#/components/schemas/quotes_resource_status_transitions" + subscription: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription" + description: The subscription that was created or updated from this quote. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription" + subscription_data: + "$ref": "#/components/schemas/quotes_resource_subscription_data" + subscription_schedule: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription_schedule" + description: The subscription schedule that was created or updated from + this quote. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription_schedule" + total_details: + "$ref": "#/components/schemas/quotes_resource_total_details" + transfer_data: + anyOf: + - "$ref": "#/components/schemas/quotes_resource_transfer_data" + description: The account (if any) the payments will be attributed to for + tax reporting, and where funds from each payment will be transferred to + for each of the invoices. + nullable: true + required: + - amount_subtotal + - amount_total + - automatic_tax + - collection_method + - computed + - created + - discounts + - expires_at + - id + - livemode + - metadata + - object + - status + - status_transitions + - subscription_data + - total_details + title: Quote + type: object + x-expandableFields: + - automatic_tax + - computed + - customer + - default_tax_rates + - discounts + - from_quote + - invoice + - invoice_settings + - line_items + - on_behalf_of + - status_transitions + - subscription + - subscription_data + - subscription_schedule + - total_details + - transfer_data + x-resourceId: quote + quotes_resource_automatic_tax: + description: '' + properties: + enabled: + description: Automatically calculate taxes + type: boolean + status: + description: The status of the most recent automated tax calculation for + this quote. + enum: + - complete + - failed + - requires_location_inputs + nullable: true + type: string + required: + - enabled + title: QuotesResourceAutomaticTax + type: object + x-expandableFields: [] + quotes_resource_computed: + description: '' + properties: + recurring: + anyOf: + - "$ref": "#/components/schemas/quotes_resource_recurring" + description: The definitive totals and line items the customer will be charged + on a recurring basis. Takes into account the line items with recurring + prices and discounts with `duration=forever` coupons only. Defaults to + `null` if no inputted line items with recurring prices. + nullable: true + upfront: + "$ref": "#/components/schemas/quotes_resource_upfront" + required: + - upfront + title: QuotesResourceComputed + type: object + x-expandableFields: + - recurring + - upfront + quotes_resource_from_quote: + description: '' + properties: + is_revision: + description: Whether this quote is a revision of a different quote. + type: boolean + quote: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/quote" + description: The quote that was cloned. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/quote" + required: + - is_revision + - quote + title: QuotesResourceFromQuote + type: object + x-expandableFields: + - quote + quotes_resource_recurring: + description: '' + properties: + amount_subtotal: + description: Total before any discounts or taxes are applied. + type: integer + amount_total: + description: Total after discounts and taxes are applied. + type: integer + interval: + description: The frequency at which a subscription is billed. One of `day`, + `week`, `month` or `year`. + enum: + - day + - month + - week + - year + type: string + interval_count: + description: The number of intervals (specified in the `interval` attribute) + between subscription billings. For example, `interval=month` and `interval_count=3` + bills every 3 months. + type: integer + total_details: + "$ref": "#/components/schemas/quotes_resource_total_details" + required: + - amount_subtotal + - amount_total + - interval + - interval_count + - total_details + title: QuotesResourceRecurring + type: object + x-expandableFields: + - total_details + quotes_resource_status_transitions: + description: '' + properties: + accepted_at: + description: The time that the quote was accepted. Measured in seconds since + Unix epoch. + format: unix-time + nullable: true + type: integer + canceled_at: + description: The time that the quote was canceled. Measured in seconds since + Unix epoch. + format: unix-time + nullable: true + type: integer + finalized_at: + description: The time that the quote was finalized. Measured in seconds + since Unix epoch. + format: unix-time + nullable: true + type: integer + title: QuotesResourceStatusTransitions + type: object + x-expandableFields: [] + quotes_resource_subscription_data: + description: '' + properties: + effective_date: + description: When creating a new subscription, the date of which the subscription + schedule will start after the quote is accepted. This date is ignored + if it is in the past when the quote is accepted. Measured in seconds since + the Unix epoch. + format: unix-time + nullable: true + type: integer + trial_period_days: + description: Integer representing the number of trial period days before + the customer is charged for the first time. + nullable: true + type: integer + title: QuotesResourceSubscriptionData + type: object + x-expandableFields: [] + quotes_resource_total_details: + description: '' + properties: + amount_discount: + description: This is the sum of all the line item discounts. + type: integer + amount_shipping: + description: This is the sum of all the line item shipping amounts. + nullable: true + type: integer + amount_tax: + description: This is the sum of all the line item tax amounts. + type: integer + breakdown: + "$ref": "#/components/schemas/quotes_resource_total_details_resource_breakdown" + required: + - amount_discount + - amount_tax + title: QuotesResourceTotalDetails + type: object + x-expandableFields: + - breakdown + quotes_resource_total_details_resource_breakdown: + description: '' + properties: + discounts: + description: The aggregated line item discounts. + items: + "$ref": "#/components/schemas/line_items_discount_amount" + type: array + taxes: + description: The aggregated line item tax amounts by rate. + items: + "$ref": "#/components/schemas/line_items_tax_amount" + type: array + required: + - discounts + - taxes + title: QuotesResourceTotalDetailsResourceBreakdown + type: object + x-expandableFields: + - discounts + - taxes + quotes_resource_transfer_data: + description: '' + properties: + amount: + description: The amount in %s that will be transferred to the destination + account when the invoice is paid. By default, the entire amount is transferred + to the destination. + nullable: true + type: integer + amount_percent: + description: A non-negative decimal between 0 and 100, with at most two + decimal places. This represents the percentage of the subscription invoice + subtotal that will be transferred to the destination account. By default, + the entire amount will be transferred to the destination. + nullable: true + type: number + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account where funds from the payment will be transferred + to upon payment success. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + required: + - destination + title: QuotesResourceTransferData + type: object + x-expandableFields: + - destination + quotes_resource_upfront: + description: '' + properties: + amount_subtotal: + description: Total before any discounts or taxes are applied. + type: integer + amount_total: + description: Total after discounts and taxes are applied. + type: integer + line_items: + description: The line items that will appear on the next invoice after this + quote is accepted. This does not include pending invoice items that exist + on the customer but may still be included in the next invoice. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: QuotesResourceListLineItems + type: object + x-expandableFields: + - data + total_details: + "$ref": "#/components/schemas/quotes_resource_total_details" + required: + - amount_subtotal + - amount_total + - total_details + title: QuotesResourceUpfront + type: object + x-expandableFields: + - line_items + - total_details + radar.early_fraud_warning: + description: |- + An early fraud warning indicates that the card issuer has notified us that a + charge may be fraudulent. + + Related guide: [Early Fraud Warnings](https://stripe.com/docs/disputes/measuring#early-fraud-warnings). + properties: + actionable: + description: An EFW is actionable if it has not received a dispute and has + not been fully refunded. You may wish to proactively refund a charge that + receives an EFW, in order to avoid receiving a dispute later. + type: boolean + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the charge this early fraud warning is for, optionally + expanded. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + fraud_type: + description: The type of fraud labelled by the issuer. One of `card_never_received`, + `fraudulent_card_application`, `made_with_counterfeit_card`, `made_with_lost_card`, + `made_with_stolen_card`, `misc`, `unauthorized_use_of_card`. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - radar.early_fraud_warning + type: string + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: ID of the Payment Intent this early fraud warning is for, optionally + expanded. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + required: + - actionable + - charge + - created + - fraud_type + - id + - livemode + - object + title: RadarEarlyFraudWarning + type: object + x-expandableFields: + - charge + - payment_intent + x-resourceId: radar.early_fraud_warning + radar.value_list: + description: |- + Value lists allow you to group values together which can then be referenced in rules. + + Related guide: [Default Stripe Lists](https://stripe.com/docs/radar/lists#managing-list-items). + properties: + alias: + description: The name of the value list for use in rules. + maxLength: 5000 + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + created_by: + description: The name or email address of the user who created this value + list. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + item_type: + description: The type of items in the value list. One of `card_fingerprint`, + `card_bin`, `email`, `ip_address`, `country`, `string`, or `case_sensitive_string`. + enum: + - card_bin + - card_fingerprint + - case_sensitive_string + - country + - email + - ip_address + - string + type: string + list_items: + description: List of items contained within this value list. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/radar.value_list_item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: RadarListListItemList + type: object + x-expandableFields: + - data + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + name: + description: The name of the value list. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - radar.value_list + type: string + required: + - alias + - created + - created_by + - id + - item_type + - list_items + - livemode + - metadata + - name + - object + title: RadarListList + type: object + x-expandableFields: + - list_items + x-resourceId: radar.value_list + radar.value_list_item: + description: |- + Value list items allow you to add specific values to a given Radar value list, which can then be used in rules. + + Related guide: [Managing List Items](https://stripe.com/docs/radar/lists#managing-list-items). + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + created_by: + description: The name or email address of the user who added this item to + the value list. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - radar.value_list_item + type: string + value: + description: The value of the item. + maxLength: 5000 + type: string + value_list: + description: The identifier of the value list this item belongs to. + maxLength: 5000 + type: string + required: + - created + - created_by + - id + - livemode + - object + - value + - value_list + title: RadarListListItem + type: object + x-expandableFields: [] + x-resourceId: radar.value_list_item + radar_review_resource_location: + description: '' + properties: + city: + description: The city where the payment originated. + maxLength: 5000 + nullable: true + type: string + country: + description: Two-letter ISO code representing the country where the payment + originated. + maxLength: 5000 + nullable: true + type: string + latitude: + description: The geographic latitude where the payment originated. + nullable: true + type: number + longitude: + description: The geographic longitude where the payment originated. + nullable: true + type: number + region: + description: The state/county/province/region where the payment originated. + maxLength: 5000 + nullable: true + type: string + title: RadarReviewResourceLocation + type: object + x-expandableFields: [] + radar_review_resource_session: + description: '' + properties: + browser: + description: The browser used in this browser session (e.g., `Chrome`). + maxLength: 5000 + nullable: true + type: string + device: + description: Information about the device used for the browser session (e.g., + `Samsung SM-G930T`). + maxLength: 5000 + nullable: true + type: string + platform: + description: The platform for the browser session (e.g., `Macintosh`). + maxLength: 5000 + nullable: true + type: string + version: + description: The version for the browser session (e.g., `61.0.3163.100`). + maxLength: 5000 + nullable: true + type: string + title: RadarReviewResourceSession + type: object + x-expandableFields: [] + recipient: + description: |- + With `Recipient` objects, you can transfer money from your Stripe account to a + third-party bank account or debit card. The API allows you to create, delete, + and update your recipients. You can retrieve individual recipients as well as + a list of all your recipients. + + **`Recipient` objects have been deprecated in favor of + [Connect](https://stripe.com/docs/connect), specifically Connect's much more powerful + [Account objects](https://stripe.com/docs/api#account). Stripe accounts that don't already use + recipients can no longer begin doing so. Please use `Account` objects + instead.** + properties: + active_account: + anyOf: + - "$ref": "#/components/schemas/bank_account" + description: Hash describing the current account on the recipient, if there + is one. + nullable: true + cards: + description: '' + nullable: true + properties: + data: + items: + "$ref": "#/components/schemas/card" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: CardList + type: object + x-expandableFields: + - data + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + default_card: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/card" + description: The default card to use for creating transfers to this recipient. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/card" + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + email: + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + migrated_to: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: 'The ID of the [Custom account](https://stripe.com/docs/connect/custom-accounts) + this recipient was migrated to. If set, the recipient can no longer be + updated, nor can transfers be made to it: use the Custom account instead.' + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + name: + description: Full, legal name of the recipient. + maxLength: 5000 + nullable: true + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - recipient + type: string + rolled_back_from: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + type: + description: Type of the recipient, one of `individual` or `corporation`. + maxLength: 5000 + type: string + required: + - created + - id + - livemode + - metadata + - object + - type + title: TransferRecipient + type: object + x-expandableFields: + - active_account + - cards + - default_card + - migrated_to + - rolled_back_from + x-resourceId: recipient + recurring: + description: '' + properties: + aggregate_usage: + description: Specifies a usage aggregation strategy for prices of `usage_type=metered`. + Allowed values are `sum` for summing up all usage during a period, `last_during_period` + for using the last usage record reported within a period, `last_ever` + for using the last usage record ever (across period bounds) or `max` which + uses the usage record with the maximum reported usage during a period. + Defaults to `sum`. + enum: + - last_during_period + - last_ever + - max + - sum + nullable: true + type: string + interval: + description: The frequency at which a subscription is billed. One of `day`, + `week`, `month` or `year`. + enum: + - day + - month + - week + - year + type: string + interval_count: + description: The number of intervals (specified in the `interval` attribute) + between subscription billings. For example, `interval=month` and `interval_count=3` + bills every 3 months. + type: integer + usage_type: + description: Configures how the quantity per period should be determined. + Can be either `metered` or `licensed`. `licensed` automatically bills + the `quantity` set when adding it to a subscription. `metered` aggregates + the total usage based on usage records. Defaults to `licensed`. + enum: + - licensed + - metered + type: string + required: + - interval + - interval_count + - usage_type + title: Recurring + type: object + x-expandableFields: [] + refund: + description: |- + `Refund` objects allow you to refund a charge that has previously been created + but not yet refunded. Funds will be refunded to the credit or debit card that + was originally charged. + + Related guide: [Refunds](https://stripe.com/docs/refunds). + properties: + amount: + description: Amount, in %s. + type: integer + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: Balance transaction that describes the impact on your account + balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the charge that was refunded. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. (Available on non-card refunds only) + maxLength: 5000 + type: string + failure_balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: If the refund failed, this balance transaction describes the + adjustment made on your account balance that reverses the initial balance + transaction. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + failure_reason: + description: If the refund failed, the reason for refund failure if known. + Possible values are `lost_or_stolen_card`, `expired_or_canceled_card`, + or `unknown`. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - refund + type: string + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: ID of the PaymentIntent that was refunded. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + reason: + description: Reason for the refund, either user-provided (`duplicate`, `fraudulent`, + or `requested_by_customer`) or generated by Stripe internally (`expired_uncaptured_charge`). + maxLength: 5000 + nullable: true + type: string + receipt_number: + description: This is the transaction number that appears on email receipts + sent for this refund. + maxLength: 5000 + nullable: true + type: string + source_transfer_reversal: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/transfer_reversal" + description: The transfer reversal that is associated with the refund. Only + present if the charge came from another Stripe account. See the Connect + documentation for details. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/transfer_reversal" + status: + description: Status of the refund. For credit card refunds, this can be + `pending`, `succeeded`, or `failed`. For other types of refunds, it can + be `pending`, `succeeded`, `failed`, or `canceled`. Refer to our [refunds](https://stripe.com/docs/refunds#failed-refunds) + documentation for more details. + maxLength: 5000 + nullable: true + type: string + transfer_reversal: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/transfer_reversal" + description: If the accompanying transfer was reversed, the transfer reversal + object. Only applicable if the charge was created using the destination + parameter. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/transfer_reversal" + required: + - amount + - created + - currency + - id + - object + title: Refund + type: object + x-expandableFields: + - balance_transaction + - charge + - failure_balance_transaction + - payment_intent + - source_transfer_reversal + - transfer_reversal + x-resourceId: refund + reporting.report_run: + description: |- + The Report Run object represents an instance of a report type generated with + specific run parameters. Once the object is created, Stripe begins processing the report. + When the report has finished running, it will give you a reference to a file + where you can retrieve your results. For an overview, see + [API Access to Reports](https://stripe.com/docs/reporting/statements/api). + + Note that certain report types can only be run based on your live-mode data (not test-mode + data), and will error when queried without a [live-mode API key](https://stripe.com/docs/keys#test-live-modes). + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + error: + description: |- + If something should go wrong during the run, a message about the failure (populated when + `status=failed`). + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: "`true` if the report is run on live mode data and `false` + if it is run on test mode data." + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - reporting.report_run + type: string + parameters: + "$ref": "#/components/schemas/financial_reporting_finance_report_run_run_parameters" + report_type: + description: The ID of the [report type](https://stripe.com/docs/reports/report-types) + to run, such as `"balance.summary.1"`. + maxLength: 5000 + type: string + result: + anyOf: + - "$ref": "#/components/schemas/file" + description: |- + The file object representing the result of the report run (populated when + `status=succeeded`). + nullable: true + status: + description: |- + Status of this report run. This will be `pending` when the run is initially created. + When the run finishes, this will be set to `succeeded` and the `result` field will be populated. + Rarely, we may encounter an error, at which point this will be set to `failed` and the `error` field will be populated. + maxLength: 5000 + type: string + succeeded_at: + description: |- + Timestamp at which this run successfully finished (populated when + `status=succeeded`). Measured in seconds since the Unix epoch. + format: unix-time + nullable: true + type: integer + required: + - created + - id + - livemode + - object + - parameters + - report_type + - status + title: reporting_report_run + type: object + x-expandableFields: + - parameters + - result + x-resourceId: reporting.report_run + reporting.report_type: + description: |- + The Report Type resource corresponds to a particular type of report, such as + the "Activity summary" or "Itemized payouts" reports. These objects are + identified by an ID belonging to a set of enumerated values. See + [API Access to Reports documentation](https://stripe.com/docs/reporting/statements/api) + for those Report Type IDs, along with required and optional parameters. + + Note that certain report types can only be run based on your live-mode data (not test-mode + data), and will error when queried without a [live-mode API key](https://stripe.com/docs/keys#test-live-modes). + properties: + data_available_end: + description: Most recent time for which this Report Type is available. Measured + in seconds since the Unix epoch. + format: unix-time + type: integer + data_available_start: + description: Earliest time for which this Report Type is available. Measured + in seconds since the Unix epoch. + format: unix-time + type: integer + default_columns: + description: List of column names that are included by default when this + Report Type gets run. (If the Report Type doesn't support the `columns` + parameter, this will be null.) + items: + maxLength: 5000 + type: string + nullable: true + type: array + id: + description: The [ID of the Report Type](https://stripe.com/docs/reporting/statements/api#available-report-types), + such as `balance.summary.1`. + maxLength: 5000 + type: string + name: + description: Human-readable name of the Report Type + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - reporting.report_type + type: string + updated: + description: When this Report Type was latest updated. Measured in seconds + since the Unix epoch. + format: unix-time + type: integer + version: + description: Version of the Report Type. Different versions report with + the same ID will have the same purpose, but may take different run parameters + or have different result schemas. + type: integer + required: + - data_available_end + - data_available_start + - id + - name + - object + - updated + - version + title: reporting_report_type + type: object + x-expandableFields: [] + x-resourceId: reporting.report_type + reserve_transaction: + description: '' + properties: + amount: + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - reserve_transaction + type: string + required: + - amount + - currency + - id + - object + title: ReserveTransaction + type: object + x-expandableFields: [] + review: + description: |- + Reviews can be used to supplement automated fraud detection with human expertise. + + Learn more about [Radar](/radar) and reviewing payments + [here](https://stripe.com/docs/radar/reviews). + properties: + billing_zip: + description: The ZIP or postal code of the card used, if applicable. + maxLength: 5000 + nullable: true + type: string + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: The charge associated with this review. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + closed_reason: + description: The reason the review was closed, or null if it has not yet + been closed. One of `approved`, `refunded`, `refunded_as_fraud`, `disputed`, + or `redacted`. + enum: + - approved + - disputed + - redacted + - refunded + - refunded_as_fraud + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + ip_address: + description: The IP address where the payment originated. + maxLength: 5000 + nullable: true + type: string + ip_address_location: + anyOf: + - "$ref": "#/components/schemas/radar_review_resource_location" + description: Information related to the location of the payment. Note that + this information is an approximation and attempts to locate the nearest + population center - it should not be used to determine a specific address. + nullable: true + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - review + type: string + open: + description: If `true`, the review needs action. + type: boolean + opened_reason: + description: The reason the review was opened. One of `rule` or `manual`. + enum: + - manual + - rule + type: string + payment_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_intent" + description: The PaymentIntent ID associated with this review, if one exists. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_intent" + reason: + description: The reason the review is currently open or closed. One of `rule`, + `manual`, `approved`, `refunded`, `refunded_as_fraud`, `disputed`, or + `redacted`. + maxLength: 5000 + type: string + session: + anyOf: + - "$ref": "#/components/schemas/radar_review_resource_session" + description: Information related to the browsing session of the user who + initiated the payment. + nullable: true + required: + - created + - id + - livemode + - object + - open + - opened_reason + - reason + title: RadarReview + type: object + x-expandableFields: + - charge + - ip_address_location + - payment_intent + - session + x-resourceId: review + rule: + description: '' + properties: + action: + description: The action taken on the payment. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + predicate: + description: The predicate to evaluate the payment against. + maxLength: 5000 + type: string + required: + - action + - id + - predicate + title: RadarRule + type: object + x-expandableFields: [] + scheduled_query_run: + description: |- + If you have [scheduled a Sigma query](https://stripe.com/docs/sigma/scheduled-queries), you'll + receive a `sigma.scheduled_query_run.created` webhook each time the query + runs. The webhook contains a `ScheduledQueryRun` object, which you can use to + retrieve the query results. + properties: + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + data_load_time: + description: When the query was run, Sigma contained a snapshot of your + Stripe data at this time. + format: unix-time + type: integer + error: + "$ref": "#/components/schemas/sigma_scheduled_query_run_error" + file: + anyOf: + - "$ref": "#/components/schemas/file" + description: The file object representing the results of the query. + nullable: true + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - scheduled_query_run + type: string + result_available_until: + description: Time at which the result expires and is no longer available + for download. + format: unix-time + type: integer + sql: + description: SQL for the query. + maxLength: 100000 + type: string + status: + description: The query's execution status, which will be `completed` for + successful runs, and `canceled`, `failed`, or `timed_out` otherwise. + maxLength: 5000 + type: string + title: + description: Title of the query. + maxLength: 5000 + type: string + required: + - created + - data_load_time + - id + - livemode + - object + - result_available_until + - sql + - status + - title + title: ScheduledQueryRun + type: object + x-expandableFields: + - error + - file + x-resourceId: scheduled_query_run + schedules_phase_automatic_tax: + description: 'Automatic tax configuration details' + properties: + enabled: + description: Whether Stripe automatically computes tax on invoices created + during this phase. + type: boolean + required: + - enabled + title: SchedulesPhaseAutomaticTax + type: object + x-expandableFields: [] + sepa_debit_generated_from: + description: '' + properties: + charge: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: The ID of the Charge that generated this PaymentMethod, if + any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + setup_attempt: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/setup_attempt" + description: The ID of the SetupAttempt that generated this PaymentMethod, + if any. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/setup_attempt" + title: sepa_debit_generated_from + type: object + x-expandableFields: + - charge + - setup_attempt + setup_attempt: + description: |- + A SetupAttempt describes one attempted confirmation of a SetupIntent, + whether that confirmation was successful or unsuccessful. You can use + SetupAttempts to inspect details of a specific attempt at setting up a + payment method using a SetupIntent. + properties: + application: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application" + description: The value of [application](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-application) + on the SetupIntent at the time of this confirmation. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: The value of [customer](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-customer) + on the SetupIntent at the time of this confirmation. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - setup_attempt + type: string + on_behalf_of: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The value of [on_behalf_of](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-on_behalf_of) + on the SetupIntent at the time of this confirmation. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the payment method used with this SetupAttempt. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + payment_method_details: + "$ref": "#/components/schemas/setup_attempt_payment_method_details" + setup_error: + anyOf: + - "$ref": "#/components/schemas/api_errors" + description: The error encountered during this attempt to confirm the SetupIntent, + if any. + nullable: true + setup_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/setup_intent" + description: ID of the SetupIntent that this attempt belongs to. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/setup_intent" + status: + description: Status of this SetupAttempt, one of `requires_confirmation`, + `requires_action`, `processing`, `succeeded`, `failed`, or `abandoned`. + maxLength: 5000 + type: string + usage: + description: The value of [usage](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-usage) + on the SetupIntent at the time of this confirmation, one of `off_session` + or `on_session`. + maxLength: 5000 + type: string + required: + - created + - id + - livemode + - object + - payment_method + - payment_method_details + - setup_intent + - status + - usage + title: PaymentFlowsSetupIntentSetupAttempt + type: object + x-expandableFields: + - application + - customer + - on_behalf_of + - payment_method + - payment_method_details + - setup_error + - setup_intent + x-resourceId: setup_attempt + setup_attempt_payment_method_details: + description: '' + properties: + acss_debit: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_acss_debit" + au_becs_debit: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_au_becs_debit" + bacs_debit: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_bacs_debit" + bancontact: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_bancontact" + card: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_card" + card_present: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_card_present" + ideal: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_ideal" + sepa_debit: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_sepa_debit" + sofort: + "$ref": "#/components/schemas/setup_attempt_payment_method_details_sofort" + type: + description: The type of the payment method used in the SetupIntent (e.g., + `card`). An additional hash is included on `payment_method_details` with + a name matching this value. It contains confirmation-specific information + for the payment method. + maxLength: 5000 + type: string + required: + - type + title: SetupAttemptPaymentMethodDetails + type: object + x-expandableFields: + - acss_debit + - au_becs_debit + - bacs_debit + - bancontact + - card + - card_present + - ideal + - sepa_debit + - sofort + setup_attempt_payment_method_details_acss_debit: + description: '' + properties: {} + title: setup_attempt_payment_method_details_acss_debit + type: object + x-expandableFields: [] + setup_attempt_payment_method_details_au_becs_debit: + description: '' + properties: {} + title: setup_attempt_payment_method_details_au_becs_debit + type: object + x-expandableFields: [] + setup_attempt_payment_method_details_bacs_debit: + description: '' + properties: {} + title: setup_attempt_payment_method_details_bacs_debit + type: object + x-expandableFields: [] + setup_attempt_payment_method_details_bancontact: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bic: + description: Bank Identifier Code of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + generated_sepa_debit: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the SEPA Direct Debit PaymentMethod which was generated + by this SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + generated_sepa_debit_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: The mandate for the SEPA Direct Debit PaymentMethod which was + generated by this SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + iban_last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + preferred_language: + description: |- + Preferred language of the Bancontact authorization page that the customer is redirected to. + Can be one of `en`, `de`, `fr`, or `nl` + enum: + - de + - en + - fr + - nl + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by Bancontact directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + title: setup_attempt_payment_method_details_bancontact + type: object + x-expandableFields: + - generated_sepa_debit + - generated_sepa_debit_mandate + setup_attempt_payment_method_details_card: + description: '' + properties: + three_d_secure: + anyOf: + - "$ref": "#/components/schemas/three_d_secure_details" + description: Populated if this authorization used 3D Secure authentication. + nullable: true + title: setup_attempt_payment_method_details_card + type: object + x-expandableFields: + - three_d_secure + setup_attempt_payment_method_details_card_present: + description: '' + properties: + generated_card: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the Card PaymentMethod which was generated by this + SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + title: setup_attempt_payment_method_details_card_present + type: object + x-expandableFields: + - generated_card + setup_attempt_payment_method_details_ideal: + description: '' + properties: + bank: + description: The customer's bank. Can be one of `abn_amro`, `asn_bank`, + `bunq`, `handelsbanken`, `ing`, `knab`, `moneyou`, `rabobank`, `regiobank`, + `revolut`, `sns_bank`, `triodos_bank`, or `van_lanschot`. + enum: + - abn_amro + - asn_bank + - bunq + - handelsbanken + - ing + - knab + - moneyou + - rabobank + - regiobank + - revolut + - sns_bank + - triodos_bank + - van_lanschot + nullable: true + type: string + bic: + description: The Bank Identifier Code of the customer's bank. + enum: + - ABNANL2A + - ASNBNL21 + - BUNQNL2A + - FVLBNL22 + - HANDNL2A + - INGBNL2A + - KNABNL2H + - MOYONL21 + - RABONL2U + - RBRBNL21 + - REVOLT21 + - SNSBNL2A + - TRIONL2U + nullable: true + type: string + generated_sepa_debit: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the SEPA Direct Debit PaymentMethod which was generated + by this SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + generated_sepa_debit_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: The mandate for the SEPA Direct Debit PaymentMethod which was + generated by this SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + iban_last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by iDEAL directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + title: setup_attempt_payment_method_details_ideal + type: object + x-expandableFields: + - generated_sepa_debit + - generated_sepa_debit_mandate + setup_attempt_payment_method_details_sepa_debit: + description: '' + properties: {} + title: setup_attempt_payment_method_details_sepa_debit + type: object + x-expandableFields: [] + setup_attempt_payment_method_details_sofort: + description: '' + properties: + bank_code: + description: Bank code of bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bank_name: + description: Name of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + bic: + description: Bank Identifier Code of the bank associated with the bank account. + maxLength: 5000 + nullable: true + type: string + generated_sepa_debit: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: The ID of the SEPA Direct Debit PaymentMethod which was generated + by this SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + generated_sepa_debit_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: The mandate for the SEPA Direct Debit PaymentMethod which was + generated by this SetupAttempt. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + iban_last4: + description: Last four characters of the IBAN. + maxLength: 5000 + nullable: true + type: string + preferred_language: + description: |- + Preferred language of the Sofort authorization page that the customer is redirected to. + Can be one of `en`, `de`, `fr`, or `nl` + enum: + - de + - en + - fr + - nl + nullable: true + type: string + verified_name: + description: |- + Owner's verified full name. Values are verified or provided by Sofort directly + (if supported) at the time of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + title: setup_attempt_payment_method_details_sofort + type: object + x-expandableFields: + - generated_sepa_debit + - generated_sepa_debit_mandate + setup_intent: + description: |- + A SetupIntent guides you through the process of setting up and saving a customer's payment credentials for future payments. + For example, you could use a SetupIntent to set up and save your customer's card without immediately collecting a payment. + Later, you can use [PaymentIntents](https://stripe.com/docs/api#payment_intents) to drive the payment flow. + + Create a SetupIntent as soon as you're ready to collect your customer's payment credentials. + Do not maintain long-lived, unconfirmed SetupIntents as they may no longer be valid. + The SetupIntent then transitions through multiple [statuses](https://stripe.com/docs/payments/intents#intent-statuses) as it guides + you through the setup process. + + Successful SetupIntents result in payment credentials that are optimized for future payments. + For example, cardholders in [certain regions](/guides/strong-customer-authentication) may need to be run through + [Strong Customer Authentication](https://stripe.com/docs/strong-customer-authentication) at the time of payment method collection + in order to streamline later [off-session payments](https://stripe.com/docs/payments/setup-intents). + If the SetupIntent is used with a [Customer](https://stripe.com/docs/api#setup_intent_object-customer), upon success, + it will automatically attach the resulting payment method to that Customer. + We recommend using SetupIntents or [setup_future_usage](https://stripe.com/docs/api#payment_intent_object-setup_future_usage) on + PaymentIntents to save payment methods in order to prevent saving invalid or unoptimized payment methods. + + By using SetupIntents, you ensure that your customers experience the minimum set of required friction, + even as regulations change over time. + + Related guide: [Setup Intents API](https://stripe.com/docs/payments/setup-intents). + properties: + application: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/application" + description: ID of the Connect application that created the SetupIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/application" + cancellation_reason: + description: Reason for cancellation of this SetupIntent, one of `abandoned`, + `requested_by_customer`, or `duplicate`. + enum: + - abandoned + - duplicate + - requested_by_customer + nullable: true + type: string + client_secret: + description: |- + The client secret of this SetupIntent. Used for client-side retrieval using a publishable key. + + The client secret can be used to complete payment setup from your frontend. It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer. Make sure that you have TLS enabled on any page that includes the client secret. + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: |- + ID of the Customer this SetupIntent belongs to, if one exists. + + If present, the SetupIntent's payment method will be attached to the Customer on successful setup. Payment methods attached to other Customers cannot be used with this SetupIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + last_setup_error: + anyOf: + - "$ref": "#/components/schemas/api_errors" + description: The error encountered in the previous SetupIntent confirmation. + nullable: true + latest_attempt: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/setup_attempt" + description: The most recent SetupAttempt for this SetupIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/setup_attempt" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: ID of the multi use Mandate generated by the SetupIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + next_action: + anyOf: + - "$ref": "#/components/schemas/setup_intent_next_action" + description: If present, this property tells you what actions you need to + take in order for your customer to continue payment setup. + nullable: true + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - setup_intent + type: string + on_behalf_of: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account (if any) for which the setup is intended. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the payment method used with this SetupIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + payment_method_options: + anyOf: + - "$ref": "#/components/schemas/setup_intent_payment_method_options" + description: Payment-method-specific configuration for this SetupIntent. + nullable: true + payment_method_types: + description: The list of payment method types (e.g. card) that this SetupIntent + is allowed to set up. + items: + maxLength: 5000 + type: string + type: array + single_use_mandate: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/mandate" + description: ID of the single_use Mandate generated by the SetupIntent. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/mandate" + status: + description: "[Status](https://stripe.com/docs/payments/intents#intent-statuses) + of this SetupIntent, one of `requires_payment_method`, `requires_confirmation`, + `requires_action`, `processing`, `canceled`, or `succeeded`." + enum: + - canceled + - processing + - requires_action + - requires_confirmation + - requires_payment_method + - succeeded + type: string + usage: + description: |- + Indicates how the payment method is intended to be used in the future. + + Use `on_session` if you intend to only reuse the payment method when the customer is in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow. If not provided, this value defaults to `off_session`. + maxLength: 5000 + type: string + required: + - created + - id + - livemode + - object + - payment_method_types + - status + - usage + title: SetupIntent + type: object + x-expandableFields: + - application + - customer + - last_setup_error + - latest_attempt + - mandate + - next_action + - on_behalf_of + - payment_method + - payment_method_options + - single_use_mandate + x-resourceId: setup_intent + setup_intent_next_action: + description: '' + properties: + redirect_to_url: + "$ref": "#/components/schemas/setup_intent_next_action_redirect_to_url" + type: + description: Type of the next action to perform, one of `redirect_to_url`, + `use_stripe_sdk`, `alipay_handle_redirect`, or `oxxo_display_details`. + maxLength: 5000 + type: string + use_stripe_sdk: + description: When confirming a SetupIntent with Stripe.js, Stripe.js depends + on the contents of this dictionary to invoke authentication flows. The + shape of the contents is subject to change and is only intended to be + used by Stripe.js. + type: object + verify_with_microdeposits: + "$ref": "#/components/schemas/setup_intent_next_action_verify_with_microdeposits" + required: + - type + title: SetupIntentNextAction + type: object + x-expandableFields: + - redirect_to_url + - verify_with_microdeposits + setup_intent_next_action_redirect_to_url: + description: '' + properties: + return_url: + description: If the customer does not exit their browser while authenticating, + they will be redirected to this specified URL after completion. + maxLength: 5000 + nullable: true + type: string + url: + description: The URL you must redirect your customer to in order to authenticate. + maxLength: 5000 + nullable: true + type: string + title: SetupIntentNextActionRedirectToUrl + type: object + x-expandableFields: [] + setup_intent_next_action_verify_with_microdeposits: + description: '' + properties: + arrival_date: + description: The timestamp when the microdeposits are expected to land. + format: unix-time + type: integer + hosted_verification_url: + description: The URL for the hosted verification page, which allows customers + to verify their bank account. + maxLength: 5000 + type: string + required: + - arrival_date + - hosted_verification_url + title: SetupIntentNextActionVerifyWithMicrodeposits + type: object + x-expandableFields: [] + setup_intent_payment_method_options: + description: '' + properties: + acss_debit: + "$ref": "#/components/schemas/setup_intent_payment_method_options_acss_debit" + card: + "$ref": "#/components/schemas/setup_intent_payment_method_options_card" + sepa_debit: + "$ref": "#/components/schemas/setup_intent_payment_method_options_sepa_debit" + title: SetupIntentPaymentMethodOptions + type: object + x-expandableFields: + - acss_debit + - card + - sepa_debit + setup_intent_payment_method_options_acss_debit: + description: '' + properties: + currency: + description: Currency supported by the bank account + enum: + - cad + - usd + nullable: true + type: string + mandate_options: + "$ref": "#/components/schemas/setup_intent_payment_method_options_mandate_options_acss_debit" + verification_method: + description: Bank account verification method. + enum: + - automatic + - instant + - microdeposits + type: string + x-stripeBypassValidation: true + title: setup_intent_payment_method_options_acss_debit + type: object + x-expandableFields: + - mandate_options + setup_intent_payment_method_options_card: + description: '' + properties: + request_three_d_secure: + description: 'We strongly recommend that you rely on our SCA Engine to automatically + prompt your customers for authentication based on risk level and [other + requirements](https://stripe.com/docs/strong-customer-authentication). + However, if you wish to request 3D Secure based on logic from your own + fraud engine, provide this option. Permitted values include: `automatic` + or `any`. If not provided, defaults to `automatic`. Read our guide on + [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) + for more information on how this configuration interacts with Radar and + our SCA Engine.' + enum: + - any + - automatic + - challenge_only + nullable: true + type: string + title: setup_intent_payment_method_options_card + type: object + x-expandableFields: [] + setup_intent_payment_method_options_mandate_options_acss_debit: + description: '' + properties: + custom_mandate_url: + description: A URL for custom mandate text + maxLength: 5000 + type: string + interval_description: + description: Description of the interval. Only required if the 'payment_schedule' + parameter is 'interval' or 'combined'. + maxLength: 5000 + nullable: true + type: string + payment_schedule: + description: Payment schedule for the mandate. + enum: + - combined + - interval + - sporadic + nullable: true + type: string + transaction_type: + description: Transaction type of the mandate. + enum: + - business + - personal + nullable: true + type: string + title: setup_intent_payment_method_options_mandate_options_acss_debit + type: object + x-expandableFields: [] + setup_intent_payment_method_options_mandate_options_sepa_debit: + description: '' + properties: {} + title: setup_intent_payment_method_options_mandate_options_sepa_debit + type: object + x-expandableFields: [] + setup_intent_payment_method_options_sepa_debit: + description: '' + properties: + mandate_options: + "$ref": "#/components/schemas/setup_intent_payment_method_options_mandate_options_sepa_debit" + title: setup_intent_payment_method_options_sepa_debit + type: object + x-expandableFields: + - mandate_options + shipping: + description: '' + properties: + address: + "$ref": "#/components/schemas/address" + carrier: + description: The delivery service that shipped a physical product, such + as Fedex, UPS, USPS, etc. + maxLength: 5000 + nullable: true + type: string + name: + description: Recipient name. + maxLength: 5000 + nullable: true + type: string + phone: + description: Recipient phone (including extension). + maxLength: 5000 + nullable: true + type: string + tracking_number: + description: The tracking number for a physical product, obtained from the + delivery service. If multiple tracking numbers were generated for this + purchase, please separate them with commas. + maxLength: 5000 + nullable: true + type: string + title: Shipping + type: object + x-expandableFields: + - address + shipping_method: + description: '' + properties: + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the total amount for the line item. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + delivery_estimate: + anyOf: + - "$ref": "#/components/schemas/delivery_estimate" + description: The estimated delivery date for the given shipping method. + Can be either a specific date or a range. + nullable: true + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + required: + - amount + - currency + - description + - id + title: ShippingMethod + type: object + x-expandableFields: + - delivery_estimate + sigma_scheduled_query_run_error: + description: '' + properties: + message: + description: Information about the run failure. + maxLength: 5000 + type: string + required: + - message + title: SigmaScheduledQueryRunError + type: object + x-expandableFields: [] + sku: + description: |- + Stores representations of [stock keeping units](http://en.wikipedia.org/wiki/Stock_keeping_unit). + SKUs describe specific product variations, taking into account any combination of: attributes, + currency, and cost. For example, a product may be a T-shirt, whereas a specific SKU represents + the `size: large`, `color: red` version of that shirt. + + Can also be used to manage inventory. + + Related guide: [Tax, Shipping, and Inventory](https://stripe.com/docs/orders). + properties: + active: + description: Whether the SKU is available for purchase. + type: boolean + attributes: + additionalProperties: + maxLength: 5000 + type: string + description: 'A dictionary of attributes and values for the attributes defined + by the product. If, for example, a product''s attributes are `["size", + "gender"]`, a valid SKU has the following dictionary of attributes: `{"size": + "Medium", "gender": "Unisex"}`.' + type: object + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + image: + description: The URL of an image for this SKU, meant to be displayable to + the customer. + maxLength: 2048 + nullable: true + type: string + inventory: + "$ref": "#/components/schemas/sku_inventory" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - sku + type: string + package_dimensions: + anyOf: + - "$ref": "#/components/schemas/package_dimensions" + description: The dimensions of this SKU for shipping purposes. + nullable: true + price: + description: The cost of the item as a positive integer in the smallest + currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, + Japanese Yen being a zero-decimal currency). + type: integer + product: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/product" + description: The ID of the product this SKU is associated with. The product + must be currently active. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/product" + updated: + description: Time at which the object was last updated. Measured in seconds + since the Unix epoch. + format: unix-time + type: integer + required: + - active + - attributes + - created + - currency + - id + - inventory + - livemode + - metadata + - object + - price + - product + - updated + title: Sku + type: object + x-expandableFields: + - inventory + - package_dimensions + - product + x-resourceId: sku + sku_inventory: + description: 'Description of the SKU’s inventory' + properties: + quantity: + description: The count of inventory available. Will be present if and only + if `type` is `finite`. + nullable: true + type: integer + type: + description: Inventory type. Possible values are `finite`, `bucket` (not + quantified), and `infinite`. + maxLength: 5000 + type: string + value: + description: An indicator of the inventory available. Possible values are + `in_stock`, `limited`, and `out_of_stock`. Will be present if and only + if `type` is `bucket`. + maxLength: 5000 + nullable: true + type: string + required: + - type + title: SKUInventory + type: object + x-expandableFields: [] + source: + description: |- + `Source` objects allow you to accept a variety of payment methods. They + represent a customer's payment instrument, and can be used with the Stripe API + just like a `Card` object: once chargeable, they can be charged, or can be + attached to customers. + + Related guides: [Sources API](https://stripe.com/docs/sources) and [Sources & Customers](https://stripe.com/docs/sources/customers). + properties: + ach_credit_transfer: + "$ref": "#/components/schemas/source_type_ach_credit_transfer" + ach_debit: + "$ref": "#/components/schemas/source_type_ach_debit" + acss_debit: + "$ref": "#/components/schemas/source_type_acss_debit" + alipay: + "$ref": "#/components/schemas/source_type_alipay" + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the total amount associated with the source. This is the + amount for which the source will be chargeable once ready. Required for + `single_use` sources. + nullable: true + type: integer + au_becs_debit: + "$ref": "#/components/schemas/source_type_au_becs_debit" + bancontact: + "$ref": "#/components/schemas/source_type_bancontact" + card: + "$ref": "#/components/schemas/source_type_card" + card_present: + "$ref": "#/components/schemas/source_type_card_present" + client_secret: + description: The client secret of the source. Used for client-side retrieval + using a publishable key. + maxLength: 5000 + type: string + code_verification: + "$ref": "#/components/schemas/source_code_verification_flow" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) + associated with the source. This is the currency for which the source + will be chargeable once ready. Required for `single_use` sources. + nullable: true + type: string + customer: + description: The ID of the customer to which this source is attached. This + will not be present when the source has not been attached to a customer. + maxLength: 5000 + type: string + eps: + "$ref": "#/components/schemas/source_type_eps" + flow: + description: The authentication `flow` of the source. `flow` is one of `redirect`, + `receiver`, `code_verification`, `none`. + maxLength: 5000 + type: string + giropay: + "$ref": "#/components/schemas/source_type_giropay" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + ideal: + "$ref": "#/components/schemas/source_type_ideal" + klarna: + "$ref": "#/components/schemas/source_type_klarna" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + multibanco: + "$ref": "#/components/schemas/source_type_multibanco" + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - source + type: string + owner: + anyOf: + - "$ref": "#/components/schemas/source_owner" + description: Information about the owner of the payment instrument that + may be used or required by particular source types. + nullable: true + p24: + "$ref": "#/components/schemas/source_type_p24" + receiver: + "$ref": "#/components/schemas/source_receiver_flow" + redirect: + "$ref": "#/components/schemas/source_redirect_flow" + sepa_debit: + "$ref": "#/components/schemas/source_type_sepa_debit" + sofort: + "$ref": "#/components/schemas/source_type_sofort" + source_order: + "$ref": "#/components/schemas/source_order" + statement_descriptor: + description: Extra information about a source. This will appear on your + customer's statement every time you charge the source. + maxLength: 5000 + nullable: true + type: string + status: + description: The status of the source, one of `canceled`, `chargeable`, + `consumed`, `failed`, or `pending`. Only `chargeable` sources can be used + to create a charge. + maxLength: 5000 + type: string + three_d_secure: + "$ref": "#/components/schemas/source_type_three_d_secure" + type: + description: The `type` of the source. The `type` is a payment method, one + of `ach_credit_transfer`, `ach_debit`, `alipay`, `bancontact`, `card`, + `card_present`, `eps`, `giropay`, `ideal`, `multibanco`, `klarna`, `p24`, + `sepa_debit`, `sofort`, `three_d_secure`, or `wechat`. An additional hash + is included on the source with a name matching this value. It contains + additional information specific to the [payment method](https://stripe.com/docs/sources) + used. + enum: + - ach_credit_transfer + - ach_debit + - acss_debit + - alipay + - au_becs_debit + - bancontact + - card + - card_present + - eps + - giropay + - ideal + - klarna + - multibanco + - p24 + - sepa_debit + - sofort + - three_d_secure + - wechat + type: string + x-stripeBypassValidation: true + usage: + description: Either `reusable` or `single_use`. Whether this source should + be reusable or not. Some source types may or may not be reusable by construction, + while others may leave the option at creation. If an incompatible value + is passed, an error will be returned. + maxLength: 5000 + nullable: true + type: string + wechat: + "$ref": "#/components/schemas/source_type_wechat" + required: + - client_secret + - created + - flow + - id + - livemode + - object + - status + - type + title: Source + type: object + x-expandableFields: + - code_verification + - owner + - receiver + - redirect + - source_order + x-resourceId: source + source_code_verification_flow: + description: '' + properties: + attempts_remaining: + description: The number of attempts remaining to authenticate the source + object with a verification code. + type: integer + status: + description: The status of the code verification, either `pending` (awaiting + verification, `attempts_remaining` should be greater than 0), `succeeded` + (successful verification) or `failed` (failed verification, cannot be + verified anymore as `attempts_remaining` should be 0). + maxLength: 5000 + type: string + required: + - attempts_remaining + - status + title: SourceCodeVerificationFlow + type: object + x-expandableFields: [] + source_mandate_notification: + description: |- + Source mandate notifications should be created when a notification related to + a source mandate must be sent to the payer. They will trigger a webhook or + deliver an email to the customer. + properties: + acss_debit: + "$ref": "#/components/schemas/source_mandate_notification_acss_debit_data" + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the amount associated with the mandate notification. The + amount is expressed in the currency of the underlying source. Required + if the notification type is `debit_initiated`. + nullable: true + type: integer + bacs_debit: + "$ref": "#/components/schemas/source_mandate_notification_bacs_debit_data" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - source_mandate_notification + type: string + reason: + description: The reason of the mandate notification. Valid reasons are `mandate_confirmed` + or `debit_initiated`. + maxLength: 5000 + type: string + sepa_debit: + "$ref": "#/components/schemas/source_mandate_notification_sepa_debit_data" + source: + "$ref": "#/components/schemas/source" + status: + description: The status of the mandate notification. Valid statuses are + `pending` or `submitted`. + maxLength: 5000 + type: string + type: + description: The type of source this mandate notification is attached to. + Should be the source type identifier code for the payment method, such + as `three_d_secure`. + maxLength: 5000 + type: string + required: + - created + - id + - livemode + - object + - reason + - source + - status + - type + title: SourceMandateNotification + type: object + x-expandableFields: + - acss_debit + - bacs_debit + - sepa_debit + - source + x-resourceId: source_mandate_notification + source_mandate_notification_acss_debit_data: + description: '' + properties: + statement_descriptor: + description: The statement descriptor associate with the debit. + maxLength: 5000 + type: string + title: SourceMandateNotificationAcssDebitData + type: object + x-expandableFields: [] + source_mandate_notification_bacs_debit_data: + description: '' + properties: + last4: + description: Last 4 digits of the account number associated with the debit. + maxLength: 5000 + type: string + title: SourceMandateNotificationBacsDebitData + type: object + x-expandableFields: [] + source_mandate_notification_sepa_debit_data: + description: '' + properties: + creditor_identifier: + description: SEPA creditor ID. + maxLength: 5000 + type: string + last4: + description: Last 4 digits of the account number associated with the debit. + maxLength: 5000 + type: string + mandate_reference: + description: Mandate reference associated with the debit. + maxLength: 5000 + type: string + title: SourceMandateNotificationSepaDebitData + type: object + x-expandableFields: [] + source_order: + description: '' + properties: + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the total amount for the order. + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + email: + description: The email address of the customer placing the order. + maxLength: 5000 + type: string + items: + description: List of items constituting the order. + items: + "$ref": "#/components/schemas/source_order_item" + nullable: true + type: array + shipping: + "$ref": "#/components/schemas/shipping" + required: + - amount + - currency + title: SourceOrder + type: object + x-expandableFields: + - items + - shipping + source_order_item: + description: '' + properties: + amount: + description: The amount (price) for this order item. + nullable: true + type: integer + currency: + description: This currency of this order item. Required when `amount` is + present. + maxLength: 5000 + nullable: true + type: string + description: + description: Human-readable description for this order item. + maxLength: 5000 + nullable: true + type: string + parent: + description: The ID of the associated object for this line item. Expandable + if not null (e.g., expandable to a SKU). + maxLength: 5000 + nullable: true + type: string + quantity: + description: The quantity of this order item. When type is `sku`, this is + the number of instances of the SKU to be ordered. + type: integer + type: + description: The type of this order item. Must be `sku`, `tax`, or `shipping`. + maxLength: 5000 + nullable: true + type: string + title: SourceOrderItem + type: object + x-expandableFields: [] + source_owner: + description: '' + properties: + address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Owner's address. + nullable: true + email: + description: Owner's email address. + maxLength: 5000 + nullable: true + type: string + name: + description: Owner's full name. + maxLength: 5000 + nullable: true + type: string + phone: + description: Owner's phone number (including extension). + maxLength: 5000 + nullable: true + type: string + verified_address: + anyOf: + - "$ref": "#/components/schemas/address" + description: Verified owner's address. Verified values are verified or provided + by the payment method directly (and if supported) at the time of authorization + or settlement. They cannot be set or mutated. + nullable: true + verified_email: + description: Verified owner's email address. Verified values are verified + or provided by the payment method directly (and if supported) at the time + of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + verified_name: + description: Verified owner's full name. Verified values are verified or + provided by the payment method directly (and if supported) at the time + of authorization or settlement. They cannot be set or mutated. + maxLength: 5000 + nullable: true + type: string + verified_phone: + description: Verified owner's phone number (including extension). Verified + values are verified or provided by the payment method directly (and if + supported) at the time of authorization or settlement. They cannot be + set or mutated. + maxLength: 5000 + nullable: true + type: string + title: SourceOwner + type: object + x-expandableFields: + - address + - verified_address + source_receiver_flow: + description: '' + properties: + address: + description: The address of the receiver source. This is the value that + should be communicated to the customer to send their funds to. + maxLength: 5000 + nullable: true + type: string + amount_charged: + description: The total amount that was moved to your balance. This is almost + always equal to the amount charged. In rare cases when customers deposit + excess funds and we are unable to refund those, those funds get moved + to your balance and show up in amount_charged as well. The amount charged + is expressed in the source's currency. + type: integer + amount_received: + description: The total amount received by the receiver source. `amount_received + = amount_returned + amount_charged` should be true for consumed sources + unless customers deposit excess funds. The amount received is expressed + in the source's currency. + type: integer + amount_returned: + description: The total amount that was returned to the customer. The amount + returned is expressed in the source's currency. + type: integer + refund_attributes_method: + description: Type of refund attribute method, one of `email`, `manual`, + or `none`. + maxLength: 5000 + type: string + refund_attributes_status: + description: Type of refund attribute status, one of `missing`, `requested`, + or `available`. + maxLength: 5000 + type: string + required: + - amount_charged + - amount_received + - amount_returned + - refund_attributes_method + - refund_attributes_status + title: SourceReceiverFlow + type: object + x-expandableFields: [] + source_redirect_flow: + description: '' + properties: + failure_reason: + description: The failure reason for the redirect, either `user_abort` (the + customer aborted or dropped out of the redirect flow), `declined` (the + authentication failed or the transaction was declined), or `processing_error` + (the redirect failed due to a technical error). Present only if the redirect + status is `failed`. + maxLength: 5000 + nullable: true + type: string + return_url: + description: The URL you provide to redirect the customer to after they + authenticated their payment. + maxLength: 5000 + type: string + status: + description: The status of the redirect, either `pending` (ready to be used + by your customer to authenticate the transaction), `succeeded` (succesful + authentication, cannot be reused) or `not_required` (redirect should not + be used) or `failed` (failed authentication, cannot be reused). + maxLength: 5000 + type: string + url: + description: The URL provided to you to redirect a customer to as part of + a `redirect` authentication flow. + maxLength: 2048 + type: string + required: + - return_url + - status + - url + title: SourceRedirectFlow + type: object + x-expandableFields: [] + source_transaction: + description: |- + Some payment methods have no required amount that a customer must send. + Customers can be instructed to send any amount, and it can be made up of + multiple transactions. As such, sources can have multiple associated + transactions. + properties: + ach_credit_transfer: + "$ref": "#/components/schemas/source_transaction_ach_credit_transfer_data" + amount: + description: A positive integer in the smallest currency unit (that is, + 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) + representing the amount your customer has pushed to the receiver. + type: integer + chf_credit_transfer: + "$ref": "#/components/schemas/source_transaction_chf_credit_transfer_data" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + gbp_credit_transfer: + "$ref": "#/components/schemas/source_transaction_gbp_credit_transfer_data" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - source_transaction + type: string + paper_check: + "$ref": "#/components/schemas/source_transaction_paper_check_data" + sepa_credit_transfer: + "$ref": "#/components/schemas/source_transaction_sepa_credit_transfer_data" + source: + description: The ID of the source this transaction is attached to. + maxLength: 5000 + type: string + status: + description: The status of the transaction, one of `succeeded`, `pending`, + or `failed`. + maxLength: 5000 + type: string + type: + description: The type of source this transaction is attached to. + enum: + - ach_credit_transfer + - ach_debit + - alipay + - bancontact + - card + - card_present + - eps + - giropay + - ideal + - klarna + - multibanco + - p24 + - sepa_debit + - sofort + - three_d_secure + - wechat + type: string + required: + - amount + - created + - currency + - id + - livemode + - object + - source + - status + - type + title: SourceTransaction + type: object + x-expandableFields: + - ach_credit_transfer + - chf_credit_transfer + - gbp_credit_transfer + - paper_check + - sepa_credit_transfer + x-resourceId: source_transaction + source_transaction_ach_credit_transfer_data: + description: '' + properties: + customer_data: + description: Customer data associated with the transfer. + maxLength: 5000 + type: string + fingerprint: + description: Bank account fingerprint associated with the transfer. + maxLength: 5000 + type: string + last4: + description: Last 4 digits of the account number associated with the transfer. + maxLength: 5000 + type: string + routing_number: + description: Routing number associated with the transfer. + maxLength: 5000 + type: string + title: SourceTransactionAchCreditTransferData + type: object + x-expandableFields: [] + source_transaction_chf_credit_transfer_data: + description: '' + properties: + reference: + description: Reference associated with the transfer. + maxLength: 5000 + type: string + sender_address_country: + description: Sender's country address. + maxLength: 5000 + type: string + sender_address_line1: + description: Sender's line 1 address. + maxLength: 5000 + type: string + sender_iban: + description: Sender's bank account IBAN. + maxLength: 5000 + type: string + sender_name: + description: Sender's name. + maxLength: 5000 + type: string + title: SourceTransactionChfCreditTransferData + type: object + x-expandableFields: [] + source_transaction_gbp_credit_transfer_data: + description: '' + properties: + fingerprint: + description: Bank account fingerprint associated with the Stripe owned bank + account receiving the transfer. + maxLength: 5000 + type: string + funding_method: + description: 'The credit transfer rails the sender used to push this transfer. + The possible rails are: Faster Payments, BACS, CHAPS, and wire transfers. + Currently only Faster Payments is supported.' + maxLength: 5000 + type: string + last4: + description: Last 4 digits of sender account number associated with the + transfer. + maxLength: 5000 + type: string + reference: + description: Sender entered arbitrary information about the transfer. + maxLength: 5000 + type: string + sender_account_number: + description: Sender account number associated with the transfer. + maxLength: 5000 + type: string + sender_name: + description: Sender name associated with the transfer. + maxLength: 5000 + type: string + sender_sort_code: + description: Sender sort code associated with the transfer. + maxLength: 5000 + type: string + title: SourceTransactionGbpCreditTransferData + type: object + x-expandableFields: [] + source_transaction_paper_check_data: + description: '' + properties: + available_at: + description: Time at which the deposited funds will be available for use. + Measured in seconds since the Unix epoch. + maxLength: 5000 + type: string + invoices: + description: Comma-separated list of invoice IDs associated with the paper + check. + maxLength: 5000 + type: string + title: SourceTransactionPaperCheckData + type: object + x-expandableFields: [] + source_transaction_sepa_credit_transfer_data: + description: '' + properties: + reference: + description: Reference associated with the transfer. + maxLength: 5000 + type: string + sender_iban: + description: Sender's bank account IBAN. + maxLength: 5000 + type: string + sender_name: + description: Sender's name. + maxLength: 5000 + type: string + title: SourceTransactionSepaCreditTransferData + type: object + x-expandableFields: [] + source_type_ach_credit_transfer: + properties: + account_number: + nullable: true + type: string + bank_name: + nullable: true + type: string + fingerprint: + nullable: true + type: string + refund_account_holder_name: + nullable: true + type: string + refund_account_holder_type: + nullable: true + type: string + refund_routing_number: + nullable: true + type: string + routing_number: + nullable: true + type: string + swift_code: + nullable: true + type: string + type: object + source_type_ach_debit: + properties: + bank_name: + nullable: true + type: string + country: + nullable: true + type: string + fingerprint: + nullable: true + type: string + last4: + nullable: true + type: string + routing_number: + nullable: true + type: string + type: + nullable: true + type: string + type: object + source_type_acss_debit: + properties: + bank_address_city: + nullable: true + type: string + bank_address_line_1: + nullable: true + type: string + bank_address_line_2: + nullable: true + type: string + bank_address_postal_code: + nullable: true + type: string + bank_name: + nullable: true + type: string + category: + nullable: true + type: string + country: + nullable: true + type: string + fingerprint: + nullable: true + type: string + last4: + nullable: true + type: string + routing_number: + nullable: true + type: string + type: object + source_type_alipay: + properties: + data_string: + nullable: true + type: string + native_url: + nullable: true + type: string + statement_descriptor: + nullable: true + type: string + type: object + source_type_au_becs_debit: + properties: + bsb_number: + nullable: true + type: string + fingerprint: + nullable: true + type: string + last4: + nullable: true + type: string + type: object + source_type_bancontact: + properties: + bank_code: + nullable: true + type: string + bank_name: + nullable: true + type: string + bic: + nullable: true + type: string + iban_last4: + nullable: true + type: string + preferred_language: + nullable: true + type: string + statement_descriptor: + nullable: true + type: string + type: object + source_type_card: + properties: + address_line1_check: + nullable: true + type: string + address_zip_check: + nullable: true + type: string + brand: + nullable: true + type: string + country: + nullable: true + type: string + cvc_check: + nullable: true + type: string + dynamic_last4: + nullable: true + type: string + exp_month: + nullable: true + type: integer + exp_year: + nullable: true + type: integer + fingerprint: + type: string + funding: + nullable: true + type: string + last4: + nullable: true + type: string + name: + nullable: true + type: string + three_d_secure: + type: string + tokenization_method: + nullable: true + type: string + type: object + source_type_card_present: + properties: + application_cryptogram: + type: string + application_preferred_name: + type: string + authorization_code: + nullable: true + type: string + authorization_response_code: + type: string + brand: + nullable: true + type: string + country: + nullable: true + type: string + cvm_type: + type: string + data_type: + nullable: true + type: string + dedicated_file_name: + type: string + emv_auth_data: + type: string + evidence_customer_signature: + nullable: true + type: string + evidence_transaction_certificate: + nullable: true + type: string + exp_month: + nullable: true + type: integer + exp_year: + nullable: true + type: integer + fingerprint: + type: string + funding: + nullable: true + type: string + last4: + nullable: true + type: string + pos_device_id: + nullable: true + type: string + pos_entry_mode: + type: string + read_method: + nullable: true + type: string + reader: + nullable: true + type: string + terminal_verification_results: + type: string + transaction_status_information: + type: string + type: object + source_type_eps: + properties: + reference: + nullable: true + type: string + statement_descriptor: + nullable: true + type: string + type: object + source_type_giropay: + properties: + bank_code: + nullable: true + type: string + bank_name: + nullable: true + type: string + bic: + nullable: true + type: string + statement_descriptor: + nullable: true + type: string + type: object + source_type_ideal: + properties: + bank: + nullable: true + type: string + bic: + nullable: true + type: string + iban_last4: + nullable: true + type: string + statement_descriptor: + nullable: true + type: string + type: object + source_type_klarna: + properties: + background_image_url: + type: string + client_token: + nullable: true + type: string + first_name: + type: string + last_name: + type: string + locale: + type: string + logo_url: + type: string + page_title: + type: string + pay_later_asset_urls_descriptive: + type: string + pay_later_asset_urls_standard: + type: string + pay_later_name: + type: string + pay_later_redirect_url: + type: string + pay_now_asset_urls_descriptive: + type: string + pay_now_asset_urls_standard: + type: string + pay_now_name: + type: string + pay_now_redirect_url: + type: string + pay_over_time_asset_urls_descriptive: + type: string + pay_over_time_asset_urls_standard: + type: string + pay_over_time_name: + type: string + pay_over_time_redirect_url: + type: string + payment_method_categories: + type: string + purchase_country: + type: string + purchase_type: + type: string + redirect_url: + type: string + shipping_delay: + type: integer + shipping_first_name: + type: string + shipping_last_name: + type: string + type: object + source_type_multibanco: + properties: + entity: + nullable: true + type: string + reference: + nullable: true + type: string + refund_account_holder_address_city: + nullable: true + type: string + refund_account_holder_address_country: + nullable: true + type: string + refund_account_holder_address_line1: + nullable: true + type: string + refund_account_holder_address_line2: + nullable: true + type: string + refund_account_holder_address_postal_code: + nullable: true + type: string + refund_account_holder_address_state: + nullable: true + type: string + refund_account_holder_name: + nullable: true + type: string + refund_iban: + nullable: true + type: string + type: object + source_type_p24: + properties: + reference: + nullable: true + type: string + type: object + source_type_sepa_debit: + properties: + bank_code: + nullable: true + type: string + branch_code: + nullable: true + type: string + country: + nullable: true + type: string + fingerprint: + nullable: true + type: string + last4: + nullable: true + type: string + mandate_reference: + nullable: true + type: string + mandate_url: + nullable: true + type: string + type: object + source_type_sofort: + properties: + bank_code: + nullable: true + type: string + bank_name: + nullable: true + type: string + bic: + nullable: true + type: string + country: + nullable: true + type: string + iban_last4: + nullable: true + type: string + preferred_language: + nullable: true + type: string + statement_descriptor: + nullable: true + type: string + type: object + source_type_three_d_secure: + properties: + address_line1_check: + nullable: true + type: string + address_zip_check: + nullable: true + type: string + authenticated: + nullable: true + type: boolean + brand: + nullable: true + type: string + card: + nullable: true + type: string + country: + nullable: true + type: string + customer: + nullable: true + type: string + cvc_check: + nullable: true + type: string + dynamic_last4: + nullable: true + type: string + exp_month: + nullable: true + type: integer + exp_year: + nullable: true + type: integer + fingerprint: + type: string + funding: + nullable: true + type: string + last4: + nullable: true + type: string + name: + nullable: true + type: string + three_d_secure: + type: string + tokenization_method: + nullable: true + type: string + type: object + source_type_wechat: + properties: + prepay_id: + type: string + qr_code_url: + nullable: true + type: string + statement_descriptor: + type: string + type: object + status_transitions: + description: '' + properties: + canceled: + description: The time that the order was canceled. + format: unix-time + nullable: true + type: integer + fulfiled: + description: The time that the order was fulfilled. + format: unix-time + nullable: true + type: integer + paid: + description: The time that the order was paid. + format: unix-time + nullable: true + type: integer + returned: + description: The time that the order was returned. + format: unix-time + nullable: true + type: integer + title: StatusTransitions + type: object + x-expandableFields: [] + subscription: + description: |- + Subscriptions allow you to charge a customer on a recurring basis. + + Related guide: [Creating Subscriptions](https://stripe.com/docs/billing/subscriptions/creating). + properties: + application_fee_percent: + description: A non-negative decimal between 0 and 100, with at most two + decimal places. This represents the percentage of the subscription invoice + subtotal that will be transferred to the application owner's Stripe account. + nullable: true + type: number + automatic_tax: + "$ref": "#/components/schemas/subscription_automatic_tax" + billing_cycle_anchor: + description: Determines the date of the first full invoice, and, for plans + with `month` or `year` intervals, the day of the month for subsequent + invoices. + format: unix-time + type: integer + billing_thresholds: + anyOf: + - "$ref": "#/components/schemas/subscription_billing_thresholds" + description: Define thresholds at which an invoice will be sent, and the + subscription advanced to a new billing period + nullable: true + cancel_at: + description: A date in the future at which the subscription will automatically + get canceled + format: unix-time + nullable: true + type: integer + cancel_at_period_end: + description: If the subscription has been canceled with the `at_period_end` + flag set to `true`, `cancel_at_period_end` on the subscription will be + true. You can use this attribute to determine whether a subscription that + has a status of active is scheduled to be canceled at the end of the current + period. + type: boolean + canceled_at: + description: If the subscription has been canceled, the date of that cancellation. + If the subscription was canceled with `cancel_at_period_end`, `canceled_at` + will reflect the time of the most recent update request, not the end of + the subscription period when the subscription is automatically moved to + a canceled state. + format: unix-time + nullable: true + type: integer + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When charging + automatically, Stripe will attempt to pay this subscription at the end + of the cycle using the default source attached to the customer. When sending + an invoice, Stripe will email your customer an invoice with payment instructions. + enum: + - charge_automatically + - send_invoice + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + current_period_end: + description: End of the current period that the subscription has been invoiced + for. At the end of this period, a new invoice will be created. + format: unix-time + type: integer + current_period_start: + description: Start of the current period that the subscription has been + invoiced for. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: ID of the customer who owns the subscription. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + days_until_due: + description: Number of days a customer has to pay invoices generated by + this subscription. This value will be `null` for subscriptions where `collection_method=charge_automatically`. + nullable: true + type: integer + default_payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the default payment method for the subscription. It must + belong to the customer associated with the subscription. This takes precedence + over `default_source`. If neither are set, invoices will use the customer's + [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) + or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + default_source: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + description: ID of the default payment source for the subscription. It must + belong to the customer associated with the subscription and be in a chargeable + state. If `default_payment_method` is also set, `default_payment_method` + will take precedence. If neither are set, invoices will use the customer's + [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) + or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/alipay_account" + - "$ref": "#/components/schemas/bank_account" + - "$ref": "#/components/schemas/bitcoin_receiver" + - "$ref": "#/components/schemas/card" + - "$ref": "#/components/schemas/source" + default_tax_rates: + description: The tax rates that will apply to any subscription item that + does not have `tax_rates` set. Invoices created will have their `default_tax_rates` + populated from the subscription. + items: + "$ref": "#/components/schemas/tax_rate" + nullable: true + type: array + discount: + anyOf: + - "$ref": "#/components/schemas/discount" + description: Describes the current discount applied to this subscription, + if there is one. When billing, a discount applied to a subscription overrides + a discount applied on a customer-wide basis. + nullable: true + ended_at: + description: If the subscription has ended, the date the subscription ended. + format: unix-time + nullable: true + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + items: + description: List of subscription items, each with an attached price. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/subscription_item" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: SubscriptionItemList + type: object + x-expandableFields: + - data + latest_invoice: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/invoice" + description: The most recent invoice this subscription has generated. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/invoice" + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + next_pending_invoice_item_invoice: + description: Specifies the approximate timestamp on which any pending invoice + items will be billed according to the schedule provided at `pending_invoice_item_interval`. + format: unix-time + nullable: true + type: integer + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - subscription + type: string + pause_collection: + anyOf: + - "$ref": "#/components/schemas/subscriptions_resource_pause_collection" + description: If specified, payment collection for this subscription will + be paused. + nullable: true + payment_settings: + anyOf: + - "$ref": "#/components/schemas/subscriptions_resource_payment_settings" + description: Payment settings passed on to invoices created by the subscription. + nullable: true + pending_invoice_item_interval: + anyOf: + - "$ref": "#/components/schemas/subscription_pending_invoice_item_interval" + description: Specifies an interval for how often to bill for any pending + invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) + for the given subscription at the specified interval. + nullable: true + pending_setup_intent: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/setup_intent" + description: You can use this [SetupIntent](https://stripe.com/docs/api/setup_intents) + to collect user authentication when creating a subscription without immediate + payment or updating a subscription's payment method, allowing you to optimize + for off-session payments. Learn more in the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication#scenario-2). + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/setup_intent" + pending_update: + anyOf: + - "$ref": "#/components/schemas/subscriptions_resource_pending_update" + description: If specified, [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates) + that will be applied to the subscription once the `latest_invoice` has + been paid. + nullable: true + schedule: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription_schedule" + description: The schedule attached to the subscription + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription_schedule" + start_date: + description: Date when the subscription was first created. The date might + differ from the `created` date due to backdating. + format: unix-time + type: integer + status: + description: "Possible values are `incomplete`, `incomplete_expired`, `trialing`, + `active`, `past_due`, `canceled`, or `unpaid`. \n\nFor `collection_method=charge_automatically` + a subscription moves into `incomplete` if the initial payment attempt + fails. A subscription in this state can only have metadata and default_source + updated. Once the first invoice is paid, the subscription moves into an + `active` state. If the first invoice is not paid within 23 hours, the + subscription transitions to `incomplete_expired`. This is a terminal state, + the open invoice will be voided and no further invoices will be generated. + \n\nA subscription that is currently in a trial period is `trialing` and + moves to `active` when the trial period is over. \n\nIf subscription `collection_method=charge_automatically` + it becomes `past_due` when payment to renew it fails and `canceled` or + `unpaid` (depending on your subscriptions settings) when Stripe has exhausted + all payment retry attempts. \n\nIf subscription `collection_method=send_invoice` + it becomes `past_due` when its invoice is not paid by the due date, and + `canceled` or `unpaid` if it is still not paid by an additional deadline + after that. Note that when a subscription has a status of `unpaid`, no + subsequent invoices will be attempted (invoices will be created, but then + immediately automatically closed). After receiving updated payment information + from a customer, you may choose to reopen and pay their closed invoices." + enum: + - active + - canceled + - incomplete + - incomplete_expired + - past_due + - trialing + - unpaid + type: string + transfer_data: + anyOf: + - "$ref": "#/components/schemas/subscription_transfer_data" + description: The account (if any) the subscription's payments will be attributed + to for tax reporting, and where funds from each payment will be transferred + to for each of the subscription's invoices. + nullable: true + trial_end: + description: If the subscription has a trial, the end of that trial. + format: unix-time + nullable: true + type: integer + trial_start: + description: If the subscription has a trial, the beginning of that trial. + format: unix-time + nullable: true + type: integer + required: + - automatic_tax + - billing_cycle_anchor + - cancel_at_period_end + - collection_method + - created + - current_period_end + - current_period_start + - customer + - id + - items + - livemode + - metadata + - object + - start_date + - status + title: Subscription + type: object + x-expandableFields: + - automatic_tax + - billing_thresholds + - customer + - default_payment_method + - default_source + - default_tax_rates + - discount + - items + - latest_invoice + - pause_collection + - payment_settings + - pending_invoice_item_interval + - pending_setup_intent + - pending_update + - schedule + - transfer_data + x-resourceId: subscription + subscription_automatic_tax: + description: '' + properties: + enabled: + description: Whether Stripe automatically computes tax on this subscription. + type: boolean + required: + - enabled + title: SubscriptionAutomaticTax + type: object + x-expandableFields: [] + subscription_billing_thresholds: + description: '' + properties: + amount_gte: + description: Monetary threshold that triggers the subscription to create + an invoice + nullable: true + type: integer + reset_billing_cycle_anchor: + description: Indicates if the `billing_cycle_anchor` should be reset when + a threshold is reached. If true, `billing_cycle_anchor` will be updated + to the date/time the threshold was last reached; otherwise, the value + will remain unchanged. This value may not be `true` if the subscription + contains items with plans that have `aggregate_usage=last_ever`. + nullable: true + type: boolean + title: SubscriptionBillingThresholds + type: object + x-expandableFields: [] + subscription_item: + description: |- + Subscription items allow you to create customer subscriptions with more than + one plan, making it easy to represent complex billing relationships. + properties: + billing_thresholds: + anyOf: + - "$ref": "#/components/schemas/subscription_item_billing_thresholds" + description: Define thresholds at which an invoice will be sent, and the + related subscription advanced to a new billing period + nullable: true + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - subscription_item + type: string + price: + "$ref": "#/components/schemas/price" + quantity: + description: The [quantity](https://stripe.com/docs/subscriptions/quantities) + of the plan to which the customer should be subscribed. + type: integer + subscription: + description: The `subscription` this `subscription_item` belongs to. + maxLength: 5000 + type: string + tax_rates: + description: The tax rates which apply to this `subscription_item`. When + set, the `default_tax_rates` on the subscription do not apply to this + `subscription_item`. + items: + "$ref": "#/components/schemas/tax_rate" + nullable: true + type: array + required: + - created + - id + - metadata + - object + - price + - subscription + title: SubscriptionItem + type: object + x-expandableFields: + - billing_thresholds + - price + - tax_rates + x-resourceId: subscription_item + subscription_item_billing_thresholds: + description: '' + properties: + usage_gte: + description: Usage threshold that triggers the subscription to create an + invoice + nullable: true + type: integer + title: SubscriptionItemBillingThresholds + type: object + x-expandableFields: [] + subscription_pending_invoice_item_interval: + description: '' + properties: + interval: + description: Specifies invoicing frequency. Either `day`, `week`, `month` + or `year`. + enum: + - day + - month + - week + - year + type: string + interval_count: + description: The number of intervals between invoices. For example, `interval=month` + and `interval_count=3` bills every 3 months. Maximum of one year interval + allowed (1 year, 12 months, or 52 weeks). + type: integer + required: + - interval + - interval_count + title: SubscriptionPendingInvoiceItemInterval + type: object + x-expandableFields: [] + subscription_schedule: + description: |- + A subscription schedule allows you to create and manage the lifecycle of a subscription by predefining expected changes. + + Related guide: [Subscription Schedules](https://stripe.com/docs/billing/subscriptions/subscription-schedules). + properties: + canceled_at: + description: Time at which the subscription schedule was canceled. Measured + in seconds since the Unix epoch. + format: unix-time + nullable: true + type: integer + completed_at: + description: Time at which the subscription schedule was completed. Measured + in seconds since the Unix epoch. + format: unix-time + nullable: true + type: integer + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + current_phase: + anyOf: + - "$ref": "#/components/schemas/subscription_schedule_current_phase" + description: Object representing the start and end dates for the current + phase of the subscription schedule, if it is `active`. + nullable: true + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: ID of the customer who owns the subscription schedule. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + default_settings: + "$ref": "#/components/schemas/subscription_schedules_resource_default_settings" + description: Object representing the subscription schedule’s default settings. + end_behavior: + description: Behavior of the subscription schedule and underlying subscription + when it ends. Possible values are `release` and `cancel`. + enum: + - cancel + - none + - release + - renew + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - subscription_schedule + type: string + phases: + description: Configuration for the subscription schedule's phases. + items: + "$ref": "#/components/schemas/subscription_schedule_phase_configuration" + type: array + released_at: + description: Time at which the subscription schedule was released. Measured + in seconds since the Unix epoch. + format: unix-time + nullable: true + type: integer + released_subscription: + description: ID of the subscription once managed by the subscription schedule + (if it is released). + maxLength: 5000 + nullable: true + type: string + status: + description: The present status of the subscription schedule. Possible values + are `not_started`, `active`, `completed`, `released`, and `canceled`. + You can read more about the different states in our [behavior guide](https://stripe.com/docs/billing/subscriptions/subscription-schedules). + enum: + - active + - canceled + - completed + - not_started + - released + type: string + subscription: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/subscription" + description: ID of the subscription managed by the subscription schedule. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/subscription" + required: + - created + - customer + - default_settings + - end_behavior + - id + - livemode + - object + - phases + - status + title: SubscriptionSchedule + type: object + x-expandableFields: + - current_phase + - customer + - default_settings + - phases + - subscription + x-resourceId: subscription_schedule + subscription_schedule_add_invoice_item: + description: An Add Invoice Item describes the prices and quantities that will + be added as pending invoice items when entering a phase. + properties: + price: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/price" + - "$ref": "#/components/schemas/deleted_price" + description: ID of the price used to generate the invoice item. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/price" + - "$ref": "#/components/schemas/deleted_price" + quantity: + description: The quantity of the invoice item. + nullable: true + type: integer + tax_rates: + description: The tax rates which apply to the item. When set, the `default_tax_rates` + do not apply to this item. + items: + "$ref": "#/components/schemas/tax_rate" + nullable: true + type: array + required: + - price + title: SubscriptionScheduleAddInvoiceItem + type: object + x-expandableFields: + - price + - tax_rates + subscription_schedule_configuration_item: + description: A phase item describes the price and quantity of a phase. + properties: + billing_thresholds: + anyOf: + - "$ref": "#/components/schemas/subscription_item_billing_thresholds" + description: Define thresholds at which an invoice will be sent, and the + related subscription advanced to a new billing period + nullable: true + price: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/price" + - "$ref": "#/components/schemas/deleted_price" + description: ID of the price to which the customer should be subscribed. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/price" + - "$ref": "#/components/schemas/deleted_price" + quantity: + description: Quantity of the plan to which the customer should be subscribed. + type: integer + tax_rates: + description: The tax rates which apply to this `phase_item`. When set, the + `default_tax_rates` on the phase do not apply to this `phase_item`. + items: + "$ref": "#/components/schemas/tax_rate" + nullable: true + type: array + required: + - price + title: SubscriptionScheduleConfigurationItem + type: object + x-expandableFields: + - billing_thresholds + - price + - tax_rates + subscription_schedule_current_phase: + description: '' + properties: + end_date: + description: The end of this phase of the subscription schedule. + format: unix-time + type: integer + start_date: + description: The start of this phase of the subscription schedule. + format: unix-time + type: integer + required: + - end_date + - start_date + title: SubscriptionScheduleCurrentPhase + type: object + x-expandableFields: [] + subscription_schedule_phase_configuration: + description: A phase describes the plans, coupon, and trialing status of a subscription + for a predefined time period. + properties: + add_invoice_items: + description: A list of prices and quantities that will generate invoice + items appended to the first invoice for this phase. + items: + "$ref": "#/components/schemas/subscription_schedule_add_invoice_item" + type: array + application_fee_percent: + description: A non-negative decimal between 0 and 100, with at most two + decimal places. This represents the percentage of the subscription invoice + subtotal that will be transferred to the application owner's Stripe account + during this phase of the schedule. + nullable: true + type: number + automatic_tax: + "$ref": "#/components/schemas/schedules_phase_automatic_tax" + billing_cycle_anchor: + description: Possible values are `phase_start` or `automatic`. If `phase_start` + then billing cycle anchor of the subscription is set to the start of the + phase when entering the phase. If `automatic` then the billing cycle anchor + is automatically modified as needed when entering the phase. For more + information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + enum: + - automatic + - phase_start + nullable: true + type: string + billing_thresholds: + anyOf: + - "$ref": "#/components/schemas/subscription_billing_thresholds" + description: Define thresholds at which an invoice will be sent, and the + subscription advanced to a new billing period + nullable: true + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When charging + automatically, Stripe will attempt to pay the underlying subscription + at the end of each billing cycle using the default source attached to + the customer. When sending an invoice, Stripe will email your customer + an invoice with payment instructions. + enum: + - charge_automatically + - send_invoice + nullable: true + type: string + coupon: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/coupon" + - "$ref": "#/components/schemas/deleted_coupon" + description: ID of the coupon to use during this phase of the subscription + schedule. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/coupon" + - "$ref": "#/components/schemas/deleted_coupon" + default_payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the default payment method for the subscription schedule. + It must belong to the customer associated with the subscription schedule. + If not set, invoices will use the default payment method in the customer's + invoice settings. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + default_tax_rates: + description: The default tax rates to apply to the subscription during this + phase of the subscription schedule. + items: + "$ref": "#/components/schemas/tax_rate" + nullable: true + type: array + end_date: + description: The end of this phase of the subscription schedule. + format: unix-time + type: integer + invoice_settings: + anyOf: + - "$ref": "#/components/schemas/invoice_setting_subscription_schedule_setting" + description: The invoice settings applicable during this phase. + nullable: true + items: + description: Subscription items to configure the subscription to during + this phase of the subscription schedule. + items: + "$ref": "#/components/schemas/subscription_schedule_configuration_item" + type: array + proration_behavior: + description: If the subscription schedule will prorate when transitioning + to this phase. Possible values are `create_prorations` and `none`. + enum: + - always_invoice + - create_prorations + - none + type: string + start_date: + description: The start of this phase of the subscription schedule. + format: unix-time + type: integer + transfer_data: + anyOf: + - "$ref": "#/components/schemas/subscription_transfer_data" + description: The account (if any) the associated subscription's payments + will be attributed to for tax reporting, and where funds from each payment + will be transferred to for each of the subscription's invoices. + nullable: true + trial_end: + description: When the trial ends within the phase. + format: unix-time + nullable: true + type: integer + required: + - add_invoice_items + - end_date + - items + - proration_behavior + - start_date + title: SubscriptionSchedulePhaseConfiguration + type: object + x-expandableFields: + - add_invoice_items + - automatic_tax + - billing_thresholds + - coupon + - default_payment_method + - default_tax_rates + - invoice_settings + - items + - transfer_data + subscription_schedules_resource_default_settings: + description: 'Object representing the subscription schedule’s default settings' + properties: + application_fee_percent: + description: A non-negative decimal between 0 and 100, with at most two + decimal places. This represents the percentage of the subscription invoice + subtotal that will be transferred to the application owner's Stripe account + during this phase of the schedule. + nullable: true + type: number + automatic_tax: + "$ref": "#/components/schemas/subscription_schedules_resource_default_settings_automatic_tax" + billing_cycle_anchor: + description: Possible values are `phase_start` or `automatic`. If `phase_start` + then billing cycle anchor of the subscription is set to the start of the + phase when entering the phase. If `automatic` then the billing cycle anchor + is automatically modified as needed when entering the phase. For more + information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + enum: + - automatic + - phase_start + type: string + billing_thresholds: + anyOf: + - "$ref": "#/components/schemas/subscription_billing_thresholds" + description: Define thresholds at which an invoice will be sent, and the + subscription advanced to a new billing period + nullable: true + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When charging + automatically, Stripe will attempt to pay the underlying subscription + at the end of each billing cycle using the default source attached to + the customer. When sending an invoice, Stripe will email your customer + an invoice with payment instructions. + enum: + - charge_automatically + - send_invoice + nullable: true + type: string + default_payment_method: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/payment_method" + description: ID of the default payment method for the subscription schedule. + If not set, invoices will use the default payment method in the customer's + invoice settings. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/payment_method" + invoice_settings: + anyOf: + - "$ref": "#/components/schemas/invoice_setting_subscription_schedule_setting" + description: The subscription schedule's default invoice settings. + nullable: true + transfer_data: + anyOf: + - "$ref": "#/components/schemas/subscription_transfer_data" + description: The account (if any) the associated subscription's payments + will be attributed to for tax reporting, and where funds from each payment + will be transferred to for each of the subscription's invoices. + nullable: true + required: + - billing_cycle_anchor + title: SubscriptionSchedulesResourceDefaultSettings + type: object + x-expandableFields: + - automatic_tax + - billing_thresholds + - default_payment_method + - invoice_settings + - transfer_data + subscription_schedules_resource_default_settings_automatic_tax: + description: '' + properties: + enabled: + description: Whether Stripe automatically computes tax on invoices created + during this phase. + type: boolean + required: + - enabled + title: SubscriptionSchedulesResourceDefaultSettingsAutomaticTax + type: object + x-expandableFields: [] + subscription_transfer_data: + description: '' + properties: + amount_percent: + description: A non-negative decimal between 0 and 100, with at most two + decimal places. This represents the percentage of the subscription invoice + subtotal that will be transferred to the destination account. By default, + the entire amount is transferred to the destination. + nullable: true + type: number + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: The account where funds from the payment will be transferred + to upon payment success. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + required: + - destination + title: SubscriptionTransferData + type: object + x-expandableFields: + - destination + subscriptions_resource_pause_collection: + description: |- + The Pause Collection settings determine how we will pause collection for this subscription and for how long the subscription + should be paused. + properties: + behavior: + description: The payment collection behavior for this subscription while + paused. One of `keep_as_draft`, `mark_uncollectible`, or `void`. + enum: + - keep_as_draft + - mark_uncollectible + - void + type: string + resumes_at: + description: The time after which the subscription will resume collecting + payments. + format: unix-time + nullable: true + type: integer + required: + - behavior + title: SubscriptionsResourcePauseCollection + type: object + x-expandableFields: [] + subscriptions_resource_payment_method_options: + description: '' + properties: + bancontact: + anyOf: + - "$ref": "#/components/schemas/invoice_payment_method_options_bancontact" + description: This sub-hash contains details about the Bancontact payment + method options to pass to invoices created by the subscription. + nullable: true + card: + anyOf: + - "$ref": "#/components/schemas/invoice_payment_method_options_card" + description: This sub-hash contains details about the Card payment method + options to pass to invoices created by the subscription. + nullable: true + title: SubscriptionsResourcePaymentMethodOptions + type: object + x-expandableFields: + - bancontact + - card + subscriptions_resource_payment_settings: + description: '' + properties: + payment_method_options: + anyOf: + - "$ref": "#/components/schemas/subscriptions_resource_payment_method_options" + description: Payment-method-specific configuration to provide to invoices + created by the subscription. + nullable: true + payment_method_types: + description: The list of payment method types to provide to every invoice + created by the subscription. If not set, Stripe attempts to automatically + determine the types to use by looking at the invoice’s default payment + method, the subscription’s default payment method, the customer’s default + payment method, and your [invoice template settings](https://dashboard.stripe.com/settings/billing/invoice). + items: + enum: + - ach_credit_transfer + - ach_debit + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - fpx + - giropay + - ideal + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + nullable: true + type: array + title: SubscriptionsResourcePaymentSettings + type: object + x-expandableFields: + - payment_method_options + subscriptions_resource_pending_update: + description: |- + Pending Updates store the changes pending from a previous update that will be applied + to the Subscription upon successful payment. + properties: + billing_cycle_anchor: + description: If the update is applied, determines the date of the first + full invoice, and, for plans with `month` or `year` intervals, the day + of the month for subsequent invoices. + format: unix-time + nullable: true + type: integer + expires_at: + description: The point after which the changes reflected by this update + will be discarded and no longer applied. + format: unix-time + type: integer + subscription_items: + description: List of subscription items, each with an attached plan, that + will be set if the update is applied. + items: + "$ref": "#/components/schemas/subscription_item" + nullable: true + type: array + trial_end: + description: Unix timestamp representing the end of the trial period the + customer will get before being charged for the first time, if the update + is applied. + format: unix-time + nullable: true + type: integer + trial_from_plan: + description: Indicates if a plan's `trial_period_days` should be applied + to the subscription. Setting `trial_end` per subscription is preferred, + and this defaults to `false`. Setting this flag to `true` together with + `trial_end` is not allowed. + nullable: true + type: boolean + required: + - expires_at + title: SubscriptionsResourcePendingUpdate + type: object + x-expandableFields: + - subscription_items + tax_code: + description: "[Tax codes](https://stripe.com/docs/tax/tax-codes) classify goods + and services for tax purposes." + properties: + description: + description: A detailed description of which types of products the tax code + represents. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + name: + description: A short name for the tax code. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - tax_code + type: string + required: + - description + - id + - name + - object + title: TaxProductResourceTaxCode + type: object + x-expandableFields: [] + x-resourceId: tax_code + tax_deducted_at_source: + description: '' + properties: + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - tax_deducted_at_source + type: string + period_end: + description: The end of the invoicing period. This TDS applies to Stripe + fees collected during this invoicing period. + format: unix-time + type: integer + period_start: + description: The start of the invoicing period. This TDS applies to Stripe + fees collected during this invoicing period. + format: unix-time + type: integer + tax_deduction_account_number: + description: The TAN that was supplied to Stripe when TDS was assessed + maxLength: 5000 + type: string + required: + - id + - object + - period_end + - period_start + - tax_deduction_account_number + title: TaxDeductedAtSource + type: object + x-expandableFields: [] + tax_id: + description: |- + You can add one or multiple tax IDs to a [customer](https://stripe.com/docs/api/customers). + A customer's tax IDs are displayed on invoices and credit notes issued for the customer. + + Related guide: [Customer Tax Identification Numbers](https://stripe.com/docs/billing/taxes/tax-ids). + properties: + country: + description: Two-letter ISO code representing the country of the tax ID. + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + customer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/customer" + description: ID of the customer. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/customer" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - tax_id + type: string + type: + description: Type of the tax ID, one of `ae_trn`, `au_abn`, `au_arn`, `br_cnpj`, + `br_cpf`, `ca_bn`, `ca_gst_hst`, `ca_pst_bc`, `ca_pst_mb`, `ca_pst_sk`, + `ca_qst`, `ch_vat`, `cl_tin`, `es_cif`, `eu_vat`, `gb_vat`, `hk_br`, `id_npwp`, + `il_vat`, `in_gst`, `jp_cn`, `jp_rn`, `kr_brn`, `li_uid`, `mx_rfc`, `my_frp`, + `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `ru_inn`, `ru_kpp`, `sa_vat`, + `sg_gst`, `sg_uen`, `th_vat`, `tw_vat`, `us_ein`, or `za_vat`. Note that + some legacy tax IDs have type `unknown` + enum: + - ae_trn + - au_abn + - au_arn + - br_cnpj + - br_cpf + - ca_bn + - ca_gst_hst + - ca_pst_bc + - ca_pst_mb + - ca_pst_sk + - ca_qst + - ch_vat + - cl_tin + - es_cif + - eu_vat + - gb_vat + - hk_br + - id_npwp + - il_vat + - in_gst + - jp_cn + - jp_rn + - kr_brn + - li_uid + - mx_rfc + - my_frp + - my_itn + - my_sst + - no_vat + - nz_gst + - ru_inn + - ru_kpp + - sa_vat + - sg_gst + - sg_uen + - th_vat + - tw_vat + - unknown + - us_ein + - za_vat + type: string + value: + description: Value of the tax ID. + maxLength: 5000 + type: string + verification: + anyOf: + - "$ref": "#/components/schemas/tax_id_verification" + description: Tax ID verification information. + nullable: true + required: + - created + - id + - livemode + - object + - type + - value + title: tax_id + type: object + x-expandableFields: + - customer + - verification + x-resourceId: tax_id + tax_id_verification: + description: '' + properties: + status: + description: Verification status, one of `pending`, `verified`, `unverified`, + or `unavailable`. + enum: + - pending + - unavailable + - unverified + - verified + type: string + verified_address: + description: Verified address. + maxLength: 5000 + nullable: true + type: string + verified_name: + description: Verified name. + maxLength: 5000 + nullable: true + type: string + required: + - status + title: tax_id_verification + type: object + x-expandableFields: [] + tax_rate: + description: |- + Tax rates can be applied to [invoices](https://stripe.com/docs/billing/invoices/tax-rates), [subscriptions](https://stripe.com/docs/billing/subscriptions/taxes) and [Checkout Sessions](https://stripe.com/docs/payments/checkout/set-up-a-subscription#tax-rates) to collect tax. + + Related guide: [Tax Rates](https://stripe.com/docs/billing/taxes/tax-rates). + properties: + active: + description: Defaults to `true`. When set to `false`, this tax rate cannot + be used with new applications or Checkout Sessions, but will still work + for subscriptions and invoices that already have it set. + type: boolean + country: + description: Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)). + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + description: + description: An arbitrary string attached to the tax rate for your internal + use only. It will not be visible to your customers. + maxLength: 5000 + nullable: true + type: string + display_name: + description: The display name of the tax rates as it will appear to your + customer on their receipt email, PDF, and the hosted invoice page. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + inclusive: + description: This specifies if the tax rate is inclusive or exclusive. + type: boolean + jurisdiction: + description: The jurisdiction for the tax rate. You can use this label field + for tax reporting purposes. It also appears on your customer’s invoice. + maxLength: 5000 + nullable: true + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - tax_rate + type: string + percentage: + description: This represents the tax rate percent out of 100. + type: number + state: + description: '[ISO 3166-2 subdivision code](https://en.wikipedia.org/wiki/ISO_3166-2:US), + without country prefix. For example, "NY" for New York, United States.' + maxLength: 5000 + nullable: true + type: string + tax_type: + description: The high-level tax type, such as `vat` or `sales_tax`. + enum: + - gst + - hst + - pst + - qst + - sales_tax + - vat + nullable: true + type: string + required: + - active + - created + - display_name + - id + - inclusive + - livemode + - object + - percentage + title: TaxRate + type: object + x-expandableFields: [] + x-resourceId: tax_rate + terminal.connection_token: + description: |- + A Connection Token is used by the Stripe Terminal SDK to connect to a reader. + + Related guide: [Fleet Management](https://stripe.com/docs/terminal/creating-locations). + properties: + location: + description: The id of the location that this connection token is scoped + to. Note that location scoping only applies to internet-connected readers. + For more details, see [the docs on scoping connection tokens](https://stripe.com/docs/terminal/readers/fleet-management#connection-tokens). + maxLength: 5000 + type: string + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - terminal.connection_token + type: string + secret: + description: Your application should pass this token to the Stripe Terminal + SDK. + maxLength: 5000 + type: string + required: + - object + - secret + title: TerminalConnectionToken + type: object + x-expandableFields: [] + x-resourceId: terminal.connection_token + terminal.location: + description: |- + A Location represents a grouping of readers. + + Related guide: [Fleet Management](https://stripe.com/docs/terminal/creating-locations). + properties: + address: + "$ref": "#/components/schemas/address" + display_name: + description: The display name of the location. + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - terminal.location + type: string + required: + - address + - display_name + - id + - livemode + - metadata + - object + title: TerminalLocationLocation + type: object + x-expandableFields: + - address + x-resourceId: terminal.location + terminal.reader: + description: |- + A Reader represents a physical device for accepting payment details. + + Related guide: [Connecting to a Reader](https://stripe.com/docs/terminal/readers/connecting). + properties: + device_sw_version: + description: The current software version of the reader. + maxLength: 5000 + nullable: true + type: string + device_type: + description: Type of reader, one of `bbpos_chipper2x` or `verifone_P400`. + enum: + - bbpos_chipper2x + - verifone_P400 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + ip_address: + description: The local IP address of the reader. + maxLength: 5000 + nullable: true + type: string + label: + description: Custom label given to the reader for easier identification. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + location: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/terminal.location" + description: The location identifier of the reader. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/terminal.location" + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - terminal.reader + type: string + serial_number: + description: Serial number of the reader. + maxLength: 5000 + type: string + status: + description: The networking status of the reader. + maxLength: 5000 + nullable: true + type: string + required: + - device_type + - id + - label + - livemode + - metadata + - object + - serial_number + title: TerminalReaderReader + type: object + x-expandableFields: + - location + x-resourceId: terminal.reader + three_d_secure: + description: |- + Cardholder authentication via 3D Secure is initiated by creating a `3D Secure` + object. Once the object has been created, you can use it to authenticate the + cardholder and create a charge. + properties: + amount: + description: Amount of the charge that you will create when authentication + completes. + type: integer + authenticated: + description: True if the cardholder went through the authentication flow + and their bank indicated that authentication succeeded. + type: boolean + card: + "$ref": "#/components/schemas/card" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + maxLength: 5000 + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - three_d_secure + type: string + redirect_url: + description: If present, this is the URL that you should send the cardholder + to for authentication. If you are going to use Stripe.js to display the + authentication page in an iframe, you should use the value "_callback". + maxLength: 5000 + nullable: true + type: string + status: + description: Possible values are `redirect_pending`, `succeeded`, or `failed`. + When the cardholder can be authenticated, the object starts with status + `redirect_pending`. When liability will be shifted to the cardholder's + bank (either because the cardholder was successfully authenticated, or + because the bank has not implemented 3D Secure, the object wlil be in + status `succeeded`. `failed` indicates that authentication was attempted + unsuccessfully. + maxLength: 5000 + type: string + required: + - amount + - authenticated + - card + - created + - currency + - id + - livemode + - object + - status + title: ThreeDSecure + type: object + x-expandableFields: + - card + x-resourceId: three_d_secure + three_d_secure_details: + description: '' + properties: + authentication_flow: + description: |- + For authenticated transactions: how the customer was authenticated by + the issuing bank. + enum: + - challenge + - frictionless + nullable: true + type: string + result: + description: Indicates the outcome of 3D Secure authentication. + enum: + - attempt_acknowledged + - authenticated + - failed + - not_supported + - processing_error + nullable: true + type: string + x-stripeBypassValidation: true + result_reason: + description: |- + Additional information about why 3D Secure succeeded or failed based + on the `result`. + enum: + - abandoned + - bypassed + - canceled + - card_not_enrolled + - network_not_supported + - protocol_error + - rejected + nullable: true + type: string + version: + description: The version of 3D Secure that was used. + enum: + - 1.0.2 + - 2.1.0 + - 2.2.0 + nullable: true + type: string + title: three_d_secure_details + type: object + x-expandableFields: [] + three_d_secure_usage: + description: '' + properties: + supported: + description: Whether 3D Secure is supported on this card. + type: boolean + required: + - supported + title: three_d_secure_usage + type: object + x-expandableFields: [] + token: + description: |- + Tokenization is the process Stripe uses to collect sensitive card or bank + account details, or personally identifiable information (PII), directly from + your customers in a secure manner. A token representing this information is + returned to your server to use. You should use our + [recommended payments integrations](https://stripe.com/docs/payments) to perform this process + client-side. This ensures that no sensitive card data touches your server, + and allows your integration to operate in a PCI-compliant way. + + If you cannot use client-side tokenization, you can also create tokens using + the API with either your publishable or secret API key. Keep in mind that if + your integration uses this method, you are responsible for any PCI compliance + that may be required, and you must keep your secret API key safe. Unlike with + client-side tokenization, your customer's information is not sent directly to + Stripe, so we cannot determine how it is handled or stored. + + Tokens cannot be stored or used more than once. To store card or bank account + information for later use, you can create [Customer](https://stripe.com/docs/api#customers) + objects or [Custom accounts](https://stripe.com/docs/api#external_accounts). Note that + [Radar](https://stripe.com/docs/radar), our integrated solution for automatic fraud protection, + performs best with integrations that use client-side tokenization. + + Related guide: [Accept a payment](https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token) + properties: + bank_account: + "$ref": "#/components/schemas/bank_account" + card: + "$ref": "#/components/schemas/card" + client_ip: + description: IP address of the client that generated the token. + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - token + type: string + type: + description: 'Type of the token: `account`, `bank_account`, `card`, or `pii`.' + maxLength: 5000 + type: string + used: + description: Whether this token has already been used (tokens can be used + only once). + type: boolean + required: + - created + - id + - livemode + - object + - type + - used + title: Token + type: object + x-expandableFields: + - bank_account + - card + x-resourceId: token + topup: + description: |- + To top up your Stripe balance, you create a top-up object. You can retrieve + individual top-ups, as well as list all top-ups. Top-ups are identified by a + unique, random ID. + + Related guide: [Topping Up your Platform Account](https://stripe.com/docs/connect/top-ups). + properties: + amount: + description: Amount transferred. + type: integer + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: ID of the balance transaction that describes the impact of + this top-up on your account balance. May not be specified depending on + status of top-up. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + maxLength: 5000 + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + expected_availability_date: + description: Date the funds are expected to arrive in your Stripe account + for payouts. This factors in delays like weekends or bank holidays. May + not be specified depending on status of top-up. + nullable: true + type: integer + failure_code: + description: Error code explaining reason for top-up failure if available + (see [the errors section](https://stripe.com/docs/api#errors) for a list + of codes). + maxLength: 5000 + nullable: true + type: string + failure_message: + description: Message to user further explaining reason for top-up failure + if available. + maxLength: 5000 + nullable: true + type: string + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - topup + type: string + source: + "$ref": "#/components/schemas/source" + statement_descriptor: + description: Extra information about a top-up. This will appear on your + source's bank statement. It must contain at least one letter. + maxLength: 5000 + nullable: true + type: string + status: + description: The status of the top-up is either `canceled`, `failed`, `pending`, + `reversed`, or `succeeded`. + enum: + - canceled + - failed + - pending + - reversed + - succeeded + type: string + transfer_group: + description: A string that identifies this top-up as part of a group. + maxLength: 5000 + nullable: true + type: string + required: + - amount + - created + - currency + - id + - livemode + - metadata + - object + - source + - status + title: Topup + type: object + x-expandableFields: + - balance_transaction + - source + x-resourceId: topup + transfer: + description: |- + A `Transfer` object is created when you move funds between Stripe accounts as + part of Connect. + + Before April 6, 2017, transfers also represented movement of funds from a + Stripe account to a card or bank account. This behavior has since been split + out into a [Payout](https://stripe.com/docs/api#payout_object) object, with corresponding payout endpoints. For more + information, read about the + [transfer/payout split](https://stripe.com/docs/transfer-payout-split). + + Related guide: [Creating Separate Charges and Transfers](https://stripe.com/docs/connect/charges-transfers). + properties: + amount: + description: Amount in %s to be transferred. + type: integer + amount_reversed: + description: Amount in %s reversed (can be less than the amount attribute + on the transfer if a partial reversal was issued). + type: integer + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: Balance transaction that describes the impact of this transfer + on your account balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + created: + description: Time that this record of the transfer was first created. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + description: + description: An arbitrary string attached to the object. Often useful for + displaying to users. + maxLength: 5000 + nullable: true + type: string + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: ID of the Stripe account the transfer was sent to. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + destination_payment: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: If the destination is a Stripe account, this will be the ID + of the payment that the destination account received for the transfer. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - transfer + type: string + reversals: + description: A list of reversals that have been applied to the transfer. + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/transfer_reversal" + type: array + has_more: + description: True if this list has another page of items after this + one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: TransferReversalList + type: object + x-expandableFields: + - data + reversed: + description: Whether the transfer has been fully reversed. If the transfer + is only partially reversed, this attribute will still be false. + type: boolean + source_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/charge" + description: ID of the charge or payment that was used to fund the transfer. + If null, the transfer was funded from the available balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/charge" + source_type: + description: The source balance this transfer came from. One of `card`, + `fpx`, or `bank_account`. + maxLength: 5000 + nullable: true + type: string + transfer_group: + description: A string that identifies this transaction as part of a group. + See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) + for details. + maxLength: 5000 + nullable: true + type: string + required: + - amount + - amount_reversed + - created + - currency + - id + - livemode + - metadata + - object + - reversals + - reversed + title: Transfer + type: object + x-expandableFields: + - balance_transaction + - destination + - destination_payment + - reversals + - source_transaction + x-resourceId: transfer + transfer_data: + description: '' + properties: + amount: + description: Amount intended to be collected by this PaymentIntent. A positive + integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) + (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal + currency). The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). + The amount value supports up to eight digits (e.g., a value of 99999999 + for a USD charge of $999,999.99). + type: integer + destination: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/account" + description: |- + The account (if any) the payment will be attributed to for tax + reporting, and where funds from the payment will be transferred to upon + payment success. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/account" + required: + - destination + title: transfer_data + type: object + x-expandableFields: + - destination + transfer_reversal: + description: |- + [Stripe Connect](https://stripe.com/docs/connect) platforms can reverse transfers made to a + connected account, either entirely or partially, and can also specify whether + to refund any related application fees. Transfer reversals add to the + platform's balance and subtract from the destination account's balance. + + Reversing a transfer that was made for a [destination + charge](/docs/connect/destination-charges) is allowed only up to the amount of + the charge. It is possible to reverse a + [transfer_group](https://stripe.com/docs/connect/charges-transfers#transfer-options) + transfer only if the destination account has enough balance to cover the + reversal. + + Related guide: [Reversing Transfers](https://stripe.com/docs/connect/charges-transfers#reversing-transfers). + properties: + amount: + description: Amount, in %s. + type: integer + balance_transaction: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/balance_transaction" + description: Balance transaction that describes the impact on your account + balance. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/balance_transaction" + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + destination_payment_refund: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/refund" + description: Linked payment refund for the transfer reversal. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/refund" + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + nullable: true + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - transfer_reversal + type: string + source_refund: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/refund" + description: ID of the refund responsible for the transfer reversal. + nullable: true + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/refund" + transfer: + anyOf: + - maxLength: 5000 + type: string + - "$ref": "#/components/schemas/transfer" + description: ID of the transfer that was reversed. + x-expansionResources: + oneOf: + - "$ref": "#/components/schemas/transfer" + required: + - amount + - created + - currency + - id + - object + - transfer + title: TransferReversal + type: object + x-expandableFields: + - balance_transaction + - destination_payment_refund + - source_refund + - transfer + x-resourceId: transfer_reversal + transfer_schedule: + description: '' + properties: + delay_days: + description: The number of days charges for the account will be held before + being paid out. + type: integer + interval: + description: How frequently funds will be paid out. One of `manual` (payouts + only created via API call), `daily`, `weekly`, or `monthly`. + maxLength: 5000 + type: string + monthly_anchor: + description: The day of the month funds will be paid out. Only shown if + `interval` is monthly. Payouts scheduled between the 29th and 31st of + the month are sent on the last day of shorter months. + type: integer + weekly_anchor: + description: The day of the week funds will be paid out, of the style 'monday', + 'tuesday', etc. Only shown if `interval` is weekly. + maxLength: 5000 + type: string + required: + - delay_days + - interval + title: TransferSchedule + type: object + x-expandableFields: [] + transform_quantity: + description: '' + properties: + divide_by: + description: Divide usage by this number. + type: integer + round: + description: After division, either round the result `up` or `down`. + enum: + - down + - up + type: string + required: + - divide_by + - round + title: TransformQuantity + type: object + x-expandableFields: [] + transform_usage: + description: '' + properties: + divide_by: + description: Divide usage by this number. + type: integer + round: + description: After division, either round the result `up` or `down`. + enum: + - down + - up + type: string + required: + - divide_by + - round + title: TransformUsage + type: object + x-expandableFields: [] + usage_record: + description: |- + Usage records allow you to report customer usage and metrics to Stripe for + metered billing of subscription prices. + + Related guide: [Metered Billing](https://stripe.com/docs/billing/subscriptions/metered-billing). + properties: + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - usage_record + type: string + quantity: + description: The usage quantity for the specified date. + type: integer + subscription_item: + description: The ID of the subscription item this usage record contains + data for. + maxLength: 5000 + type: string + timestamp: + description: The timestamp when this usage occurred. + format: unix-time + type: integer + required: + - id + - livemode + - object + - quantity + - subscription_item + - timestamp + title: UsageRecord + type: object + x-expandableFields: [] + x-resourceId: usage_record + usage_record_summary: + description: '' + properties: + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + invoice: + description: The invoice in which this usage period has been billed for. + maxLength: 5000 + nullable: true + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - usage_record_summary + type: string + period: + "$ref": "#/components/schemas/period" + subscription_item: + description: The ID of the subscription item this summary is describing. + maxLength: 5000 + type: string + total_usage: + description: The total usage within this usage period. + type: integer + required: + - id + - livemode + - object + - period + - subscription_item + - total_usage + title: UsageRecordSummary + type: object + x-expandableFields: + - period + x-resourceId: usage_record_summary + verification_session_redaction: + description: '' + properties: + status: + description: Indicates whether this object and its related objects have + been redacted or not. + enum: + - processing + - redacted + type: string + required: + - status + title: verification_session_redaction + type: object + x-expandableFields: [] + webhook_endpoint: + description: |- + You can configure [webhook endpoints](https://stripe.com/docs/webhooks/) via the API to be + notified about events that happen in your Stripe account or connected + accounts. + + Most users configure webhooks from [the dashboard](https://dashboard.stripe.com/webhooks), which provides a user interface for registering and testing your webhook endpoints. + + Related guide: [Setting up Webhooks](https://stripe.com/docs/webhooks/configure). + properties: + api_version: + description: The API version events are rendered as for this webhook endpoint. + maxLength: 5000 + nullable: true + type: string + application: + description: The ID of the associated Connect application. + maxLength: 5000 + nullable: true + type: string + created: + description: Time at which the object was created. Measured in seconds since + the Unix epoch. + format: unix-time + type: integer + description: + description: An optional description of what the webhook is used for. + maxLength: 5000 + nullable: true + type: string + enabled_events: + description: The list of events to enable for this endpoint. `['*']` indicates + that all events are enabled, except those that require explicit selection. + items: + maxLength: 5000 + type: string + type: array + id: + description: Unique identifier for the object. + maxLength: 5000 + type: string + livemode: + description: Has the value `true` if the object exists in live mode or the + value `false` if the object exists in test mode. + type: boolean + metadata: + additionalProperties: + maxLength: 500 + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing additional + information about the object in a structured format. + type: object + object: + description: String representing the object's type. Objects of the same + type share the same value. + enum: + - webhook_endpoint + type: string + secret: + description: The endpoint's secret, used to generate [webhook signatures](https://stripe.com/docs/webhooks/signatures). + Only returned at creation. + maxLength: 5000 + type: string + status: + description: The status of the webhook. It can be `enabled` or `disabled`. + maxLength: 5000 + type: string + url: + description: The URL of the webhook endpoint. + maxLength: 5000 + type: string + required: + - created + - enabled_events + - id + - livemode + - metadata + - object + - status + - url + title: NotificationWebhookEndpoint + type: object + x-expandableFields: [] + x-resourceId: webhook_endpoint + securitySchemes: + basicAuth: + description: 'Basic HTTP authentication. Allowed headers-- Authorization: Basic + | Authorization: Basic ' + scheme: basic + type: http + bearerAuth: + bearerFormat: auth-scheme + description: 'Bearer HTTP authentication. Allowed headers-- Authorization: Bearer + ' + scheme: bearer + type: http +info: + contact: + email: dev-platform@stripe.com + name: Stripe Dev Platform Team + url: https://stripe.com + description: > + This is a generated connector for [Stripe API v1](https://stripe.com/docs/api) OpenAPI Specification. + + Stripe offers payment processing software and application programming interfaces for e-commerce websites and mobile applications. + + The Stripe API is organized around REST. Our API has predictable resource-oriented URLs, accepts form-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs. + termsOfService: https://stripe.com/us/terms/ + title: Stripe API + version: '2020-08-27' + x-stripeSpecFilename: spec3 + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Create a [Stripe](https://dashboard.stripe.com/login) account and obtain API Key following [this guide](https://stripe.com/docs/api/authentication). + + Provide obtained API Key as the token at connector initialization. Configure required permissions when generating the API Key. + x-ballerina-display: + label: Stripe + iconPath: "icon.png" +openapi: 3.0.0 +servers: + - url: 'https://api.stripe.com/' +tags: + - description: Customers + name: Customers + - description: Payment Methods + name: Payment_Methods + - description: Subscriptions + name: Subscriptions + - description: Subscription Items + name: Subscription_Items + - description: A subscription schedule allows you to create and manage the lifecycle of a subscription by predefining expected changes. + name: Subscription_Schedule + - description: Usage Records + name: Usage_Records + - description: Invoices + name: Invoices + - description: Products + name: Products + - description: Price + name: Price + - description: "A coupon contains information about a percent-off or amount-off discount you might want to apply to a customer." + name: Coupons +paths: + "/v1/coupons": + get: + tags: + - "Coupons" + description: "

Returns a list of your coupons.

" + operationId: listCoupons + parameters: + - description: A filter on the list, based on the object `created` field. The + value can be a string with an integer Unix timestamp, or it can be a dictionary + with a number of different query options. + explode: true + in: query + name: created + required: false + schema: + $ref: '#/components/schemas/CreatedDetails' + style: deepObject + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + items: + "$ref": "#/components/schemas/coupon" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + pattern: "^/v1/coupons" + type: string + required: + - data + - has_more + - object + - url + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/coupons/{coupon}": + get: + tags: + - "Coupons" + description: "

Retrieves the coupon with the given ID.

" + operationId: getCoupon + parameters: + - in: path + name: coupon + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Coupon Id + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/coupon" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/customers": + post: + description: "

Creates a new customer object.

" + operationId: createCustomer + tags: + - "Customers" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + address: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + invoice_settings: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + preferred_locales: + explode: true + style: deepObject + shipping: + explode: true + style: deepObject + tax: + explode: true + style: deepObject + tax_id_data: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + address: + anyOf: + - $ref: "#/components/schemas/customer_adresss" + - type: string + description: The customer's address. + balance: + description: An integer amount in %s that represents the customer's + current balance, which affect the customer's future invoices. + A negative amount represents a credit that decreases the amount + due on an invoice; a positive amount increases the amount due + on an invoice. + type: integer + coupon: + maxLength: 5000 + type: string + description: + description: An arbitrary string that you can attach to a customer + object. It is displayed alongside the customer in the dashboard. + maxLength: 5000 + type: string + email: + description: Customer's email address. It's displayed alongside + the customer in your dashboard and can be useful for searching + and tracking. This may be up to *512 characters*. + maxLength: 512 + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + invoice_prefix: + description: The prefix for the customer used to generate unique + invoice numbers. Must be 3–12 uppercase letters or numbers. + maxLength: 5000 + type: string + invoice_settings: + description: Default invoice settings for this customer. + properties: + custom_fields: + anyOf: + - items: + properties: + name: + maxLength: 30 + type: string + value: + maxLength: 30 + type: string + required: + - name + - value + title: custom_field_params + type: object + type: array + - enum: + - '' + type: string + default_payment_method: + maxLength: 5000 + type: string + footer: + maxLength: 5000 + type: string + title: customer_param + type: object + metadata: + anyOf: + - $ref: "#/components/schemas/additional_properties" + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + name: + description: The customer's full name or business name. + maxLength: 256 + type: string + next_invoice_sequence: + description: The sequence to be used on the customer's next invoice. + Defaults to 1. + type: integer + payment_method: + maxLength: 5000 + type: string + phone: + description: The customer's phone number. + maxLength: 20 + type: string + preferred_locales: + description: Customer's preferred languages, ordered by preference. + items: + maxLength: 5000 + type: string + type: array + promotion_code: + description: The API ID of a promotion code to apply to the customer. + The customer will have a discount applied on all recurring payments. + Charges you create through the API will not have the discount. + maxLength: 5000 + type: string + shipping: + anyOf: + - $ref: "#/components/schemas/customer_address_with_name" + - type: string + description: The customer's shipping information. Appears on invoices + emailed to this customer. + source: + maxLength: 5000 + type: string + x-stripeBypassValidation: true + tax: + description: Tax details about the customer. + properties: + ip_address: + anyOf: + - type: string + - enum: + - '' + type: string + title: tax_param + type: object + tax_exempt: + description: The customer's tax exemption. One of `none`, `exempt`, + or `reverse`. + enum: + - '' + - exempt + - none + - reverse + type: string + tax_id_data: + description: The customer's tax IDs. + items: + properties: + type: + enum: + - ae_trn + - au_abn + - au_arn + - br_cnpj + - br_cpf + - ca_bn + - ca_gst_hst + - ca_pst_bc + - ca_pst_mb + - ca_pst_sk + - ca_qst + - ch_vat + - cl_tin + - es_cif + - eu_vat + - gb_vat + - hk_br + - id_npwp + - il_vat + - in_gst + - jp_cn + - jp_rn + - kr_brn + - li_uid + - mx_rfc + - my_frp + - my_itn + - my_sst + - no_vat + - nz_gst + - ru_inn + - ru_kpp + - sa_vat + - sg_gst + - sg_uen + - th_vat + - tw_vat + - us_ein + - za_vat + maxLength: 5000 + type: string + x-stripeBypassValidation: true + value: + type: string + required: + - type + - value + title: data_params + type: object + type: array + type: object + description: Customer details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/customer" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/customers/{customer}": + get: + description: "

Retrieves the details of an existing customer. You need only + supply the unique customer identifier that was returned upon customer creation.

" + operationId: getCustomer + tags: + - "Customers" + parameters: + - in: path + name: customer + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Customer Id + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + responses: + '200': + content: + application/json: + schema: + anyOf: + - "$ref": "#/components/schemas/customer" + - "$ref": "#/components/schemas/deleted_customer" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: |- +

Updates the specified customer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. For example, if you pass the source parameter, that becomes the customer’s active source (e.g., a card) to be used for all charges in the future. When you update a customer to a new valid card source by passing the source parameter: for each of the customer’s current subscriptions, if the subscription bills automatically and is in the past_due state, then the latest open invoice for the subscription with automatic collection enabled will be retried. This retry will not count as an automatic retry, and will not affect the next regularly scheduled payment for the invoice. Changing the default_source for a customer will not trigger this behavior.

+ +

This request accepts mostly the same arguments as the customer creation call.

+ operationId: updateCustomer + tags: + - "Customers" + parameters: + - in: path + name: customer + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Customer Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + address: + explode: true + style: deepObject + bank_account: + explode: true + style: deepObject + card: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + invoice_settings: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + preferred_locales: + explode: true + style: deepObject + shipping: + explode: true + style: deepObject + tax: + explode: true + style: deepObject + trial_end: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + address: + anyOf: + - $ref: "#/components/schemas/customer_adresss" + - type: string + description: The customer's address. + balance: + description: An integer amount in %s that represents the customer's + current balance, which affect the customer's future invoices. + A negative amount represents a credit that decreases the amount + due on an invoice; a positive amount increases the amount due + on an invoice. + type: integer + bank_account: + anyOf: + - $ref: "#/components/schemas/customer_bank_account_details" + - maxLength: 5000 + type: string + description: Either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/js), + or a dictionary containing a user's bank account details. + card: + anyOf: + - $ref: "#/components/schemas/customer_card_details" + - maxLength: 5000 + type: string + description: A token, like the ones returned by [Stripe.js](https://stripe.com/docs/js). + x-stripeBypassValidation: true + coupon: + maxLength: 5000 + type: string + default_alipay_account: + description: ID of Alipay account to make the customer's new default + for invoice payments. + maxLength: 500 + type: string + default_bank_account: + description: ID of bank account to make the customer's new default + for invoice payments. + maxLength: 500 + type: string + default_card: + description: ID of card to make the customer's new default for invoice + payments. + maxLength: 500 + type: string + default_source: + description: |- + If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) parameter. + + Provide the ID of a payment source already attached to this customer to make it this customer's default payment source. + + If you want to add a new payment source and make it the default, see the [source](https://stripe.com/docs/api/customers/update#update_customer-source) property. + maxLength: 500 + type: string + description: + description: An arbitrary string that you can attach to a customer + object. It is displayed alongside the customer in the dashboard. + maxLength: 5000 + type: string + email: + description: Customer's email address. It's displayed alongside + the customer in your dashboard and can be useful for searching + and tracking. This may be up to *512 characters*. + maxLength: 512 + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + invoice_prefix: + description: The prefix for the customer used to generate unique + invoice numbers. Must be 3–12 uppercase letters or numbers. + maxLength: 5000 + type: string + invoice_settings: + description: Default invoice settings for this customer. + properties: + custom_fields: + anyOf: + - $ref: "#/components/schemas/invoice_settings_custom_fields" + - enum: + - '' + type: string + default_payment_method: + maxLength: 5000 + type: string + footer: + maxLength: 5000 + type: string + title: customer_param + type: object + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + name: + description: The customer's full name or business name. + maxLength: 256 + type: string + next_invoice_sequence: + description: The sequence to be used on the customer's next invoice. + Defaults to 1. + type: integer + phone: + description: The customer's phone number. + maxLength: 20 + type: string + preferred_locales: + description: Customer's preferred languages, ordered by preference. + items: + maxLength: 5000 + type: string + type: array + promotion_code: + description: The API ID of a promotion code to apply to the customer. + The customer will have a discount applied on all recurring payments. + Charges you create through the API will not have the discount. + maxLength: 5000 + type: string + shipping: + anyOf: + - $ref: "#/components/schemas/customer_shipping_address" + - enum: + - '' + type: string + description: The customer's shipping information. Appears on invoices + emailed to this customer. + source: + maxLength: 5000 + type: string + x-stripeBypassValidation: true + tax: + description: Tax details about the customer. + properties: + ip_address: + anyOf: + - type: string + - enum: + - '' + type: string + title: tax_param + type: object + tax_exempt: + description: The customer's tax exemption. One of `none`, `exempt`, + or `reverse`. + enum: + - '' + - exempt + - none + - reverse + type: string + trial_end: + anyOf: + - enum: + - now + maxLength: 5000 + type: string + - format: unix-time + type: integer + description: Unix timestamp representing the end of the trial period + the customer will get before being charged for the first time. + This will always overwrite any trials that might apply via a subscribed + plan. If set, trial_end will override the default trial period + of the plan the customer is being subscribed to. The special value + `now` can be provided to end the customer's trial immediately. + Can be at most two years from `billing_cycle_anchor`. + type: object + description: Customer details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/customer" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + delete: + description: "

Permanently deletes a customer. It cannot be undone. Also immediately + cancels any active subscriptions on the customer.

" + operationId: DeleteCustomer + tags: + - "Customers" + parameters: + - in: path + name: customer + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Customer Id + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/deleted_customer" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices": + get: + description: "

You can list all invoices, or list the invoices for a specific + customer. The invoices are returned sorted by creation date, with the most + recently created invoices appearing first.

" + operationId: ListInvoices + tags: + - "Invoices" + parameters: + - description: The collection method of the invoice to retrieve. Either `charge_automatically` + or `send_invoice`. + in: query + name: collection_method + required: false + schema: + enum: + - charge_automatically + - send_invoice + type: string + style: form + - explode: true + in: query + name: created + required: false + schema: + anyOf: + - $ref: "#/components/schemas/range_query_specs" + - type: integer + style: deepObject + description: A filter on the list based on the object created field. The value can be a string with an integer Unix timestamp, or it can be a dictionary + - description: Only return invoices for the customer specified by this customer + ID. + in: query + name: customer + required: false + schema: + maxLength: 5000 + type: string + style: form + - explode: true + in: query + name: due_date + required: false + schema: + anyOf: + - $ref: "#/components/schemas/range_query_specs" + - type: integer + style: deepObject + description: A filter on the list based on the object due_date field. The value can be an integer Unix timestamp, or it can be a dictionary + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, + or `void`. [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview) + in: query + name: status + required: false + schema: + enum: + - draft + - open + - paid + - uncollectible + - void + maxLength: 5000 + type: string + style: form + - description: Only return invoices for the subscription specified by this subscription + ID. + in: query + name: subscription + required: false + schema: + maxLength: 5000 + type: string + style: form + + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + items: + "$ref": "#/components/schemas/invoice" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + pattern: "^/v1/invoices" + type: string + required: + - data + - has_more + - object + - url + title: InvoicesList + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description:

This endpoint creates a draft invoice for a given customer. + The draft invoice created pulls in all pending invoice items on that customer, + including prorations. The invoice remains a draft until you finalize + the invoice, which allows you to pay or send + the invoice to your customers.

+ operationId: createInvoice + tags: + - "Invoices" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + account_tax_ids: + explode: true + style: deepObject + automatic_tax: + explode: true + style: deepObject + custom_fields: + explode: true + style: deepObject + default_tax_rates: + explode: true + style: deepObject + discounts: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + payment_settings: + explode: true + style: deepObject + transfer_data: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + account_tax_ids: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + description: The account tax IDs associated with the invoice. Only + editable when the invoice is a draft. + application_fee_amount: + description: A fee in %s that will be applied to the invoice and + transferred to the application owner's Stripe account. The request + must be made with an OAuth key or the Stripe-Account header in + order to take an application fee. For more information, see the + application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + type: integer + auto_advance: + description: Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) + of the invoice. When `false`, the invoice's state will not automatically + advance without an explicit action. + type: boolean + automatic_tax: + description: Settings for automatic tax lookup for this invoice. + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_param + type: object + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When + charging automatically, Stripe will attempt to pay this invoice + using the default source attached to the customer. When sending + an invoice, Stripe will email this invoice to the customer with + payment instructions. Defaults to `charge_automatically`. + enum: + - charge_automatically + - send_invoice + type: string + custom_fields: + anyOf: + - $ref: "#/components/schemas/invoice_settings_custom_fields" + - enum: + - '' + type: string + description: A list of up to 4 custom fields to be displayed on + the invoice. + customer: + description: The ID of the customer who will be billed. + maxLength: 5000 + type: string + days_until_due: + description: The number of days from when the invoice is created + until it is due. Valid only for invoices where `collection_method=send_invoice`. + type: integer + default_payment_method: + description: ID of the default payment method for the invoice. It + must belong to the customer associated with the invoice. If not + set, defaults to the subscription's default payment method, if + any, or to the default payment method in the customer's invoice + settings. + maxLength: 5000 + type: string + default_source: + description: ID of the default payment source for the invoice. It + must belong to the customer associated with the invoice and be + in a chargeable state. If not set, defaults to the subscription's + default source, if any, or to the customer's default source. + maxLength: 5000 + type: string + default_tax_rates: + description: The tax rates that will apply to any line item that + does not have `tax_rates` set. + items: + maxLength: 5000 + type: string + type: array + description: + description: An arbitrary string attached to the object. Often useful + for displaying to users. Referenced as 'memo' in the Dashboard. + maxLength: 1500 + type: string + discounts: + anyOf: + - $ref: '#/components/schemas/discounts_data_param' + - enum: + - '' + type: string + description: The coupons to redeem into discounts for the invoice. + If not specified, inherits the discount from the invoice's customer. + Pass an empty string to avoid inheriting any discounts. + due_date: + description: The date on which payment for this invoice is due. + Valid only for invoices where `collection_method=send_invoice`. + format: unix-time + type: integer + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + footer: + description: Footer to be displayed on the invoice. + maxLength: 5000 + type: string + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + on_behalf_of: + description: The account (if any) for which the funds of the invoice + payment are intended. If set, the invoice will be presented with + the branding and support information of the specified account. + See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) + documentation for details. + type: string + payment_settings: + description: Configuration settings for the PaymentIntent that is + generated when the invoice is finalized. + properties: + payment_method_options: + properties: + bancontact: + anyOf: + - properties: + preferred_language: + enum: + - de + - en + - fr + - nl + type: string + title: invoice_payment_method_options_param + type: object + - enum: + - '' + type: string + card: + anyOf: + - properties: + request_three_d_secure: + enum: + - any + - automatic + type: string + title: invoice_payment_method_options_param + type: object + - enum: + - '' + type: string + title: payment_method_options + type: object + payment_method_types: + anyOf: + - items: + enum: + - ach_credit_transfer + - ach_debit + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - fpx + - giropay + - ideal + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + type: array + - enum: + - '' + type: string + title: payment_settings + type: object + statement_descriptor: + description: Extra information about a charge for the customer's + credit card statement. It must contain at least one letter. If + not specified and this invoice is part of a subscription, the + default `statement_descriptor` will be set to the first subscription + item's product's `statement_descriptor`. + maxLength: 22 + type: string + subscription: + description: The ID of the subscription to invoice, if any. If not + set, the created invoice will include all pending invoice items + for the customer. If set, the created invoice will only include + pending invoice items for that subscription and pending invoice + items not associated with any subscription. The subscription's + billing cycle and regular subscription events won't be affected. + maxLength: 5000 + type: string + transfer_data: + description: If specified, the funds from the invoice will be transferred + to the destination and the ID of the resulting transfer will be + found on the invoice's charge. + properties: + amount: + type: integer + destination: + type: string + required: + - destination + title: transfer_data_specs + type: object + required: + - customer + type: object + required: true + description: Invoice details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/{invoice}": + delete: + description:

Permanently deletes a one-off invoice draft. This cannot be + undone. Attempts to delete invoices that are no longer in a draft state will + fail; once an invoice has been finalized or if an invoice is for a subscription, + it must be voided.

+ operationId: deleteInvoice + tags: + - "Invoices" + parameters: + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/deleted_invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + get: + description: "

Retrieves the invoice with the given ID.

" + operationId: getInvoice + tags: + - "Invoices" + parameters: + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: |- +

Draft invoices are fully editable. Once an invoice is finalized, + monetary values, as well as collection_method, become uneditable.

+ +

If you would like to stop the Stripe Billing engine from automatically finalizing, reattempting payments on, + sending reminders for, or automatically reconciling invoices, pass + auto_advance=false.

+ operationId: updateInvoice + tags: + - "Invoices" + parameters: + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + account_tax_ids: + explode: true + style: deepObject + automatic_tax: + explode: true + style: deepObject + custom_fields: + explode: true + style: deepObject + default_tax_rates: + explode: true + style: deepObject + discounts: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + on_behalf_of: + explode: true + style: deepObject + payment_settings: + explode: true + style: deepObject + transfer_data: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + account_tax_ids: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + description: The account tax IDs associated with the invoice. Only + editable when the invoice is a draft. + application_fee_amount: + description: A fee in %s that will be applied to the invoice and + transferred to the application owner's Stripe account. The request + must be made with an OAuth key or the Stripe-Account header in + order to take an application fee. For more information, see the + application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees). + type: integer + auto_advance: + description: Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) + of the invoice. + type: boolean + automatic_tax: + description: Settings for automatic tax lookup for this invoice. + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_param + type: object + collection_method: + description: Either `charge_automatically` or `send_invoice`. This + field can be updated only on `draft` invoices. + enum: + - charge_automatically + - send_invoice + type: string + custom_fields: + anyOf: + - $ref: "#/components/schemas/invoice_settings_custom_fields" + - enum: + - '' + type: string + description: A list of up to 4 custom fields to be displayed on + the invoice. If a value for `custom_fields` is specified, the + list specified will replace the existing custom field list on + this invoice. Pass an empty string to remove previously-defined + fields. + days_until_due: + description: The number of days from which the invoice is created + until it is due. Only valid for invoices where `collection_method=send_invoice`. + This field can only be updated on `draft` invoices. + type: integer + default_payment_method: + description: ID of the default payment method for the invoice. It + must belong to the customer associated with the invoice. If not + set, defaults to the subscription's default payment method, if + any, or to the default payment method in the customer's invoice + settings. + maxLength: 5000 + type: string + default_source: + description: ID of the default payment source for the invoice. It + must belong to the customer associated with the invoice and be + in a chargeable state. If not set, defaults to the subscription's + default source, if any, or to the customer's default source. + maxLength: 5000 + type: string + default_tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + description: The tax rates that will apply to any line item that + does not have `tax_rates` set. Pass an empty string to remove + previously-defined tax rates. + description: + description: An arbitrary string attached to the object. Often useful + for displaying to users. Referenced as 'memo' in the Dashboard. + maxLength: 1500 + type: string + discounts: + anyOf: + - $ref: "#/components/schemas/discounts_data_param" + - enum: + - '' + type: string + description: The discounts that will apply to the invoice. Pass + an empty string to remove previously-defined discounts. + due_date: + description: The date on which payment for this invoice is due. + Only valid for invoices where `collection_method=send_invoice`. + This field can only be updated on `draft` invoices. + format: unix-time + type: integer + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + footer: + description: Footer to be displayed on the invoice. + maxLength: 5000 + type: string + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + on_behalf_of: + anyOf: + - type: string + - enum: + - '' + type: string + description: The account (if any) for which the funds of the invoice + payment are intended. If set, the invoice will be presented with + the branding and support information of the specified account. + See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) + documentation for details. + payment_settings: + description: Configuration settings for the PaymentIntent that is + generated when the invoice is finalized. + properties: + payment_method_options: + properties: + bancontact: + anyOf: + - properties: + preferred_language: + enum: + - de + - en + - fr + - nl + type: string + title: invoice_payment_method_options_param + type: object + - enum: + - '' + type: string + card: + anyOf: + - properties: + request_three_d_secure: + enum: + - any + - automatic + type: string + title: invoice_payment_method_options_param + type: object + - enum: + - '' + type: string + title: payment_method_options + type: object + payment_method_types: + anyOf: + - items: + enum: + - ach_credit_transfer + - ach_debit + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - fpx + - giropay + - ideal + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + type: array + - enum: + - '' + type: string + title: payment_settings + type: object + statement_descriptor: + description: Extra information about a charge for the customer's + credit card statement. It must contain at least one letter. If + not specified and this invoice is part of a subscription, the + default `statement_descriptor` will be set to the first subscription + item's product's `statement_descriptor`. + maxLength: 22 + type: string + transfer_data: + anyOf: + - $ref: "#/components/schemas/discounts_data_param" + - enum: + - '' + type: string + description: If specified, the funds from the invoice will be transferred + to the destination and the ID of the resulting transfer will be + found on the invoice's charge. This will be unset if you POST + an empty value. + type: object + required: false + description: Invoice details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/{invoice}/pay": + post: + description:

Stripe automatically creates and then attempts to collect payment + on invoices for customers on subscriptions according to your subscriptions + settings. However, if you’d like to attempt payment on an invoice out + of the normal collection schedule or for some other reason, you can do so.

+ operationId: payInvoice + tags: + - "Invoices" + parameters: + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + forgive: + description: "In cases where the source used to pay the invoice + has insufficient funds, passing `forgive=true` controls whether + a charge should be attempted for the full amount available on + the source, up to the amount to fully pay the invoice. This effectively + forgives the difference between the amount available on the source + and the amount due. \n\nPassing `forgive=false` will fail the + charge if the source hasn't been pre-funded with the right amount. + An example for this case is with ACH Credit Transfers and wires: + if the amount wired is less than the amount due by a small amount, + you might want to forgive the difference. Defaults to `false`." + type: boolean + off_session: + description: Indicates if a customer is on or off-session while + an invoice payment is attempted. Defaults to `true` (off-session). + type: boolean + paid_out_of_band: + description: Boolean representing whether an invoice is paid outside + of Stripe. This will result in no charge being made. Defaults + to `false`. + type: boolean + payment_method: + description: A PaymentMethod to be charged. The PaymentMethod must + be the ID of a PaymentMethod belonging to the customer associated + with the invoice being paid. + maxLength: 5000 + type: string + source: + description: A payment source to be charged. The source must be + the ID of a source belonging to the customer associated with the + invoice being paid. + maxLength: 5000 + type: string + type: object + required: false + description: Invoice payment details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/{invoice}/send": + post: + description: |- +

Stripe will automatically send invoices to customers according to your subscriptions settings. However, if you’d like to manually send an invoice to your customer out of the normal schedule, you can do so. When sending invoices that have already been paid, there will be no reference to the payment in the email.

+ +

Requests made in test-mode result in no emails being sent, despite sending an invoice.sent event.

+ operationId: sendInvoice + tags: + - "Invoices" + parameters: + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + type: object + required: false + description: Invoice details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/{invoice}/void": + post: + description:

Mark a finalized invoice as void. This cannot be undone. Voiding + an invoice is similar to deletion, however it + only applies to finalized invoices and maintains a papertrail where the invoice + can still be found.

+ operationId: voidInvoice + tags: + - "Invoices" + parameters: + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + type: object + required: false + description: Invoice details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/{invoice}/mark_uncollectible": + post: + description: "

Marking an invoice as uncollectible is useful for keeping track + of bad debts that can be written off for accounting purposes.

" + operationId: markInvoiceUncollectable + tags: + - "Invoices" + parameters: + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + type: object + required: false + description: Invoice details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/{invoice}/lines": + get: + description: "

When retrieving an invoice, you’ll get a lines + property containing the total count of line items and the first handful of + those items. There is also a URL where you can retrieve the full (paginated) + list of line items.

" + operationId: GetInvoicesInvoiceLines + tags: + - "Invoices" + parameters: + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - in: path + name: invoice + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Invoice Id + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/line_item" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: InvoiceLinesList + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/upcoming": + get: + description: |- +

At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discounts that are applicable to the invoice.

+ +

Note that when you are viewing an upcoming invoice, you are simply viewing a preview – the invoice has not yet been created. As such, the upcoming invoice will not show up in invoice listing calls, and you cannot use the API to pay or edit the invoice. If you want to change the amount that your customer will be billed, you can add, remove, or update pending invoice items, or update the customer’s discount.

+ +

You can preview the effects of updating a subscription, including a preview of what proration will take place. To ensure that the actual proration is calculated exactly the same as the previewed proration, you should pass a proration_date parameter when doing the actual subscription update. The value passed in should be the same as the subscription_proration_date returned on the upcoming invoice resource. The recommended way to get only the prorations being previewed is to consider only proration line items where period[start] is equal to the subscription_proration_date on the upcoming invoice resource.

+ operationId: GetInvoicesUpcoming + tags: + - "Invoices" + parameters: + - description: Settings for automatic tax lookup for this invoice preview. + explode: true + in: query + name: automatic_tax + required: false + schema: + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_param + type: object + style: deepObject + - description: The code of the coupon to apply. If `subscription` or `subscription_items` + is provided, the invoice returned will preview updating or creating a subscription + with that coupon. Otherwise, it will preview applying that coupon to the + customer for the next upcoming invoice from among the customer's subscriptions. + The invoice can be previewed without a coupon by passing this value as an + empty string. + in: query + name: coupon + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: The identifier of the customer whose upcoming invoice you'd like + to retrieve. + in: query + name: customer + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: Details about the customer you want to invoice or overrides for + an existing customer. + explode: true + in: query + name: customer_details + required: false + schema: + properties: + address: + anyOf: + - $ref: "#/components/schemas/customer_adresss" + - enum: + - '' + type: string + shipping: + anyOf: + - $ref: "#/components/schemas/customer_address_with_name" + - enum: + - '' + type: string + tax: + properties: + ip_address: + anyOf: + - type: string + - enum: + - '' + type: string + title: tax_param + type: object + tax_exempt: + enum: + - '' + - exempt + - none + - reverse + type: string + tax_ids: + items: + properties: + type: + enum: + - ae_trn + - au_abn + - au_arn + - br_cnpj + - br_cpf + - ca_bn + - ca_gst_hst + - ca_pst_bc + - ca_pst_mb + - ca_pst_sk + - ca_qst + - ch_vat + - cl_tin + - es_cif + - eu_vat + - gb_vat + - hk_br + - id_npwp + - il_vat + - in_gst + - jp_cn + - jp_rn + - kr_brn + - li_uid + - mx_rfc + - my_frp + - my_itn + - my_sst + - no_vat + - nz_gst + - ru_inn + - ru_kpp + - sa_vat + - sg_gst + - sg_uen + - th_vat + - tw_vat + - us_ein + - za_vat + maxLength: 5000 + type: string + x-stripeBypassValidation: true + value: + type: string + required: + - type + - value + title: data_params + type: object + type: array + title: customer_details_param + type: object + style: deepObject + - description: The coupons to redeem into discounts for the invoice preview. + If not specified, inherits the discount from the customer or subscription. + Pass an empty string to avoid inheriting any discounts. To preview the upcoming + invoice for a subscription that hasn't been created, use `coupon` instead. + explode: true + in: query + name: discounts + required: false + schema: + anyOf: + - $ref: "#/components/schemas/discounts_data_param" + - enum: + - '' + type: string + style: deepObject + - description: List of invoice items to add or update in the upcoming invoice + preview. + explode: true + in: query + name: invoice_items + required: false + schema: + items: + $ref: '#/components/schemas/invoice_item_preview_params' + type: array + style: deepObject + - description: The identifier of the unstarted schedule whose upcoming invoice + you'd like to retrieve. Cannot be used with subscription or subscription + fields. + in: query + name: schedule + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: The identifier of the subscription for which you'd like to retrieve + the upcoming invoice. If not provided, but a `subscription_items` is provided, + you will preview creating a subscription with those items. If neither `subscription` + nor `subscription_items` is provided, you will retrieve the next upcoming + invoice from among the customer's subscriptions. + in: query + name: subscription + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: For new subscriptions, a future timestamp to anchor the subscription's + [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). This + is used to determine the date of the first full invoice, and, for plans + with `month` or `year` intervals, the day of the month for subsequent invoices. + For existing subscriptions, the value can only be set to `now` or `unchanged`. + explode: true + in: query + name: subscription_billing_cycle_anchor + required: false + schema: + anyOf: + - enum: + - now + - unchanged + maxLength: 5000 + type: string + - format: unix-time + type: integer + style: deepObject + - description: Timestamp indicating when the subscription should be scheduled + to cancel. Will prorate if within the current period and prorations have + been enabled using `proration_behavior`. + explode: true + in: query + name: subscription_cancel_at + required: false + schema: + anyOf: + - format: unix-time + type: integer + - enum: + - '' + type: string + style: deepObject + - description: Boolean indicating whether this subscription should cancel at + the end of the current period. + in: query + name: subscription_cancel_at_period_end + required: false + schema: + type: boolean + style: form + - description: This simulates the subscription being canceled or expired immediately. + in: query + name: subscription_cancel_now + required: false + schema: + type: boolean + style: form + - description: If provided, the invoice returned will preview updating or creating + a subscription with these default tax rates. The default tax rates will + apply to any line item that does not have `tax_rates` set. + explode: true + in: query + name: subscription_default_tax_rates + required: false + schema: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + style: deepObject + - description: A list of up to 20 subscription items, each with an attached + price. + explode: true + in: query + name: subscription_items + required: false + schema: + items: + $ref: "#/components/schemas/getInvoicesUpcomingRequestBody" + type: array + style: deepObject + - description: |- + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. Valid values are `create_prorations`, `none`, or `always_invoice`. + + Passing `create_prorations` will cause proration invoice items to be created when applicable. These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). In order to always invoice immediately for prorations, pass `always_invoice`. + + Prorations can be disabled by passing `none`. + in: query + name: subscription_proration_behavior + required: false + schema: + enum: + - always_invoice + - create_prorations + - none + type: string + style: form + - description: If previewing an update to a subscription, and doing proration, + `subscription_proration_date` forces the proration to be calculated as though + the update was done at the specified time. The time given must be within + the current subscription period, and cannot be before the subscription was + on its current plan. If set, `subscription`, and one of `subscription_items`, + or `subscription_trial_end` are required. Also, `subscription_proration_behavior` + cannot be set to 'none'. + in: query + name: subscription_proration_date + required: false + schema: + format: unix-time + type: integer + style: form + - description: Date a subscription is intended to start (can be future or past) + in: query + name: subscription_start_date + required: false + schema: + format: unix-time + type: integer + style: form + - description: If provided, the invoice returned will preview updating or creating + a subscription with that trial end. If set, one of `subscription_items` + or `subscription` is required. + explode: true + in: query + name: subscription_trial_end + required: false + schema: + anyOf: + - enum: + - now + maxLength: 5000 + type: string + - format: unix-time + type: integer + style: deepObject + - description: Indicates if a plan's `trial_period_days` should be applied to + the subscription. Setting `subscription_trial_end` per subscription is preferred, + and this defaults to `false`. Setting this flag to `true` together with + `subscription_trial_end` is not allowed. + in: query + name: subscription_trial_from_plan + required: false + schema: + type: boolean + style: form + + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/invoice" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/invoices/upcoming/lines": + get: + description: "

When retrieving an upcoming invoice, you’ll get a lines + property containing the total count of line items and the first handful of + those items. There is also a URL where you can retrieve the full (paginated) + list of line items.

" + operationId: GetInvoicesUpcomingLines + tags: + - "Invoices" + parameters: + - description: Settings for automatic tax lookup for this invoice preview. + explode: true + in: query + name: automatic_tax + required: false + schema: + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_param + type: object + style: deepObject + - description: The code of the coupon to apply. If `subscription` or `subscription_items` + is provided, the invoice returned will preview updating or creating a subscription + with that coupon. Otherwise, it will preview applying that coupon to the + customer for the next upcoming invoice from among the customer's subscriptions. + The invoice can be previewed without a coupon by passing this value as an + empty string. + in: query + name: coupon + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: The identifier of the customer whose upcoming invoice you'd like + to retrieve. + in: query + name: customer + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: Details about the customer you want to invoice or overrides for + an existing customer. + explode: true + in: query + name: customer_details + required: false + schema: + properties: + address: + anyOf: + - $ref : "#/components/schemas/customer_adresss" + type: object + - enum: + - '' + type: string + shipping: + anyOf: + - $ref : "#/components/schemas/customer_address_with_name" + - enum: + - '' + type: string + tax: + properties: + ip_address: + anyOf: + - type: string + - enum: + - '' + type: string + title: tax_param + type: object + tax_exempt: + enum: + - '' + - exempt + - none + - reverse + type: string + tax_ids: + items: + properties: + type: + enum: + - ae_trn + - au_abn + - au_arn + - br_cnpj + - br_cpf + - ca_bn + - ca_gst_hst + - ca_pst_bc + - ca_pst_mb + - ca_pst_sk + - ca_qst + - ch_vat + - cl_tin + - es_cif + - eu_vat + - gb_vat + - hk_br + - id_npwp + - il_vat + - in_gst + - jp_cn + - jp_rn + - kr_brn + - li_uid + - mx_rfc + - my_frp + - my_itn + - my_sst + - no_vat + - nz_gst + - ru_inn + - ru_kpp + - sa_vat + - sg_gst + - sg_uen + - th_vat + - tw_vat + - us_ein + - za_vat + maxLength: 5000 + type: string + x-stripeBypassValidation: true + value: + type: string + required: + - type + - value + title: data_params + type: object + type: array + title: customer_details_param + type: object + style: deepObject + - description: The coupons to redeem into discounts for the invoice preview. + If not specified, inherits the discount from the customer or subscription. + Pass an empty string to avoid inheriting any discounts. To preview the upcoming + invoice for a subscription that hasn't been created, use `coupon` instead. + explode: true + in: query + name: discounts + required: false + schema: + anyOf: + - $ref: "#/components/schemas/discounts_data_param" + - enum: + - '' + type: string + style: deepObject + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: List of invoice items to add or update in the upcoming invoice + preview. + explode: true + in: query + name: invoice_items + required: false + schema: + items: + $ref: '#/components/schemas/invoice_item_preview_params' + type: array + style: deepObject + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: The identifier of the unstarted schedule whose upcoming invoice + you'd like to retrieve. Cannot be used with subscription or subscription + fields. + in: query + name: schedule + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: The identifier of the subscription for which you'd like to retrieve + the upcoming invoice. If not provided, but a `subscription_items` is provided, + you will preview creating a subscription with those items. If neither `subscription` + nor `subscription_items` is provided, you will retrieve the next upcoming + invoice from among the customer's subscriptions. + in: query + name: subscription + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: For new subscriptions, a future timestamp to anchor the subscription's + [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). This + is used to determine the date of the first full invoice, and, for plans + with `month` or `year` intervals, the day of the month for subsequent invoices. + For existing subscriptions, the value can only be set to `now` or `unchanged`. + explode: true + in: query + name: subscription_billing_cycle_anchor + required: false + schema: + anyOf: + - enum: + - now + - unchanged + maxLength: 5000 + type: string + - format: unix-time + type: integer + style: deepObject + - description: Timestamp indicating when the subscription should be scheduled + to cancel. Will prorate if within the current period and prorations have + been enabled using `proration_behavior`. + explode: true + in: query + name: subscription_cancel_at + required: false + schema: + anyOf: + - format: unix-time + type: integer + - enum: + - '' + type: string + style: deepObject + - description: Boolean indicating whether this subscription should cancel at + the end of the current period. + in: query + name: subscription_cancel_at_period_end + required: false + schema: + type: boolean + style: form + - description: This simulates the subscription being canceled or expired immediately. + in: query + name: subscription_cancel_now + required: false + schema: + type: boolean + style: form + - description: If provided, the invoice returned will preview updating or creating + a subscription with these default tax rates. The default tax rates will + apply to any line item that does not have `tax_rates` set. + explode: true + in: query + name: subscription_default_tax_rates + required: false + schema: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + style: deepObject + - description: A list of up to 20 subscription items, each with an attached + price. + explode: true + in: query + name: subscription_items + schema: + items: + $ref: "#/components/schemas/getInvoicesUpcomingRequestBody" + type: array + style: deepObject + - description: |- + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. Valid values are `create_prorations`, `none`, or `always_invoice`. + + Passing `create_prorations` will cause proration invoice items to be created when applicable. These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). In order to always invoice immediately for prorations, pass `always_invoice`. + + Prorations can be disabled by passing `none`. + in: query + name: subscription_proration_behavior + required: false + schema: + enum: + - always_invoice + - create_prorations + - none + type: string + style: form + - description: If previewing an update to a subscription, and doing proration, + `subscription_proration_date` forces the proration to be calculated as though + the update was done at the specified time. The time given must be within + the current subscription period, and cannot be before the subscription was + on its current plan. If set, `subscription`, and one of `subscription_items`, + or `subscription_trial_end` are required. Also, `subscription_proration_behavior` + cannot be set to 'none'. + in: query + name: subscription_proration_date + required: false + schema: + format: unix-time + type: integer + style: form + - description: Date a subscription is intended to start (can be future or past) + in: query + name: subscription_start_date + required: false + schema: + format: unix-time + type: integer + style: form + - description: If provided, the invoice returned will preview updating or creating + a subscription with that trial end. If set, one of `subscription_items` + or `subscription` is required. + explode: true + in: query + name: subscription_trial_end + required: false + schema: + anyOf: + - enum: + - now + maxLength: 5000 + type: string + - format: unix-time + type: integer + style: deepObject + - description: Indicates if a plan's `trial_period_days` should be applied to + the subscription. Setting `subscription_trial_end` per subscription is preferred, + and this defaults to `false`. Setting this flag to `true` together with + `subscription_trial_end` is not allowed. + in: query + name: subscription_trial_from_plan + required: false + schema: + type: boolean + style: form + + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + description: Details about each object. + items: + "$ref": "#/components/schemas/line_item" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: InvoiceLinesList + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/payment_methods": + get: + description: "

Returns a list of PaymentMethods for a given Customer

" + operationId: ListPaymentMethods + tags: + - "Payment_Methods" + parameters: + - description: The ID of the customer whose PaymentMethods will be retrieved. + in: query + name: customer + required: true + schema: + maxLength: 5000 + type: string + style: form + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + type: string + style: form + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + type: string + style: form + - description: A required filter on the list, based on the object `type` field. + in: query + name: type + required: true + schema: + enum: + - acss_debit + - afterpay_clearpay + - alipay + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - eps + - fpx + - giropay + - grabpay + - ideal + - oxxo + - p24 + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + style: form + + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + items: + "$ref": "#/components/schemas/payment_method" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + pattern: "^/v1/payment_methods" + type: string + required: + - data + - has_more + - object + - url + title: PaymentFlowsPaymentMethodList + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: |- +

Creates a PaymentMethod object. Read the Stripe.js reference to learn how to create PaymentMethods via Stripe.js.

+ +

Instead of creating a PaymentMethod directly, we recommend using the PaymentIntents API to accept a payment immediately or the SetupIntent API to collect payment method details ahead of a future payment.

+ operationId: CreatePaymentMethod + tags: + - "Payment_Methods" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + acss_debit: + explode: true + style: deepObject + afterpay_clearpay: + explode: true + style: deepObject + alipay: + explode: true + style: deepObject + au_becs_debit: + explode: true + style: deepObject + bacs_debit: + explode: true + style: deepObject + bancontact: + explode: true + style: deepObject + billing_details: + explode: true + style: deepObject + boleto: + explode: true + style: deepObject + card: + explode: true + style: deepObject + eps: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + fpx: + explode: true + style: deepObject + giropay: + explode: true + style: deepObject + grabpay: + explode: true + style: deepObject + ideal: + explode: true + style: deepObject + interac_present: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + oxxo: + explode: true + style: deepObject + p24: + explode: true + style: deepObject + sepa_debit: + explode: true + style: deepObject + sofort: + explode: true + style: deepObject + wechat_pay: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + acss_debit: + description: If this is an `acss_debit` PaymentMethod, this hash + contains details about the ACSS Debit payment method. + properties: + account_number: + maxLength: 5000 + type: string + description: Customer’s bank account number + institution_number: + maxLength: 5000 + type: string + description: Institution number of the customer’s bank + transit_number: + maxLength: 5000 + type: string + description: Transit number of the customer’s bank + required: + - account_number + - institution_number + - transit_number + title: payment_method_param + type: object + afterpay_clearpay: + description: If this is an `AfterpayClearpay` PaymentMethod, this + hash contains details about the AfterpayClearpay payment method. + properties: {} + title: param + type: object + alipay: + description: If this is an `Alipay` PaymentMethod, this hash contains + details about the Alipay payment method. + properties: {} + title: param + type: object + au_becs_debit: + description: If this is an `au_becs_debit` PaymentMethod, this hash + contains details about the bank account. + properties: + account_number: + maxLength: 5000 + type: string + description: The account number for the bank account + bsb_number: + maxLength: 5000 + type: string + description: Bank-State-Branch number of the bank account + required: + - account_number + - bsb_number + title: param + type: object + bacs_debit: + description: If this is a `bacs_debit` PaymentMethod, this hash + contains details about the Bacs Direct Debit bank account. + properties: + account_number: + maxLength: 5000 + type: string + sort_code: + maxLength: 5000 + type: string + title: param + type: object + bancontact: + description: If this is a `bancontact` PaymentMethod, this hash + contains details about the Bancontact payment method. + properties: {} + title: param + type: object + billing_details: + description: Billing information associated with the PaymentMethod + that may be used or required by particular types of payment methods. + properties: + address: + anyOf: + - $ref: "#/components/schemas/billing_details_address" + - enum: + - '' + type: string + email: + type: string + name: + maxLength: 5000 + type: string + phone: + maxLength: 5000 + type: string + title: billing_details_inner_params + type: object + boleto: + description: If this is a `boleto` PaymentMethod, this hash contains + details about the Boleto payment method. + properties: + tax_id: + maxLength: 5000 + type: string + required: + - tax_id + title: param + type: object + card: + anyOf: + - $ref: "#/components/schemas/card_details_params" + - $ref: "#/components/schemas/token_paramas" + description: 'If this is a `card` PaymentMethod, this hash contains + the user''s card details. For backwards compatibility, you can + alternatively provide a Stripe token (e.g., for Apple Pay, Amex + Express Checkout, or legacy Checkout) into the card hash with + format `card: {token: "tok_visa"}`. When providing a card number, + you must meet the requirements for [PCI compliance](https://stripe.com/docs/security#validating-pci-compliance). + We strongly recommend using Stripe.js instead of interacting with + this API directly.' + x-stripeBypassValidation: true + customer: + description: The `Customer` to whom the original PaymentMethod is + attached. + maxLength: 5000 + type: string + eps: + description: If this is an `eps` PaymentMethod, this hash contains + details about the EPS payment method. + properties: + bank: + enum: + - arzte_und_apotheker_bank + - austrian_anadi_bank_ag + - bank_austria + - bankhaus_carl_spangler + - bankhaus_schelhammer_und_schattera_ag + - bawag_psk_ag + - bks_bank_ag + - brull_kallmus_bank_ag + - btv_vier_lander_bank + - capital_bank_grawe_gruppe_ag + - dolomitenbank + - easybank_ag + - erste_bank_und_sparkassen + - hypo_alpeadriabank_international_ag + - hypo_bank_burgenland_aktiengesellschaft + - hypo_noe_lb_fur_niederosterreich_u_wien + - hypo_oberosterreich_salzburg_steiermark + - hypo_tirol_bank_ag + - hypo_vorarlberg_bank_ag + - marchfelder_bank + - oberbank_ag + - raiffeisen_bankengruppe_osterreich + - schoellerbank_ag + - sparda_bank_wien + - volksbank_gruppe + - volkskreditbank_ag + - vr_bank_braunau + maxLength: 5000 + type: string + title: param + type: object + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + fpx: + description: If this is an `fpx` PaymentMethod, this hash contains + details about the FPX payment method. + properties: + bank: + enum: + - affin_bank + - alliance_bank + - ambank + - bank_islam + - bank_muamalat + - bank_rakyat + - bsn + - cimb + - deutsche_bank + - hong_leong_bank + - hsbc + - kfh + - maybank2e + - maybank2u + - ocbc + - pb_enterprise + - public_bank + - rhb + - standard_chartered + - uob + maxLength: 5000 + type: string + x-stripeBypassValidation: true + required: + - bank + title: param + type: object + giropay: + description: If this is a `giropay` PaymentMethod, this hash contains + details about the Giropay payment method. + properties: {} + title: param + type: object + grabpay: + description: If this is a `grabpay` PaymentMethod, this hash contains + details about the GrabPay payment method. + properties: {} + title: param + type: object + ideal: + description: If this is an `ideal` PaymentMethod, this hash contains + details about the iDEAL payment method. + properties: + bank: + enum: + - abn_amro + - asn_bank + - bunq + - handelsbanken + - ing + - knab + - moneyou + - rabobank + - regiobank + - revolut + - sns_bank + - triodos_bank + - van_lanschot + maxLength: 5000 + type: string + title: param + type: object + interac_present: + description: If this is an `interac_present` PaymentMethod, this + hash contains details about the Interac Present payment method. + properties: {} + title: param + type: object + metadata: + additionalProperties: + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + type: object + oxxo: + description: If this is an `oxxo` PaymentMethod, this hash contains + details about the OXXO payment method. + properties: {} + title: param + type: object + p24: + description: If this is a `p24` PaymentMethod, this hash contains + details about the P24 payment method. + properties: + bank: + enum: + - alior_bank + - bank_millennium + - bank_nowy_bfg_sa + - bank_pekao_sa + - banki_spbdzielcze + - blik + - bnp_paribas + - boz + - citi_handlowy + - credit_agricole + - envelobank + - etransfer_pocztowy24 + - getin_bank + - ideabank + - ing + - inteligo + - mbank_mtransfer + - nest_przelew + - noble_pay + - pbac_z_ipko + - plus_bank + - santander_przelew24 + - tmobile_usbugi_bankowe + - toyota_bank + - volkswagen_bank + maxLength: 5000 + type: string + title: param + type: object + payment_method: + description: The PaymentMethod to share. + maxLength: 5000 + type: string + sepa_debit: + description: If this is a `sepa_debit` PaymentMethod, this hash + contains details about the SEPA debit bank account. + properties: + iban: + maxLength: 5000 + type: string + required: + - iban + title: param + type: object + sofort: + description: If this is a `sofort` PaymentMethod, this hash contains + details about the SOFORT payment method. + properties: + country: + enum: + - AT + - BE + - DE + - ES + - IT + - NL + type: string + required: + - country + title: param + type: object + type: + description: The type of the PaymentMethod. An additional hash is + included on the PaymentMethod with a name matching this value. + It contains additional information specific to the PaymentMethod + type. + enum: + - acss_debit + - afterpay_clearpay + - alipay + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - eps + - fpx + - giropay + - grabpay + - ideal + - oxxo + - p24 + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + wechat_pay: + description: If this is an `wechat_pay` PaymentMethod, this hash + contains details about the wechat_pay payment method. + properties: {} + title: param + type: object + type: object + description: Payment method details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/payment_method" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/payment_methods/{payment_method}": + get: + description: "

Retrieves a PaymentMethod object.

" + operationId: GetPaymentMethod + tags: + - "Payment_Methods" + parameters: + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - in: path + name: payment_method + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Payment method Id + + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/payment_method" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: "

Updates a PaymentMethod object. A PaymentMethod must be attached + a customer to be updated.

" + operationId: updatePaymentMethod + tags: + - "Payment_Methods" + parameters: + - in: path + name: payment_method + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Payment method Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + billing_details: + explode: true + style: deepObject + card: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + billing_details: + description: Billing information associated with the PaymentMethod + that may be used or required by particular types of payment methods. + properties: + address: + anyOf: + - $ref: "#/components/schemas/billing_details_address" + - enum: + - '' + type: string + email: + type: string + name: + maxLength: 5000 + type: string + phone: + maxLength: 5000 + type: string + title: billing_details_inner_params + type: object + card: + description: If this is a `card` PaymentMethod, this hash contains + the user's card details. + properties: + exp_month: + type: integer + exp_year: + type: integer + title: update_api_param + type: object + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + type: object + description: Payment method details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/payment_method" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/payment_methods/{payment_method}/attach": + post: + description: |- +

Attaches a PaymentMethod object to a Customer.

+ +

To attach a new PaymentMethod to a customer for future payments, we recommend you use a SetupIntent + or a PaymentIntent with setup_future_usage. + These approaches will perform any necessary steps to ensure that the PaymentMethod can be used in a future payment. Using the + /v1/payment_methods/:id/attach endpoint does not ensure that future payments can be made with the attached PaymentMethod. + See Optimizing cards for future payments for more information about setting up future payments.

+ +

To use this PaymentMethod as the default for invoice or subscription payments, + set invoice_settings.default_payment_method, + on the Customer to the PaymentMethod’s ID.

+ operationId: attachPaymentMethodtoCustomer + tags: + - "Payment_Methods" + parameters: + - in: path + name: payment_method + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Payment method Id + requestBody: + content: + application/x-www-form-urlencoded: + schema: + additionalProperties: false + properties: + customer: + description: The ID of the customer to which to attach the PaymentMethod. + maxLength: 5000 + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + required: + - customer + type: object + description: The ID of the customer to which to attach the PaymentMethod + required: true + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/payment_method" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/payment_methods/{payment_method}/detach": + post: + description: "

Detaches a PaymentMethod object from a Customer.

" + operationId: detachPaymentMethodfromCustomer + tags: + - "Payment_Methods" + parameters: + - in: path + name: payment_method + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Payment method Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + type: object + description: Additional details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/payment_method" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/prices": + post: + description: "

Creates a new price for an existing product. The price can + be recurring or one-time.

" + operationId: CreatePrice + tags: + - "Price" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + product_data: + explode: true + style: deepObject + recurring: + explode: true + style: deepObject + tiers: + explode: true + style: deepObject + transform_quantity: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + active: + description: Whether the price can be used for new purchases. Defaults + to `true`. + type: boolean + billing_scheme: + description: Describes how to compute the price per period. Either + `per_unit` or `tiered`. `per_unit` indicates that the fixed amount + (specified in `unit_amount` or `unit_amount_decimal`) will be + charged per unit in `quantity` (for prices with `usage_type=licensed`), + or per unit of total usage (for prices with `usage_type=metered`). + `tiered` indicates that the unit pricing will be computed using + a tiering strategy as defined using the `tiers` and `tiers_mode` + attributes. + enum: + - per_unit + - tiered + type: string + currency: + description: Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), + in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies). + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + lookup_key: + description: A lookup key used to retrieve prices dynamically from + a static string. + maxLength: 5000 + type: string + metadata: + additionalProperties: + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + type: object + nickname: + description: A brief description of the price, hidden from customers. + maxLength: 5000 + type: string + product: + description: The ID of the product that this price will belong to. + maxLength: 5000 + type: string + product_data: + description: These fields can be used to create a new product that + this price will belong to. + properties: + active: + type: boolean + description: Whether the product is currently available for purchase. Defaults to true. + id: + maxLength: 5000 + type: string + description: The ID of the product that this price will belong to. + metadata: + additionalProperties: + type: string + type: object + description: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to metadata + name: + maxLength: 5000 + type: string + description: The product’s name, meant to be displayable to the customer. Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions + statement_descriptor: + maxLength: 22 + type: string + description: An arbitrary string to be displayed on your customer’s credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all + tax_code: + maxLength: 5000 + type: string + description: A tax code ID + unit_label: + maxLength: 12 + type: string + description: A label that represents units of this product in Stripe and on customers’ receipts and invoices. When set, this will be included in associated invoice line item descriptions + required: + - name + title: inline_product_params + type: object + recurring: + description: The recurring components of a price such as `interval` + and `usage_type`. + properties: + aggregate_usage: + enum: + - last_during_period + - last_ever + - max + - sum + type: string + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + usage_type: + enum: + - licensed + - metered + type: string + required: + - interval + title: recurring + type: object + tax_behavior: + description: Specifies whether the price is considered inclusive + of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, + or `unspecified`. Once specified as either `inclusive` or `exclusive`, + it cannot be changed. + enum: + - exclusive + - inclusive + - unspecified + type: string + tiers: + description: Each element represents a pricing tier. This parameter + requires `billing_scheme` to be set to `tiered`. See also the + documentation for `billing_scheme`. + items: + properties: + flat_amount: + type: integer + flat_amount_decimal: + format: decimal + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + up_to: + anyOf: + - enum: + - inf + maxLength: 5000 + type: string + - type: integer + required: + - up_to + title: tier + type: object + type: array + tiers_mode: + description: Defines if the tiering price should be `graduated` + or `volume` based. In `volume`-based tiering, the maximum quantity + within a period determines the per unit price, in `graduated` + tiering pricing can successively change as the quantity grows. + enum: + - graduated + - volume + type: string + transfer_lookup_key: + description: If set to true, will atomically remove the lookup key + from the existing price, and assign it to this price. + type: boolean + transform_quantity: + description: Apply a transformation to the reported usage or set + quantity before computing the billed price. Cannot be combined + with `tiers`. + properties: + divide_by: + type: integer + round: + enum: + - down + - up + type: string + required: + - divide_by + - round + title: transform_usage_param + type: object + unit_amount: + description: A positive integer in %s (or 0 for a free price) representing + how much to charge. + type: integer + unit_amount_decimal: + description: Same as `unit_amount`, but accepts a decimal value + in %s with at most 12 decimal places. Only one of `unit_amount` + and `unit_amount_decimal` can be set. + format: decimal + type: string + required: + - currency + type: object + description: Price details + required: true + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/price" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/prices/{price}": + post: + description: "

Updates the specified price by setting the values of the parameters + passed. Any parameters not provided are left unchanged.

" + operationId: updatePrice + tags: + - "Price" + parameters: + - in: path + name: price + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Price Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + active: + description: Whether the price can be used for new purchases. Defaults + to `true`. + type: boolean + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + lookup_key: + description: A lookup key used to retrieve prices dynamically from + a static string. + maxLength: 5000 + type: string + metadata: + anyOf: + - $ref: "#/components/schemas/additional_properties" + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + nickname: + description: A brief description of the price, hidden from customers. + maxLength: 5000 + type: string + tax_behavior: + description: Specifies whether the price is considered inclusive + of taxes or exclusive of taxes. One of `inclusive`, `exclusive`, + or `unspecified`. Once specified as either `inclusive` or `exclusive`, + it cannot be changed. + enum: + - exclusive + - inclusive + - unspecified + type: string + transfer_lookup_key: + description: If set to true, will atomically remove the lookup key + from the existing price, and assign it to this price. + type: boolean + type: object + description: Price details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/price" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/products": + post: + description: "

Creates a new product object.

" + operationId: createProduct + tags: + - "Products" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + images: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + package_dimensions: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + active: + description: Whether the product is currently available for purchase. + Defaults to `true`. + type: boolean + description: + description: The product's description, meant to be displayable + to the customer. Use this field to optionally store a long form + explanation of the product being sold for your own rendering purposes. + maxLength: 40000 + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + id: + description: An identifier will be randomly generated by Stripe. + You can optionally override this ID, but the ID must be unique + across all products in your Stripe account. + maxLength: 5000 + type: string + images: + description: A list of up to 8 URLs of images for this product, + meant to be displayable to the customer. + items: + type: string + type: array + metadata: + additionalProperties: + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + type: object + name: + description: The product's name, meant to be displayable to the + customer. Whenever this product is sold via a subscription, name + will show up on associated invoice line item descriptions. + maxLength: 5000 + type: string + package_dimensions: + description: The dimensions of this product for shipping purposes. + properties: + height: + type: number + length: + type: number + weight: + type: number + width: + type: number + required: + - height + - length + - weight + - width + title: package_dimensions_specs + type: object + shippable: + description: Whether this product is shipped (i.e., physical goods). + type: boolean + statement_descriptor: + description: |- + An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + + This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + It must contain at least one letter. + maxLength: 22 + type: string + tax_code: + description: A [tax code](https://stripe.com/docs/tax/tax-codes) + ID. + type: string + unit_label: + description: A label that represents units of this product in Stripe + and on customers’ receipts and invoices. When set, this will be + included in associated invoice line item descriptions. + maxLength: 12 + type: string + url: + description: A URL of a publicly-accessible webpage for this product. + maxLength: 5000 + type: string + required: + - name + type: object + description: Product details + required: true + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/product" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/products/{id}": + post: + description: "

Updates the specific product by setting the values of the parameters + passed. Any parameters not provided will be left unchanged.

" + operationId: updateProduct + tags: + - "Products" + parameters: + - in: path + name: id + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Product Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + images: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + package_dimensions: + explode: true + style: deepObject + tax_code: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + active: + description: Whether the product is available for purchase. + type: boolean + description: + description: The product's description, meant to be displayable + to the customer. Use this field to optionally store a long form + explanation of the product being sold for your own rendering purposes. + maxLength: 40000 + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + images: + anyOf: + - items: + type: string + type: array + - enum: + - '' + type: string + description: A list of up to 8 URLs of images for this product, + meant to be displayable to the customer. + metadata: + anyOf: + - $ref: "#/components/schemas/additional_properties" + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + name: + description: The product's name, meant to be displayable to the + customer. Whenever this product is sold via a subscription, name + will show up on associated invoice line item descriptions. + maxLength: 5000 + type: string + package_dimensions: + anyOf: + - $ref: "#/components/schemas/package_dimentions_specs" + - enum: + - '' + type: string + description: The dimensions of this product for shipping purposes. + shippable: + description: Whether this product is shipped (i.e., physical goods). + type: boolean + statement_descriptor: + description: |- + An arbitrary string to be displayed on your customer's credit card or bank statement. While most banks display this information consistently, some may display it incorrectly or not at all. + + This may be up to 22 characters. The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. Non-ASCII characters are automatically stripped. + It must contain at least one letter. May only be set if `type=service`. + maxLength: 22 + type: string + tax_code: + anyOf: + - type: string + - enum: + - '' + type: string + description: A [tax code](https://stripe.com/docs/tax/tax-codes) + ID. + unit_label: + description: A label that represents units of this product in Stripe + and on customers’ receipts and invoices. When set, this will be + included in associated invoice line item descriptions. May only + be set if `type=service`. + maxLength: 12 + type: string + url: + description: A URL of a publicly-accessible webpage for this product. + type: string + type: object + description: Product details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/product" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_items/{item}": + post: + description: "

Updates the plan or quantity of an item on a current subscription.

" + operationId: updateSubscriptionItem + tags: + - "Subscription_Items" + parameters: + - in: path + name: item + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription item Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + billing_thresholds: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + price_data: + explode: true + style: deepObject + tax_rates: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/billing_thresholds" + - enum: + - '' + type: string + description: Define thresholds at which an invoice will be sent, + and the subscription advanced to a new billing period. When updating, + pass an empty string to remove previously-defined thresholds. + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + metadata: + anyOf: + - $ref: "#/components/schemas/additional_properties" + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + off_session: + description: Indicates if a customer is on or off-session while + an invoice payment is attempted. + type: boolean + payment_behavior: + description: |- + Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription’s invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + + Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + enum: + - allow_incomplete + - default_incomplete + - error_if_incomplete + - pending_if_incomplete + type: string + price: + description: The ID of the price object. When changing a subscription + item's price, `quantity` is set to 1 unless a `quantity` parameter + is provided. + maxLength: 5000 + type: string + price_data: + description: Data used to generate a new [Price](https://stripe.com/docs/api/prices) + object inline. + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + recurring: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: recurring_adhoc + type: object + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + - recurring + title: recurring_price_data + type: object + proration_behavior: + description: |- + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. Valid values are `create_prorations`, `none`, or `always_invoice`. + + Passing `create_prorations` will cause proration invoice items to be created when applicable. These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). In order to always invoice immediately for prorations, pass `always_invoice`. + + Prorations can be disabled by passing `none`. + enum: + - always_invoice + - create_prorations + - none + type: string + proration_date: + description: If set, the proration will be calculated as though + the subscription was updated at the given time. This can be used + to apply the same proration that was previewed with the [upcoming + invoice](https://stripe.com/docs/api#retrieve_customer_invoice) + endpoint. + format: unix-time + type: integer + quantity: + description: The quantity you'd like to apply to the subscription + item you're creating. + type: integer + tax_rates: + anyOf: + - $ref: "#/components/schemas/tax_rate_array" + - enum: + - '' + type: string + description: A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) + ids. These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) + on the Subscription. When updating, pass an empty string to remove + previously-defined tax rates. + type: object + description: Subscription item details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription_item" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_items/{subscription_item}/usage_records": + post: + description: |- +

Creates a usage record for a specified subscription item and date, and fills it with a quantity.

+ +

Usage records provide quantity information that Stripe uses to track how much a customer is using your service. With usage information and the pricing model set up by the metered billing plan, Stripe helps you send accurate invoices to your customers.

+ +

The default calculation for usage is to add up all the quantity values of the usage records within a billing period. You can change this default behavior with the billing plan’s aggregate_usage parameter. When there is more than one usage record with the same timestamp, Stripe adds the quantity values together. In most cases, this is the desired resolution, however, you can change this behavior with the action parameter.

+ +

The default pricing model for metered billing is per-unit pricing. For finer granularity, you can configure metered billing to have a tiered pricing model.

+ operationId: createSubscriptionItemUsageRecord + tags: + - "Usage_Records" + parameters: + - in: path + name: subscription_item + required: true + schema: + type: string + style: simple + description: Subscription item Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + action: + description: Valid values are `increment` (default) or `set`. When + using `increment` the specified `quantity` will be added to the + usage at the specified timestamp. The `set` action will overwrite + the usage quantity at that timestamp. If the subscription has + [billing thresholds](https://stripe.com/docs/api/subscriptions/object#subscription_object-billing_thresholds), + `increment` is the only allowed value. + enum: + - increment + - set + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + quantity: + description: The usage quantity for the specified timestamp. + type: integer + timestamp: + description: The timestamp for the usage event. This timestamp must + be within the current billing period of the subscription of the + provided `subscription_item`. + type: integer + required: + - quantity + - timestamp + type: object + description: Usage record details + required: true + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/usage_record" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_items/{subscription_item}/usage_record_summaries": + get: + description: >- +

For the specified subscription item, returns a list of summary + objects. Each object in the list provides usage information that’s been + summarized from multiple usage records and over a subscription billing + period (e.g., 15 usage records in the month of September).

+ + +

The list is sorted in reverse-chronological order (newest first). The + first list item represents the most current usage period that hasn’t + ended yet. Since new usage records can still be added, the returned + summary information for the subscription item’s ID should be seen as + unstable until the subscription billing period ends.

+ operationId: GetSubscriptionItemsSubscriptionItemUsageRecordSummaries + parameters: + - description: >- + A cursor for use in pagination. `ending_before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your + subsequent call can include `ending_before=obj_bar` in order to + fetch the previous page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - description: >- + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: >- + A cursor for use in pagination. `starting_after` is an object ID + that defines your place in the list. For instance, if you make a + list request and receive 100 objects, ending with `obj_foo`, your + subsequent call can include `starting_after=obj_foo` in order to + fetch the next page of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + - in: path + name: subscription_item + required: true + schema: + type: string + style: simple + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + items: + $ref: '#/components/schemas/usage_record_summary' + type: array + has_more: + description: >- + True if this list has another page of items after this one + that can be fetched. + type: boolean + object: + description: >- + String representing the object's type. Objects of the same + type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + type: string + required: + - data + - has_more + - object + - url + title: UsageEventsResourceUsageRecordSummaryList + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + $ref: '#/components/schemas/error' + description: Error response. + "/v1/subscriptions": + get: + description: "

By default, returns a list of subscriptions that have not been + canceled. In order to list canceled subscriptions, specify status=canceled.

" + operationId: ListSubscriptions + tags: + - "Subscriptions" + parameters: + - description: The collection method of the subscriptions to retrieve. Either + `charge_automatically` or `send_invoice`. + in: query + name: collection_method + required: false + schema: + enum: + - charge_automatically + - send_invoice + type: string + style: form + - explode: true + in: query + name: created + required: false + schema: + anyOf: + - $ref: "#/components/schemas/range_query_specs" + - type: integer + style: deepObject + description: Time at which the object was created. Measured in seconds since the Unix epoch + - explode: true + in: query + name: current_period_end + required: false + schema: + anyOf: + - $ref: "#/components/schemas/range_query_specs" + - type: integer + style: deepObject + description: A filter on the list based on the object current_period_end field. The value can be a string with an integer Unix timestamp, or it can be a dictionary + - explode: true + in: query + name: current_period_start + required: false + schema: + anyOf: + - $ref: "#/components/schemas/range_query_specs" + - type: integer + style: deepObject + description: A filter on the list based on the object current_period_start field. The value can be a string with an integer Unix timestamp, or it can be a dictionary + - description: The ID of the customer whose subscriptions will be retrieved. + in: query + name: customer + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: Filter for subscriptions that contain this recurring price ID. + in: query + name: price + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: The status of the subscriptions to retrieve. Passing in a value + of `canceled` will return all canceled subscriptions, including those belonging + to deleted customers. Pass `ended` to find subscriptions that are canceled + and subscriptions that are expired due to [incomplete payment](https://stripe.com/docs/billing/subscriptions/overview#subscription-statuses). + Passing in a value of `all` will return subscriptions of all statuses. If + no value is supplied, all subscriptions that have not been canceled are + returned. + in: query + name: status + required: false + schema: + enum: + - active + - all + - canceled + - ended + - incomplete + - incomplete_expired + - past_due + - trialing + - unpaid + type: string + style: form + + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + items: + "$ref": "#/components/schemas/subscription" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + pattern: "^/v1/subscriptions" + type: string + required: + - data + - has_more + - object + - url + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: "

Creates a new subscription on an existing customer. Each customer + can have up to 500 active or scheduled subscriptions.

" + operationId: CreateSubscriptions + tags: + - "Subscriptions" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + add_invoice_items: + explode: true + style: deepObject + automatic_tax: + explode: true + style: deepObject + billing_thresholds: + explode: true + style: deepObject + default_tax_rates: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + items: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + payment_settings: + explode: true + style: deepObject + pending_invoice_item_interval: + explode: true + style: deepObject + transfer_data: + explode: true + style: deepObject + trial_end: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + add_invoice_items: + description: A list of prices and quantities that will generate + invoice items appended to the first invoice for this subscription. + You may pass up to 20 items. + items: + properties: + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + title: one_time_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - $ref: "#/components/schemas/tax_rate_array" + - enum: + - '' + type: string + title: add_invoice_item_entry + type: object + type: array + application_fee_percent: + description: A non-negative decimal between 0 and 100, with at most + two decimal places. This represents the percentage of the subscription + invoice subtotal that will be transferred to the application owner's + Stripe account. The request must be made by a platform account + on a connected account in order to set an application fee percentage. + For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + type: number + automatic_tax: + description: Automatic tax settings for this subscription. + properties: + enabled: + type: boolean + description: Enabled + required: + - enabled + title: automatic_tax_config + type: object + backdate_start_date: + description: For new subscriptions, a past timestamp to backdate + the subscription's start date to. If set, the first invoice will + contain a proration for the timespan between the start date and + the current time. Can be combined with trials and the billing + cycle anchor. + format: unix-time + type: integer + billing_cycle_anchor: + description: A future timestamp to anchor the subscription's [billing + cycle](https://stripe.com/docs/subscriptions/billing-cycle). This + is used to determine the date of the first full invoice, and, + for plans with `month` or `year` intervals, the day of the month + for subsequent invoices. + format: unix-time + type: integer + x-stripeBypassValidation: true + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/billing_threshold_params" + - enum: + - '' + type: string + description: Define thresholds at which an invoice will be sent, + and the subscription advanced to a new billing period. Pass an + empty string to remove previously-defined thresholds. + cancel_at: + description: A timestamp at which the subscription should cancel. + If set to a date before the current period ends, this will cause + a proration if prorations have been enabled using `proration_behavior`. + If set during a future period, this will always cause a proration + for that period. + format: unix-time + type: integer + cancel_at_period_end: + description: Boolean indicating whether this subscription should + cancel at the end of the current period. + type: boolean + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When + charging automatically, Stripe will attempt to pay this subscription + at the end of the cycle using the default source attached to the + customer. When sending an invoice, Stripe will email your customer + an invoice with payment instructions. Defaults to `charge_automatically`. + enum: + - charge_automatically + - send_invoice + type: string + coupon: + description: The ID of the coupon to apply to this subscription. + A coupon applied to a subscription will only affect invoices created + for that particular subscription. + maxLength: 5000 + type: string + customer: + description: The identifier of the customer to subscribe. + maxLength: 5000 + type: string + days_until_due: + description: Number of days a customer has to pay invoices generated + by this subscription. Valid only for subscriptions where `collection_method` + is set to `send_invoice`. + type: integer + default_payment_method: + description: ID of the default payment method for the subscription. + It must belong to the customer associated with the subscription. + This takes precedence over `default_source`. If neither are set, + invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) + or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + maxLength: 5000 + type: string + default_source: + description: ID of the default payment source for the subscription. + It must belong to the customer associated with the subscription + and be in a chargeable state. If `default_payment_method` is also + set, `default_payment_method` will take precedence. If neither + are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) + or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + maxLength: 5000 + type: string + default_tax_rates: + anyOf: + - $ref: "#/components/schemas/tax_rate_array" + type: array + - enum: + - '' + type: string + description: The tax rates that will apply to any subscription item + that does not have `tax_rates` set. Invoices created will have + their `default_tax_rates` populated from the subscription. + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + items: + description: A list of up to 20 subscription items, each with an + attached price. + items: + properties: + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/item_billing_thresholds_param" + - enum: + - '' + type: string + metadata: + additionalProperties: + type: string + type: object + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + recurring: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: recurring_adhoc + type: object + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + - recurring + title: recurring_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - $ref: "#/components/schemas/tax_rate_array" + - enum: + - '' + type: string + title: subscription_item_create_params + type: object + type: array + metadata: + anyOf: + - $ref: "#/components/schemas/additional_properties" + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + off_session: + description: Indicates if a customer is on or off-session while + an invoice payment is attempted. + type: boolean + payment_behavior: + description: |- + Use `allow_incomplete` to create subscriptions with `status=incomplete` if the first invoice cannot be paid. Creating subscriptions with this status allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to create Subscriptions with `status=incomplete` when the first invoice requires payment, otherwise start as active. Subscriptions transition to `status=active` when successfully confirming the payment intent on the first invoice. This allows simpler management of scenarios where additional user actions are needed to pay a subscription’s invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. If the payment intent is not confirmed within 23 hours subscriptions transition to `status=incomplete_expired`, which is a terminal state. + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + + `pending_if_incomplete` is only used with updates and cannot be passed when creating a subscription. + enum: + - allow_incomplete + - default_incomplete + - error_if_incomplete + - pending_if_incomplete + type: string + payment_settings: + description: Payment settings to pass to invoices created by the + subscription. + properties: + payment_method_options: + properties: + bancontact: + anyOf: + - $ref: "#/components/schemas/bancontact_invoice_payment_method_options_param" + - enum: + - '' + type: string + card: + anyOf: + - $ref: "#/components/schemas/card_invoice_payment_method_options_param" + - enum: + - '' + type: string + title: payment_method_options + type: object + payment_method_types: + anyOf: + - $ref: "#/components/schemas/payment_method_types_array" + - enum: + - '' + type: string + title: payment_settings + type: object + pending_invoice_item_interval: + anyOf: + - $ref: "#/components/schemas/pending_invoice_item_interval_params" + - enum: + - '' + type: string + description: Specifies an interval for how often to bill for any + pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) + for the given subscription at the specified interval. + promotion_code: + description: The API ID of a promotion code to apply to this subscription. + A promotion code applied to a subscription will only affect invoices + created for that particular subscription. + maxLength: 5000 + type: string + proration_behavior: + description: |- + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) resulting from the `billing_cycle_anchor`. Valid values are `create_prorations` or `none`. + + Passing `create_prorations` will cause proration invoice items to be created when applicable. Prorations can be disabled by passing `none`. If no value is passed, the default is `create_prorations`. + enum: + - always_invoice + - create_prorations + - none + type: string + transfer_data: + description: If specified, the funds from the subscription's invoices + will be transferred to the destination and the ID of the resulting + transfers will be found on the resulting charges. + properties: + amount_percent: + type: number + destination: + type: string + required: + - destination + title: transfer_data_specs + type: object + trial_end: + anyOf: + - enum: + - now + maxLength: 5000 + type: string + - format: unix-time + type: integer + description: Unix timestamp representing the end of the trial period + the customer will get before being charged for the first time. + This will always overwrite any trials that might apply via a subscribed + plan. If set, trial_end will override the default trial period + of the plan the customer is being subscribed to. The special value + `now` can be provided to end the customer's trial immediately. + Can be at most two years from `billing_cycle_anchor`. + trial_from_plan: + description: Indicates if a plan's `trial_period_days` should be + applied to the subscription. Setting `trial_end` per subscription + is preferred, and this defaults to `false`. Setting this flag + to `true` together with `trial_end` is not allowed. + type: boolean + trial_period_days: + description: Integer representing the number of trial period days + before the customer is charged for the first time. This will always + overwrite any trials that might apply via a subscribed plan. + type: integer + required: + - customer + type: object + description: Subscription details + required: true + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscriptions/{subscription_exposed_id}": + get: + description: "

Retrieves the subscription with the given ID.

" + tags: + - "Subscriptions" + operationId: GetSubscription + parameters: + - description: Specifies which fields in the response should be expanded. + explode: true + in: query + name: expand + required: false + schema: + items: + maxLength: 5000 + type: string + type: array + style: deepObject + - in: path + name: subscription_exposed_id + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription Id + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description:

Updates an existing subscription on a customer to match the + specified parameters. When changing plans or quantities, we will optionally + prorate the price we charge next month to make up for any price changes. To + preview how the proration will be calculated, use the upcoming + invoice endpoint.

+ tags: + - "Subscriptions" + operationId: UpdateSubscription + parameters: + - in: path + name: subscription_exposed_id + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + add_invoice_items: + explode: true + style: deepObject + automatic_tax: + explode: true + style: deepObject + billing_thresholds: + explode: true + style: deepObject + cancel_at: + explode: true + style: deepObject + default_tax_rates: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + items: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + pause_collection: + explode: true + style: deepObject + payment_settings: + explode: true + style: deepObject + pending_invoice_item_interval: + explode: true + style: deepObject + transfer_data: + explode: true + style: deepObject + trial_end: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + add_invoice_items: + description: A list of prices and quantities that will generate + invoice items appended to the first invoice for this subscription. + You may pass up to 20 items. + items: + properties: + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + title: one_time_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: add_invoice_item_entry + type: object + type: array + application_fee_percent: + description: A non-negative decimal between 0 and 100, with at most + two decimal places. This represents the percentage of the subscription + invoice subtotal that will be transferred to the application owner's + Stripe account. The request must be made by a platform account + on a connected account in order to set an application fee percentage. + For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + type: number + automatic_tax: + description: Automatic tax settings for this subscription. + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_config + type: object + billing_cycle_anchor: + description: Either `now` or `unchanged`. Setting the value to `now` + resets the subscription's billing cycle anchor to the current + time. For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + enum: + - now + - unchanged + maxLength: 5000 + type: string + x-stripeBypassValidation: true + billing_thresholds: + anyOf: + - properties: + amount_gte: + type: integer + reset_billing_cycle_anchor: + type: boolean + title: billing_thresholds_param + type: object + - enum: + - '' + type: string + description: Define thresholds at which an invoice will be sent, + and the subscription advanced to a new billing period. Pass an + empty string to remove previously-defined thresholds. + cancel_at: + anyOf: + - format: unix-time + type: integer + - enum: + - '' + type: string + description: A timestamp at which the subscription should cancel. + If set to a date before the current period ends, this will cause + a proration if prorations have been enabled using `proration_behavior`. + If set during a future period, this will always cause a proration + for that period. + cancel_at_period_end: + description: Boolean indicating whether this subscription should + cancel at the end of the current period. + type: boolean + collection_method: + description: Either `charge_automatically`, or `send_invoice`. When + charging automatically, Stripe will attempt to pay this subscription + at the end of the cycle using the default source attached to the + customer. When sending an invoice, Stripe will email your customer + an invoice with payment instructions. Defaults to `charge_automatically`. + enum: + - charge_automatically + - send_invoice + type: string + coupon: + description: The ID of the coupon to apply to this subscription. + A coupon applied to a subscription will only affect invoices created + for that particular subscription. + maxLength: 5000 + type: string + days_until_due: + description: Number of days a customer has to pay invoices generated + by this subscription. Valid only for subscriptions where `collection_method` + is set to `send_invoice`. + type: integer + default_payment_method: + description: ID of the default payment method for the subscription. + It must belong to the customer associated with the subscription. + This takes precedence over `default_source`. If neither are set, + invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) + or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + maxLength: 5000 + type: string + default_source: + description: ID of the default payment source for the subscription. + It must belong to the customer associated with the subscription + and be in a chargeable state. If `default_payment_method` is also + set, `default_payment_method` will take precedence. If neither + are set, invoices will use the customer's [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) + or [default_source](https://stripe.com/docs/api/customers/object#customer_object-default_source). + maxLength: 5000 + type: string + default_tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + description: The tax rates that will apply to any subscription item + that does not have `tax_rates` set. Invoices created will have + their `default_tax_rates` populated from the subscription. Pass + an empty string to remove previously-defined tax rates. + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + items: + description: A list of up to 20 subscription items, each with an + attached price. + items: + properties: + billing_thresholds: + anyOf: + - properties: + usage_gte: + type: integer + required: + - usage_gte + title: item_billing_thresholds_param + type: object + - enum: + - '' + type: string + clear_usage: + type: boolean + deleted: + type: boolean + id: + maxLength: 5000 + type: string + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + recurring: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: recurring_adhoc + type: object + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + - recurring + title: recurring_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: subscription_item_update_params + type: object + type: array + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + off_session: + description: Indicates if a customer is on or off-session while + an invoice payment is attempted. + type: boolean + pause_collection: + anyOf: + - properties: + behavior: + enum: + - keep_as_draft + - mark_uncollectible + - void + type: string + resumes_at: + format: unix-time + type: integer + required: + - behavior + title: pause_collection_param + type: object + - enum: + - '' + type: string + description: If specified, payment collection for this subscription + will be paused. + payment_behavior: + description: |- + Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. For example, SCA regulation may require 3DS authentication to complete payment. See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. This is the default behavior. + + Use `default_incomplete` to transition the subscription to `status=past_due` when payment is required and await explicit confirmation of the invoice's payment intent. This allows simpler management of scenarios where additional user actions are needed to pay a subscription’s invoice. Such as failed payments, [SCA regulation](https://stripe.com/docs/billing/migration/strong-customer-authentication), or collecting a mandate for a bank debit payment method. + + Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). + + Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's invoice cannot be paid. For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not update the subscription and returns an error instead. This was the default behavior for API versions prior to 2019-03-14. See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + enum: + - allow_incomplete + - default_incomplete + - error_if_incomplete + - pending_if_incomplete + type: string + payment_settings: + description: Payment settings to pass to invoices created by the + subscription. + properties: + payment_method_options: + properties: + bancontact: + anyOf: + - properties: + preferred_language: + enum: + - de + - en + - fr + - nl + type: string + title: invoice_payment_method_options_param + type: object + - enum: + - '' + type: string + card: + anyOf: + - properties: + request_three_d_secure: + enum: + - any + - automatic + type: string + title: invoice_payment_method_options_param + type: object + - enum: + - '' + type: string + title: payment_method_options + type: object + payment_method_types: + anyOf: + - items: + enum: + - ach_credit_transfer + - ach_debit + - au_becs_debit + - bacs_debit + - bancontact + - boleto + - card + - fpx + - giropay + - ideal + - sepa_debit + - sofort + - wechat_pay + type: string + x-stripeBypassValidation: true + type: array + - enum: + - '' + type: string + title: payment_settings + type: object + pending_invoice_item_interval: + anyOf: + - properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: pending_invoice_item_interval_params + type: object + - enum: + - '' + type: string + description: Specifies an interval for how often to bill for any + pending invoice items. It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) + for the given subscription at the specified interval. + promotion_code: + description: The promotion code to apply to this subscription. A + promotion code applied to a subscription will only affect invoices + created for that particular subscription. + maxLength: 5000 + type: string + proration_behavior: + description: |- + Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. Valid values are `create_prorations`, `none`, or `always_invoice`. + + Passing `create_prorations` will cause proration invoice items to be created when applicable. These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). In order to always invoice immediately for prorations, pass `always_invoice`. + + Prorations can be disabled by passing `none`. + enum: + - always_invoice + - create_prorations + - none + type: string + proration_date: + description: If set, the proration will be calculated as though + the subscription was updated at the given time. This can be used + to apply exactly the same proration that was previewed with [upcoming + invoice](https://stripe.com/docs/api#retrieve_customer_invoice) + endpoint. It can also be used to implement custom proration logic, + such as prorating by day instead of by second, by providing the + time that you wish to use for proration calculations. + format: unix-time + type: integer + transfer_data: + anyOf: + - properties: + amount_percent: + type: number + destination: + type: string + required: + - destination + title: transfer_data_specs + type: object + - enum: + - '' + type: string + description: If specified, the funds from the subscription's invoices + will be transferred to the destination and the ID of the resulting + transfers will be found on the resulting charges. This will be + unset if you POST an empty value. + trial_end: + anyOf: + - enum: + - now + maxLength: 5000 + type: string + - format: unix-time + type: integer + description: Unix timestamp representing the end of the trial period + the customer will get before being charged for the first time. + This will always overwrite any trials that might apply via a subscribed + plan. If set, trial_end will override the default trial period + of the plan the customer is being subscribed to. The special value + `now` can be provided to end the customer's trial immediately. + Can be at most two years from `billing_cycle_anchor`. + trial_from_plan: + description: Indicates if a plan's `trial_period_days` should be + applied to the subscription. Setting `trial_end` per subscription + is preferred, and this defaults to `false`. Setting this flag + to `true` together with `trial_end` is not allowed. + type: boolean + type: object + description: Subscription details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + delete: + description: |- +

Cancels a customer’s subscription immediately. The customer will not be charged again for the subscription.

+ +

Note, however, that any pending invoice items that you’ve created will still be charged for at the end of the period, unless manually deleted. If you’ve set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations will be removed.

+ +

By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all.

+ operationId: DeleteSubscription + tags: + - "Subscriptions" + parameters: + - in: path + name: subscription_exposed_id + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: subscription Id + - in: query + name: invoice_now + required: false + schema: + type: boolean + description: Will generate a final invoice that invoices for any un-invoiced metered usage and new/pending proration invoice items. + style: simple + - in: query + required: false + name: prorate + schema: + type: boolean + description: Will generate a proration invoice item that credits remaining unused time until the subscription period end. + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_schedules": + get: + description: "

Retrieves the list of your subscription schedules.

" + operationId: listSubscriptionSchedules + tags: + - "Subscription_Schedule" + parameters: + - description: Only return subscription schedules that were created canceled + the given date interval. + explode: true + in: query + name: canceled_at + required: false + schema: + $ref: '#/components/schemas/CreatedDetails' + style: deepObject + - description: Only return subscription schedules that completed during the + given date interval. + explode: true + in: query + name: completed_at + required: false + schema: + $ref: '#/components/schemas/CreatedDetails' + style: deepObject + - description: Only return subscription schedules that were created during the + given date interval. + explode: true + in: query + name: created + required: false + schema: + $ref: '#/components/schemas/CreatedDetails' + style: deepObject + - description: Only return subscription schedules for the given customer. + in: query + name: customer + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: A cursor for use in pagination. `ending_before` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with `obj_bar`, your subsequent + call can include `ending_before=obj_bar` in order to fetch the previous + page of the list. + in: query + name: ending_before + required: false + schema: + maxLength: 5000 + type: string + style: form + - description: A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 10. + in: query + name: limit + required: false + schema: + type: integer + style: form + - description: Only return subscription schedules that were released during + the given date interval. + explode: true + in: query + name: released_at + required: false + schema: + $ref: '#/components/schemas/CreatedDetails' + style: deepObject + - description: Only return subscription schedules that have not started yet. + in: query + name: scheduled + required: false + schema: + type: boolean + style: form + - description: A cursor for use in pagination. `starting_after` is an object + ID that defines your place in the list. For instance, if you make a list + request and receive 100 objects, ending with `obj_foo`, your subsequent + call can include `starting_after=obj_foo` in order to fetch the next page + of the list. + in: query + name: starting_after + required: false + schema: + maxLength: 5000 + type: string + style: form + responses: + '200': + content: + application/json: + schema: + description: '' + properties: + data: + items: + "$ref": "#/components/schemas/subscription_schedule" + type: array + has_more: + description: True if this list has another page of items after + this one that can be fetched. + type: boolean + object: + description: String representing the object's type. Objects of + the same type share the same value. Always has the value `list`. + enum: + - list + type: string + url: + description: The URL where this list can be accessed. + maxLength: 5000 + pattern: "^/v1/subscription_schedules" + type: string + required: + - data + - has_more + - object + - url + type: object + x-expandableFields: + - data + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: "

Creates a new subscription schedule object. Each customer can + have up to 500 active or scheduled subscriptions.

" + operationId: createSubscriptionSchedule + tags: + - "Subscription_Schedule" + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + default_settings: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + phases: + explode: true + style: deepObject + start_date: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + customer: + description: The identifier of the customer to create the subscription + schedule for. + maxLength: 5000 + type: string + default_settings: + description: Object representing the subscription schedule's default + settings. + properties: + application_fee_percent: + type: number + description: A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner’s Stripe account. The request must be made by a platform account on a connected account in order to set an application fee percentage. + automatic_tax: + properties: + enabled: + type: boolean + description: Enabled automatic tax calculation which will automatically compute tax rates on all invoices generated by the subscription + required: + - enabled + title: automatic_tax_config + type: object + description: Default settings for automatic tax computation + billing_cycle_anchor: + enum: + - automatic + - phase_start + type: string + description: Can be set to phase_start to set the anchor to the start of the phase or automatic to automatically change it if needed. Cannot be set to phase_start if this phase specifies a trial + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/billing_threshold_params" + type: object + - enum: + - '' + type: string + description: Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. Pass an empty string to remove previously-defined thresholds + collection_method: + enum: + - charge_automatically + - send_invoice + type: string + description: Either charge_automatically, or send_invoice. When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions. Defaults to charge_automatically on creation + default_payment_method: + maxLength: 5000 + type: string + description: ID of the default payment method for the subscription schedule. It must belong to the customer associated with the subscription schedule. If not set, invoices will use the default payment method in the customer’s invoice settings + invoice_settings: + properties: + days_until_due: + type: integer + title: subscription_schedules_param + type: object + description: All invoices will be billed using the specified settings + transfer_data: + anyOf: + - $ref: "#/components/schemas/transfer_data_specs" + - enum: + - '' + type: string + description: The data with which to automatically create a Transfer for each of the associated subscription’s invoices + title: default_settings_params + type: object + end_behavior: + description: Configures how the subscription schedule behaves when + it ends. Possible values are `release` or `cancel` with the default + being `release`. `release` will end the subscription schedule + and keep the underlying subscription running.`cancel` will end + the subscription schedule and cancel the underlying subscription. + enum: + - cancel + - none + - release + - renew + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + from_subscription: + description: Migrate an existing subscription to be managed by a + subscription schedule. If this parameter is set, a subscription + schedule will be created using the subscription's item(s), set + to auto-renew using the subscription's interval. When using this + parameter, other parameters (such as phase values) cannot be set. + To create a subscription schedule with other modifications, we + recommend making two separate API calls. + maxLength: 5000 + type: string + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + phases: + description: List representing phases of the subscription schedule. + Each phase can be customized to have different durations, plans, + and coupons. If there are multiple phases, the `end_date` of one + phase will always equal the `start_date` of the next phase. + items: + properties: + add_invoice_items: + items: + properties: + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + title: one_time_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: add_invoice_item_entry + type: object + type: array + application_fee_percent: + type: number + automatic_tax: + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_config + type: object + billing_cycle_anchor: + enum: + - automatic + - phase_start + type: string + billing_thresholds: + anyOf: + - properties: + amount_gte: + type: integer + reset_billing_cycle_anchor: + type: boolean + title: billing_thresholds_param + type: object + - enum: + - '' + type: string + collection_method: + enum: + - charge_automatically + - send_invoice + type: string + coupon: + maxLength: 5000 + type: string + default_payment_method: + maxLength: 5000 + type: string + default_tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + end_date: + format: unix-time + type: integer + invoice_settings: + properties: + days_until_due: + type: integer + title: subscription_schedules_param + type: object + items: + items: + properties: + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/item_billing_thresholds_param" + - enum: + - '' + type: string + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + recurring: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: recurring_adhoc + type: object + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + - recurring + title: recurring_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: configuration_item_params + type: object + type: array + iterations: + type: integer + proration_behavior: + enum: + - always_invoice + - create_prorations + - none + type: string + transfer_data: + properties: + amount_percent: + type: number + destination: + type: string + required: + - destination + title: transfer_data_specs + type: object + trial: + type: boolean + trial_end: + format: unix-time + type: integer + required: + - items + title: phase_configuration_params + type: object + type: array + start_date: + anyOf: + - type: integer + - enum: + - now + maxLength: 5000 + type: string + description: When the subscription schedule starts. We recommend + using `now` so that it starts the subscription immediately. You + can also use a Unix timestamp to backdate the subscription so + that it starts on a past date, or set a future date for the subscription + to start on. + type: object + description: Subscription details + required: false + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription_schedule" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_schedules/{schedule}": + get: + description: "

Retrieves the details of an existing subscription schedule. + You only need to supply the unique subscription schedule identifier that was + returned upon subscription schedule creation.

" + operationId: GetSubscriptionSchedule + tags: + - "Subscription_Schedule" + parameters: + - in: path + name: schedule + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription schedule Id + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription_schedule" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + post: + description: "

Updates an existing subscription schedule.

" + operationId: updateSubscriptionSchedule + tags: + - "Subscription_Schedule" + parameters: + - in: path + name: schedule + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription schedule Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + default_settings: + explode: true + style: deepObject + expand: + explode: true + style: deepObject + metadata: + explode: true + style: deepObject + phases: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + default_settings: + description: Object representing the subscription schedule's default + settings. + properties: + application_fee_percent: + type: number + automatic_tax: + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_config + type: object + billing_cycle_anchor: + enum: + - automatic + - phase_start + type: string + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/billing_threshold_params" + - enum: + - '' + type: string + collection_method: + enum: + - charge_automatically + - send_invoice + type: string + default_payment_method: + maxLength: 5000 + type: string + invoice_settings: + properties: + days_until_due: + type: integer + title: subscription_schedules_param + type: object + transfer_data: + anyOf: + - $ref: "#/components/schemas/transfer_data_specs" + - enum: + - '' + type: string + title: default_settings_params + type: object + end_behavior: + description: Configures how the subscription schedule behaves when + it ends. Possible values are `release` or `cancel` with the default + being `release`. `release` will end the subscription schedule + and keep the underlying subscription running.`cancel` will end + the subscription schedule and cancel the underlying subscription. + enum: + - cancel + - none + - release + - renew + type: string + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + metadata: + anyOf: + - additionalProperties: + type: string + type: object + - enum: + - '' + type: string + description: Set of [key-value pairs](https://stripe.com/docs/api/metadata) + that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to `metadata`. + phases: + description: List representing phases of the subscription schedule. + Each phase can be customized to have different durations, plans, + and coupons. If there are multiple phases, the `end_date` of one + phase will always equal the `start_date` of the next phase. Note + that past phases can be omitted. + items: + properties: + add_invoice_items: + items: + properties: + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + title: one_time_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: add_invoice_item_entry + type: object + type: array + application_fee_percent: + type: number + automatic_tax: + properties: + enabled: + type: boolean + required: + - enabled + title: automatic_tax_config + type: object + billing_cycle_anchor: + enum: + - automatic + - phase_start + type: string + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/billing_threshold_params" + - enum: + - '' + type: string + collection_method: + enum: + - charge_automatically + - send_invoice + type: string + coupon: + maxLength: 5000 + type: string + default_payment_method: + maxLength: 5000 + type: string + default_tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + end_date: + anyOf: + - type: integer + - enum: + - now + maxLength: 5000 + type: string + invoice_settings: + properties: + days_until_due: + type: integer + title: subscription_schedules_param + type: object + items: + items: + properties: + billing_thresholds: + anyOf: + - $ref: "#/components/schemas/item_billing_thresholds_param" + - enum: + - '' + type: string + price: + maxLength: 5000 + type: string + price_data: + properties: + currency: + type: string + product: + maxLength: 5000 + type: string + recurring: + properties: + interval: + enum: + - day + - month + - week + - year + type: string + interval_count: + type: integer + required: + - interval + title: recurring_adhoc + type: object + tax_behavior: + enum: + - exclusive + - inclusive + - unspecified + type: string + unit_amount: + type: integer + unit_amount_decimal: + format: decimal + type: string + required: + - currency + - product + - recurring + title: recurring_price_data + type: object + quantity: + type: integer + tax_rates: + anyOf: + - items: + maxLength: 5000 + type: string + type: array + - enum: + - '' + type: string + title: configuration_item_params + type: object + type: array + iterations: + type: integer + proration_behavior: + enum: + - always_invoice + - create_prorations + - none + type: string + start_date: + anyOf: + - type: integer + - enum: + - now + maxLength: 5000 + type: string + transfer_data: + properties: + amount_percent: + type: number + destination: + type: string + required: + - destination + title: transfer_data_specs + type: object + trial: + type: boolean + trial_end: + anyOf: + - type: integer + - enum: + - now + maxLength: 5000 + type: string + required: + - items + title: phase_configuration_params + type: object + type: array + proration_behavior: + description: If the update changes the current phase, indicates + if the changes should be prorated. Possible values are `create_prorations` + or `none`, and the default value is `create_prorations`. + enum: + - always_invoice + - create_prorations + - none + type: string + type: object + required: false + description: Subscription schedule details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription_schedule" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_schedules/{schedule}/cancel": + post: + description: "

Cancels a subscription schedule and its associated subscription + immediately (if the subscription schedule has an active subscription). A subscription + schedule can only be canceled if its status is not_started or + active.

" + operationId: cancelSubscriptionSchedule + tags: + - "Subscription_Schedule" + parameters: + - in: path + name: schedule + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription schedule Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + invoice_now: + description: If the subscription schedule is `active`, indicates + if a final invoice will be generated that contains any un-invoiced + metered usage and new/pending proration invoice items. Defaults + to `true`. + type: boolean + prorate: + description: If the subscription schedule is `active`, indicates + if the cancellation should be prorated. Defaults to `true`. + type: boolean + type: object + required: false + description: Subscription schedule details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription_schedule" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. + "/v1/subscription_schedules/{schedule}/release": + post: + description: "

Releases the subscription schedule immediately, which will + stop scheduling of its phases, but leave any existing subscription in place. + A schedule can only be released if its status is not_started + or active. If the subscription schedule is currently associated + with a subscription, releasing it will remove its subscription + property and set the subscription’s ID to the released_subscription + property.

" + operationId: releaseSubscriptionSchedule + tags: + - "Subscription_Schedule" + parameters: + - in: path + name: schedule + required: true + schema: + maxLength: 5000 + type: string + style: simple + description: Subscription schedule Id + requestBody: + content: + application/x-www-form-urlencoded: + encoding: + expand: + explode: true + style: deepObject + schema: + additionalProperties: false + properties: + expand: + description: Specifies which fields in the response should be expanded. + items: + maxLength: 5000 + type: string + type: array + preserve_cancel_date: + description: Keep any cancellation on the subscription that the + schedule has set + type: boolean + type: object + required: false + description: Subscription schedule details + responses: + '200': + content: + application/json: + schema: + "$ref": "#/components/schemas/subscription_schedule" + description: Successful response. + default: + content: + application/json: + schema: + "$ref": "#/components/schemas/error" + description: Error response. \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/vimeo.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/vimeo.yaml new file mode 100644 index 000000000..f1f1939ff --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/vimeo.yaml @@ -0,0 +1,21915 @@ +openapi: 3.0.2 +servers: + - description: Vimeo.com + url: https://api.vimeo.com +info: + x-ballerina-display: + label: Vimeo + iconPath: "icon.png" + contact: + url: https://developer.vimeo.com/help + x-twitter: vimeo + title: Vimeo + description: > + This is a generated connector for [Vimeo API v3.4](https://developer.vimeo.com/) OpenAPI specification. + + The Vimeo API provides access to manage Vimeo platform. This includes management of videos, channels, albums, users etc. + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Create a [Vimeo account](https://vimeo.com/join) and obtain tokens by following [this guide](https://developer.vimeo.com/api/authentication). + version: "3.4" + x-apisguru-categories: + - entertainment + x-logo: + url: https://twitter.com/vimeo/profile_image?size=original + x-origin: + - converter: + url: https://github.com/lucybot/api-spec-converter + version: 2.7.31 + format: openapi + url: https://raw.githubusercontent.com/vimeo/openapi/master/api.yaml + version: "3.0" + x-providerName: vimeo.com +security: + - oauth2: + - create + - delete + - edit + - email + - interact + - private + - promo_codes + - public + - purchase + - purchased + - stats + - upload + - video_files +tags: + - name: API Information + - name: Albums\Album videos + - name: Albums\Custom album logos + - name: Albums\Custom album thumbnails + - name: Albums\Essentials + - name: Authentication Extras\Essentials + - name: Categories\Channels + - name: Categories\Essentials + - name: Categories\Groups + - name: Categories\Subscriptions + - name: Categories\Videos + - name: Channels\Categories + - name: Channels\Essentials + - name: Channels\Moderators + - name: Channels\Private channel members + - name: Channels\Subscriptions and subscribers + - name: Channels\Tags + - name: Channels\Videos + - name: Embed Presets\Custom Logos + - name: Embed Presets\Essentials + - name: Embed Presets\Videos + - name: Groups\Essentials + - name: Groups\Subscription + - name: Groups\Users + - name: Groups\Videos + - name: Likes\Essentials + - name: On Demand\Backgrounds + - name: On Demand\Essentials + - name: On Demand\Genres + - name: On Demand\Posters + - name: On Demand\Promotions + - name: On Demand\Purchases and Rentals + - name: On Demand\Regions + - name: On Demand\Seasons + - name: On Demand\Videos + - name: Portfolios\Essentials + - name: Portfolios\Videos + - name: Projects\Essentials + - name: Projects\Videos + - name: Tags\Essentials + - name: Users\Essentials + - name: Users\Feed + - name: Users\Follows + - name: Users\Internal + - name: Users\Pictures + - name: Users\Watch History + - name: Videos\Comments + - name: Videos\Content Ratings + - name: Videos\Creative Commons + - name: Videos\Credits + - name: Videos\Embed Privacy + - name: Videos\Essentials + - name: Videos\Languages + - name: Videos\Recommendations + - name: Videos\Tags + - name: Videos\Text Tracks + - name: Videos\Thumbnails + - name: Videos\Upload + - name: Videos\Versions + - name: Videos\Viewing Privacy + - name: Watch Later Queue\Essentials +paths: + /: + get: + operationId: get_endpoints + parameters: + - description: Return an OpenAPI specification. + in: query + name: openapi + required: false + schema: + example: "true" + type: boolean + responses: + "200": + content: + application/vnd.vimeo.endpoint+json: + schema: + $ref: "#/components/schemas/endpoint" + description: Standard request. + summary: Get an API specification + tags: + - API Information + /categories: + get: + description: This method gets all existing categories. + operationId: get_categories + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - last_video_featured_time + - name + type: string + responses: + "200": + content: + application/vnd.vimeo.category+json: + schema: + items: + $ref: "#/components/schemas/category" + type: array + description: The categories were returned. + summary: Get all categories + tags: + - Categories\Essentials + "/categories/{category}": + get: + operationId: get_category + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + responses: + "200": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/category" + description: The category was returned. + "404": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such category exists. + summary: Get a specific category + tags: + - Categories\Essentials + "/categories/{category}/channels": + get: + operationId: get_category_channels + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - followers + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + items: + $ref: "#/components/schemas/channel" + type: array + description: The channels were returned. + "404": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such category exists. + summary: Get all the channels in a category + tags: + - Categories\Channels + "/categories/{category}/groups": + get: + operationId: get_category_groups + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - members + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.group+json: + schema: + items: + $ref: "#/components/schemas/group" + type: array + description: The groups were returned. + "404": + content: + application/vnd.vimeo.group+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such category exists. + summary: Get all the groups in a category + tags: + - Categories\Groups + "/categories/{category}/videos": + get: + operationId: get_category_videos + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: | + The attribute by which to filter the results. + + Option descriptions: + * `conditional_featured` - Featured (promoted) videos + in: query + name: filter + required: false + schema: + enum: + - conditional_featured + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - featured + - likes + - plays + - relevant + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such category exists. + summary: Get all the videos in a category + tags: + - Categories\Videos + "/categories/{category}/videos/{video_id}": + get: + operationId: check_category_for_video + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 273576296 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video belongs to the category. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such category exists, or the video doesn't belong to it. + summary: Check for a video in a category + tags: + - Categories\Videos + /channels: + get: + operationId: get_channels + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - featured + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: | + The way to sort the results. + + Option descriptions: + * `relevant` - Relevant sorting is available only for search queries. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - followers + - relevant + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + items: + $ref: "#/components/schemas/channel" + type: array + description: The channels were returned. + "400": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The relevant sort has no search query. + summary: Get all channels + tags: + - Channels\Essentials + post: + description: This method creates a new channel. + operationId: create_channel + requestBody: + content: + application/vnd.vimeo.channel+json: + schema: + properties: + description: + description: The description of the channel. + example: We really love videos, and these are the videos we really, really love. + type: string + link: + description: The link to access the channel. You can use a custom name in the URL in place of a numeric channel ID, as in `/channels/{url_custom}`. + example: staffpicks + type: string + name: + description: The name of the channel. + example: Vimeo Staff Picks + type: string + privacy: + description: The privacy level of the channel. + enum: + - anybody + - moderators + - user + type: string + required: + - name + - privacy + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/channel" + description: The channel was created. + "400": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't create a channel. + security: + - oauth2: + - create + summary: Create a channel + tags: + - Channels\Essentials + "/channels/{channel_id}": + delete: + operationId: delete_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + description: The channel was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own this channel. + security: + - oauth2: + - delete + summary: Delete a channel + tags: + - Channels\Essentials + get: + operationId: get_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/channel" + description: The channel was returned. + summary: Get a specific channel + tags: + - Channels\Essentials + patch: + description: This method edits the specified channel. + operationId: edit_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/vnd.vimeo.channel+json: + schema: + properties: + description: + description: The description of the channel. + example: We really love videos, and these are the videos we really, really love. + type: string + link: + description: The link to access the channel. You can use a custom name in the URL in place of a numeric channel ID, as in `/channels/{url_custom}`. Submitting `""` for this field removes the link alias. + example: staffpicks + type: string + name: + description: The name of the channel. + example: Vimeo Staff Picks + type: string + privacy: + description: The privacy level of the channel. + enum: + - anybody + - moderators + - users + type: string + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/channel" + description: The channel was edited. + "400": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + security: + - oauth2: + - edit + summary: Edit a channel + tags: + - Channels\Essentials + "/channels/{channel_id}/categories": + get: + description: This method gets all the categories in the specified channel. + operationId: get_channel_categories + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "200": + content: + application/vnd.vimeo.category+json: + schema: + items: + $ref: "#/components/schemas/category" + type: array + description: The categories were returned. + "404": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Get all the categories in a channel + tags: + - Channels\Categories + put: + description: This method adds multiple categories to the specified channel. + operationId: add_channel_categories + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/json: + schema: + properties: + channels: + description: The array of category URIs to add. + items: + type: string + type: array + required: + - channels + type: object + required: true + responses: + "204": + description: The categories were added. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: There was no request body, or the request body is malformed. + * Error code 2204: You exceeded the maximum number of channel categories. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't add categories to the channel." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Add a list of categories to a channel + tags: + - Channels\Categories + "/channels/{channel_id}/categories/{category}": + delete: + description: This method removes a single category from the specified channel. + operationId: delete_channel_category + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + description: The channel was removed. + "401": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user doesn't own the channel or isn't a channel moderator." + "404": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel or category exists. + security: + - oauth2: + - edit + summary: Remove a category from a channel + tags: + - Channels\Categories + put: + description: This method adds a channel to a category. + operationId: categorize_channel + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + description: The channel was categorized. + "400": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: You exceeded the maximum number of channel categories." + "401": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user doesn't own the channel or isn't a channel moderator." + "404": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel or category exists. + security: + - oauth2: + - edit + summary: Categorize a channel + tags: + - Channels\Categories + "/channels/{channel_id}/moderators": + delete: + operationId: remove_channel_moderators + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The moderators were removed. + "403": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the channel, the user isn't a moderator of the channel, or you tried to remove the owner of the channel. + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such user exists. + security: + - oauth2: + - edit + summary: Remove a list of channel moderators + tags: + - Channels\Moderators + get: + operationId: get_channel_moderators + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The moderators were returned. + summary: Get all the moderators in a channel + tags: + - Channels\Moderators + patch: + operationId: replace_channel_moderators + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/json: + schema: + properties: + user_uri: + description: The URI of the user to add as a moderator. + example: /users/152184 + type: string + required: + - user_uri + type: object + required: true + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The moderators were replaced. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2908: The list contains more than 100 users." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user owns this channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + security: + - oauth2: + - edit + summary: Replace the moderators of a channel + tags: + - Channels\Moderators + put: + operationId: add_channel_moderators + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/json: + schema: + properties: + user_uri: + description: The URI of a user to add as a moderator. + example: /users/152184 + type: string + required: + - user_uri + type: object + required: true + responses: + "200": + description: The moderators were added. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2908: The list contains more than 100 users." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the channel, a user is already a moderator of the channel, or you tried to add a user that the authenticated user doesn't follow. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such user exists. + security: + - oauth2: + - edit + summary: Add a list of channel moderators + tags: + - Channels\Moderators + "/channels/{channel_id}/moderators/{user_id}": + delete: + operationId: remove_channel_moderator + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The moderator was removed. + "403": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the channel, the user isn't a moderator of the channel, or you tried to remove the owner of the channel. + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such user exists. + security: + - oauth2: + - edit + summary: Remove a specific channel moderator + tags: + - Channels\Moderators + get: + operationId: get_channel_moderator + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The moderator was returned. + summary: Get a specific channel moderator + tags: + - Channels\Moderators + put: + operationId: add_channel_moderator + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "403": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the channel, a user is already a moderator of the channel, or you tried to add a user that the authenticated user doesn't follow. + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such user exists. + security: + - oauth2: + - edit + summary: Add a specific channel moderator + tags: + - Channels\Moderators + "/channels/{channel_id}/privacy/users": + get: + description: This method gets all the users who have access to the specified private channel. + operationId: get_channel_privacy_users + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users were returned. + "401": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user doesn't own this channel." + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: You can't add this user to a channel of this type." + summary: Get all the users who can view a private channel + tags: + - Channels\Private channel members + put: + description: This method gives multiple users access to the specified private channel. + operationId: set_channel_privacy_users + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/vnd.vimeo.user+json: + schema: + properties: + users: + description: The array of either the user URIs or the user IDs to permit to view the private channel. + items: + type: string + type: array + required: + - users + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users can now view the private channel. + "400": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: There was no request body, or the request body is malformed. + * Error code 2900: At least one of the specified user accounts doesn't exist. + "401": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user doesn't own this channel." + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: You can't add one or more of these users to a channel of this type." + security: + - oauth2: + - edit + summary: Permit a list of users to view a private channel + tags: + - Channels\Private channel members + "/channels/{channel_id}/privacy/users/{user_id}": + delete: + description: This method prevents a single user from being able to access the specified private channel. + operationId: delete_channel_privacy_user + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user can no longer view the private channel. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user doesn't own this channel." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: You can't add this user to a channel of this type." + security: + - oauth2: + - edit + summary: Restrict a user from viewing a private channel + tags: + - Channels\Private channel members + put: + description: This method gives a single user access to the specified private channel. + operationId: set_channel_privacy_user + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + description: The user can now view the private channel. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user doesn't own this channel." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: You can't add this user to a channel of this type." + security: + - oauth2: + - edit + summary: Permit a specific user to view a private channel + tags: + - Channels\Private channel members + "/channels/{channel_id}/tags": + get: + description: This method gets all the tags that have been added to the specified channel. + operationId: get_channel_tags + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "200": + content: + application/vnd.vimeo.tag+json: + schema: + items: + $ref: "#/components/schemas/tag" + type: array + description: The tags were returned. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Get all the tags that have been added to a channel + tags: + - Channels\Tags + put: + description: This method adds multiple tags to the specified channel. + operationId: add_tags_to_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/vnd.vimeo.tag+json: + schema: + properties: + tag: + description: An array of tags to assign. + items: + type: string + type: array + required: + - tag + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.tag+json: + schema: + items: + $ref: "#/components/schemas/tag" + type: array + description: The tags were added. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such channel exists, or a parameter is invalid. + * Error code 2501: You tried to add more than 20 tags to the channel. + * Error code 2205: There was no request body, or the request body is malformed. + "401": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't add tags to this channel." + security: + - oauth2: + - edit + summary: Add a list of tags to a channel + tags: + - Channels\Tags + "/channels/{channel_id}/tags/{word}": + delete: + description: This method removes a single tag from the specified channel. + operationId: delete_tag_from_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The word to use as the tag. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "204": + description: The tag was removed. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The tag is invalid, or a parameter is invalid. + "401": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't remove tags from this channel." + security: + - oauth2: + - edit + summary: Remove a tag from a channel + tags: + - Channels\Tags + get: + description: This method determines whether a specific tag has been added to the channel in question. + operationId: check_if_channel_has_tag + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The word to use as the tag. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "204": + description: The tag has been added to the channel. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such tag exists. + "404": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: The tag exists, but the channel isn't tagged by it." + summary: Check if a tag has been added to a channel + tags: + - Channels\Tags + put: + description: This method adds a single tag to the specified channel. + operationId: add_channel_tag + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The word to use as the tag. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "204": + description: The tag was added. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The tag is invalid, or a parameter is invalid. + * Error code 2501: The channel has already reached its maximum number of 20 tags. + "401": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't add tags to this channel." + security: + - oauth2: + - edit + summary: Add a specific tag to a channel + tags: + - Channels\Tags + "/channels/{channel_id}/users": + get: + operationId: get_channel_subscribers + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: true + schema: + enum: + - moderators + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The followers were returned. + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Get all the followers of a channel + tags: + - Channels\Subscriptions and subscribers + "/channels/{channel_id}/videos": + delete: + operationId: remove_videos_from_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + content: + application/json: + schema: + $ref: "#/components/schemas/video" + description: The videos were removed. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user isn't a moderator of this channel, or you can't remove this video from the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such user exists. + security: + - oauth2: + - edit + summary: Remove a list of videos from a channel + tags: + - Channels\Videos + get: + operationId: get_channel_videos + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The page that contains the video URI. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - added + - alphabetical + - comments + - date + - default + - duration + - likes + - manual + - modified_time + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "304": + description: No videos have been added to this channel since the given `If-Modified-Since` header. + "400": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The **sort** field is `default`, but the **direction** field has a value. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Get all the videos in a channel + tags: + - Channels\Videos + put: + operationId: add_videos_to_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + requestBody: + content: + application/json: + schema: + properties: + video_uri: + description: The URI of a video to add. + example: /videos/258684937 + type: string + required: + - video_uri + type: object + required: true + responses: + "200": + description: The videos were added. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user isn't a moderator of the channel, or the video can't be added to the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such user exists. + security: + - oauth2: + - edit + summary: Add a list of videos to a channel + tags: + - Channels\Videos + "/channels/{channel_id}/videos/{video_id}": + delete: + operationId: delete_video_from_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was removed. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user isn't a moderator of this channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such video exists. + security: + - oauth2: + - edit + summary: Remove a specific video from a channel + tags: + - Channels\Videos + get: + description: This method returns a specific video in a channel. You can use it to determine whether the video is in the channel. + operationId: get_channel_video + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Get a specific video in a channel + tags: + - Channels\Videos + put: + operationId: add_video_to_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video can't be added to channels, or the authenticated user isn't the moderator of this channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists, or no such video exists. + security: + - oauth2: + - edit + summary: Add a specific video to a channel + tags: + - Channels\Videos + "/channels/{channel_id}/videos/{video_id}/comments": + get: + operationId: get_comments_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.comment+json: + schema: + items: + $ref: "#/components/schemas/comment" + type: array + description: The comments were returned. + summary: Get all the comments on a video + tags: + - Videos\Comments + post: + operationId: create_comment_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.comment+json: + schema: + properties: + text: + description: The text of the comment. + example: I love this! + type: string + required: + - text + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/comment" + description: The comment was added. + "400": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2207: The comment text is missing." + "401": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 3413: Comments are disabled for this video. + * Error code 3411: The authenticated user is unverified. + * Error code 3412: The authenticated user can't comment. + * Error code 3301: The comment was flagged as spam. + security: + - oauth2: + - interact + summary: Add a comment to a video + tags: + - Videos\Comments + "/channels/{channel_id}/videos/{video_id}/credits": + get: + operationId: get_video_credits_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.credit+json: + schema: + items: + $ref: "#/components/schemas/credit" + type: array + description: The users were returned. + summary: Get all the credited users in a video + tags: + - Videos\Credits + post: + operationId: add_video_credit_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.credit+json: + schema: + properties: + email: + description: The email address of the credited person. + example: user@example.com + type: string + name: + description: The name of the credited person. + example: Sam Doe + type: string + role: + description: The role of the credited person. + example: Producer + type: string + user_uri: + description: The URI of the Vimeo user who should be given credit in this video. + example: /users/152184 + type: string + required: + - email + - name + - role + - user_uri + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/credit" + description: The credit was added. + "400": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The credit was added. + * A parameter is invalid. + * The authenticated user has an unverified email address. + * There is a user block between the video owner and the person receiving credit. + "403": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the video. + summary: Credit a user in a video + tags: + - Videos\Credits + "/channels/{channel_id}/videos/{video_id}/likes": + get: + operationId: get_video_likes_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users were returned. + summary: Get all the users who have liked a video + tags: + - Likes\Essentials + "/channels/{channel_id}/videos/{video_id}/pictures": + get: + operationId: get_video_thumbnails_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The thumbnails were returned. + summary: Get all the thumbnails of a video + tags: + - Videos\Thumbnails + post: + operationId: create_video_thumbnail_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether the image created by the `time` field should be the default thumbnail for the video. + example: "true" + type: boolean + time: + description: Creates an image of the video from the given time offset. + example: 300 + type: number + type: object + required: false + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The thumbnail was created. + security: + - oauth2: + - upload + summary: Add a video thumbnail + tags: + - Videos\Thumbnails + "/channels/{channel_id}/videos/{video_id}/privacy/users": + get: + operationId: get_video_privacy_users_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users were returned. + "400": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No users can view the private video. + summary: Get all the users who can view a user's private videos by default + tags: + - Videos\Viewing Privacy + put: + description: |- + The body of this request should follow our + [batch request format](https://developer.vimeo.com/api/common-formats#batch-requests). Each object must contain + a single `URI` field, and the value of this field must be the URI of the user who can view this video. + operationId: add_video_privacy_users_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users can now view the private video. + security: + - oauth2: + - edit + summary: Permit a list of users to view a private video + tags: + - Videos\Viewing Privacy + "/channels/{channel_id}/videos/{video_id}/texttracks": + get: + operationId: get_text_tracks_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + items: + $ref: "#/components/schemas/text-track" + type: array + description: The text tracks were returned. + "404": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video exists. + summary: Get all the text tracks of a video + tags: + - Videos\Text Tracks + post: + description: For additional information, see our [text track upload guide](https://developer.vimeo.com/api/upload/texttracks). + operationId: create_text_track_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.video.texttrack+json: + schema: + properties: + active: + description: Active text tracks appear in the player and are visible to other users. Only one text track per language can be active. + example: "true" + type: boolean + language: + description: The language of the text track. For a complete list of valid languages, use the [/languages?filter=texttracks](https://developer.vimeo.com/api/endpoints/videos#GET/languages) endpoint. + example: en-US + type: string + name: + description: The name of the text track. + example: Commentary + type: string + type: + description: The type of the text track. + enum: + - captions + - chapters + - descriptions + - metadata + - subtitles + type: string + required: + - language + - name + - type + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/text-track" + description: The text track was added. + "403": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user can't edit the text track. + * Error code 2204: The request contains errors. + security: + - oauth2: + - upload + summary: Add a text track to a video + tags: + - Videos\Text Tracks + /contentratings: + get: + operationId: get_content_ratings + responses: + "200": + content: + application/vnd.vimeo.contentrating+json: + schema: + items: + $ref: "#/components/schemas/content-rating" + type: array + description: The content ratings were returned. + summary: Get all content ratings + tags: + - Videos\Content Ratings + /creativecommons: + get: + operationId: get_cc_licenses + responses: + "200": + content: + application/vnd.vimeo.creativecommons+json: + schema: + items: + $ref: "#/components/schemas/creative-commons" + type: array + description: The Creative Commons licenses were returned. + summary: Get all Creative Commons licenses + tags: + - Videos\Creative Commons + /groups: + get: + operationId: get_groups + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - featured + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: | + The way to sort the results. + + Option descriptions: + * `relevant` - Relevant sorting is available only for search queries. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - followers + - relevant + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.group+json: + schema: + items: + $ref: "#/components/schemas/group" + type: array + description: The groups were returned. + summary: Get all groups + tags: + - Groups\Essentials + post: + operationId: create_group + requestBody: + content: + application/vnd.vimeo.group+json: + schema: + properties: + description: + description: The description of the new group. + example: Want to participate in our weekly Challenges? Join the Group to receive messages and new Challenges! + type: string + name: + description: The name of the new group. + example: Vimeo Weekend Challenge + type: string + required: + - name + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.group+json: + schema: + $ref: "#/components/schemas/group" + description: The group was created. + "400": + content: + application/vnd.vimeo.group+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.group+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't create groups. + security: + - oauth2: + - create + summary: Create a group + tags: + - Groups\Essentials + "/groups/{group_id}": + delete: + operationId: delete_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + responses: + "204": + description: The group was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user isn't the group owner. + security: + - oauth2: + - delete + summary: Delete a group + tags: + - Groups\Essentials + get: + operationId: get_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + responses: + "200": + content: + application/vnd.vimeo.group+json: + schema: + $ref: "#/components/schemas/group" + description: The group was returned. + summary: Get a specific group + tags: + - Groups\Essentials + "/groups/{group_id}/users": + get: + operationId: get_group_members + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - moderators + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The members were returned. + "404": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such group exists. + summary: Get all the members of a group + tags: + - Groups\Users + "/groups/{group_id}/videos": + get: + operationId: get_group_videos + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "304": + description: No videos have been added to this group since the given `If-Modified-Since` header. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such group exists. + summary: Get all the videos in a group + tags: + - Groups\Videos + "/groups/{group_id}/videos/{video_id}": + delete: + operationId: delete_video_from_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this group's videos. + security: + - oauth2: + - edit + summary: Remove a video from a group + tags: + - Groups\Videos + get: + description: Check if a group has a video. + operationId: get_group_video + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or group exists. + summary: Get a specific video in a group + tags: + - Groups\Videos + put: + operationId: add_video_to_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was added. + "202": + description: The video is in pending status. + "403": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The video is already in the group. + * The user can't add videos to the group. + security: + - oauth2: + - edit + summary: Add a video to a group + tags: + - Groups\Videos + /languages: + get: + operationId: get_languages + parameters: + - description: | + The attribute by which to filter the results. + + Option descriptions: + * `texttracks` - Only return text track supported languages + in: query + name: filter + required: false + schema: + enum: + - texttracks + type: string + responses: + "200": + content: + application/vnd.vimeo.language+json: + schema: + items: + $ref: "#/components/schemas/language" + type: array + description: The languages were returned. + summary: Get all languages + tags: + - Videos\Languages + /me: + get: + operationId: get_user_alt1 + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The user was returned. + summary: Get a user + tags: + - Users\Essentials + patch: + operationId: edit_user_alt1 + requestBody: + content: + application/vnd.vimeo.user+json: + schema: + properties: + bio: + description: The user's bio. + example: This is where you will find videos and news updates from the staff + type: string + content_filter: + description: A list of values describing the content in this video. Find the full list in the [/contentratings](https://developer.vimeo.com/api/endpoints/videos#GET/contentratings) endpoint. You must provide a comma-separated list if you are using a query string or an array if you are using JSON. + items: + type: string + type: array + link: + description: The user's custom Vimeo URL slug. + example: staff + type: string + location: + description: The user's location. + example: New York City + type: string + name: + description: The user's display name. + example: Vimeo Staff + type: string + password: + description: The default password for all future videos that this user uploads. To use this field, the `videos.privacy.view` field must be `password`. + example: hunter1 + type: string + videos: + properties: + privacy: + properties: + add: + description: Whether a user can add the video to an album, channel, or group. This value becomes the default add setting for all future videos uploaded by the user. + example: "true" + type: boolean + comments: + description: Who can comment on the video. This value becomes the default comment setting for all future videos that this user uploads. + enum: + - anybody + - contacts + - nobody + type: string + download: + description: Whether a user can download the video. This value becomes the default download setting for all future videos that this user uploads. + example: "true" + type: boolean + embed: + description: The privacy for embed videos. The `whitelist` value enables you to define all valid embed domains. See our [documentation](https://developer.vimeo.com/api/endpoints/videos#/{video_id}/privacy/domains) for adding and removing domains. + enum: + - private + - public + - whitelist + type: string + view: + description: Who can view the video. This value becomes the default view setting for all future videos that this user uploads. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + type: string + type: object + type: object + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The user was edited. + summary: Edit a user + tags: + - Users\Essentials + /me/albums: + get: + operationId: get_albums_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - duration + - videos + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/album" + type: array + description: The albums were returned. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + summary: Get all the albums that belong to a user + tags: + - Albums\Essentials + post: + operationId: create_album_alt1 + requestBody: + content: + application/vnd.vimeo.album+json: + schema: + properties: + brand_color: + description: The hexadecimal code for the color of the player buttons. + example: ff66ee + type: string + description: + description: The description of the album. + example: Vimeo holiday videos! + type: string + hide_nav: + description: Whether to hide Vimeo navigation when displaying the album. + example: "true" + type: boolean + layout: + description: The type of layout for presenting the album. + enum: + - grid + - player + type: string + name: + description: The name of the album. + example: Vimeo Holiday Videos! + type: string + password: + description: The album's password. Required only if **privacy** is `password`. + example: hunter1 + type: string + privacy: + description: The privacy level of the album. + enum: + - anybody + - embed_only + - password + type: string + review_mode: + description: Whether album videos should use the review mode URL. + example: "true" + type: boolean + sort: + description: The default sort order of the album's videos. + enum: + - added_first + - added_last + - alphabetical + - arranged + - comments + - likes + - newest + - oldest + - plays + type: string + theme: + description: The color theme of the album. + enum: + - dark + - standard + type: string + required: + - name + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/album" + description: The album was created. + "400": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't create an album. + security: + - oauth2: + - create + summary: Create an album + tags: + - Albums\Essentials + "/me/albums/{album_id}": + delete: + operationId: delete_album_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + responses: + "204": + description: The album was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't delete the album. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - delete + summary: Delete an album + tags: + - Albums\Essentials + get: + operationId: get_album_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + responses: + "200": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/album" + description: The album was returned. + "404": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + summary: Get a specific album + tags: + - Albums\Essentials + patch: + operationId: edit_album_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + requestBody: + content: + application/vnd.vimeo.album+json: + schema: + properties: + brand_color: + description: The hexadecimal code for the color of the player buttons. + example: ff66ee + type: string + description: + description: The description of the album. + example: Vimeo holiday videos! + type: string + domain: + description: The custom domain a user has selected for their album. + example: mycustomdomain.com + nullable: true + type: string + hide_nav: + description: Whether to hide Vimeo navigation when displaying the album. + example: "true" + type: boolean + layout: + description: The type of layout for presenting the album. + enum: + - grid + - player + type: string + name: + description: The name of the album. + example: Vimeo Holiday Videos! + type: string + password: + description: The album's password. Required only if **privacy** is `password`. + example: hunter1 + type: string + privacy: + description: The privacy level of the album. + enum: + - anybody + - embed_only + - password + type: string + review_mode: + description: Whether album videos should use the review mode URL. + example: "true" + type: boolean + sort: + description: The default sort order of the album's videos. + enum: + - added_first + - added_last + - alphabetical + - arranged + - comments + - likes + - newest + - oldest + - plays + type: string + theme: + description: The color theme of the album. + enum: + - dark + - standard + type: string + url: + description: The custom Vimeo URL a user has selected for their album. + example: my-custom-url + nullable: true + type: string + use_custom_domain: + description: Whether the user has opted in to use a custom domain for their album. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/album" + description: The album was edited. + "400": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the album, the supplied token doesn't have the proper scopes, or the authenticated user can't edit the album. + "404": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Edit an album + tags: + - Albums\Essentials + "/me/albums/{album_id}/videos": + get: + operationId: get_album_videos_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The page containing the video URI. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The password of the album. + in: query + name: password + required: false + schema: + example: hunter1 + type: string + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - default + - duration + - likes + - manual + - modified_time + - plays + type: string + - description: Whether to include private videos in the search. Please note that a separate search service provides this functionality. The service performs a partial text search on the video's name. + in: query + name: weak_search + required: false + schema: + example: "false" + type: boolean + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + summary: Get all the videos in an album + tags: + - Albums\Album videos + put: + description: This method replaces all the existing videos in an album with one or more videos. + operationId: replace_videos_in_album_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + requestBody: + content: + application/json: + schema: + properties: + videos: + description: A comma-separated list of video URIs. + example: /videos/258684937,/videos/273576296 + type: string + required: + - videos + type: object + required: true + responses: + "201": + description: The videos were added. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't add videos to albums. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Replace all the videos in an album + tags: + - Albums\Album videos + "/me/albums/{album_id}/videos/{video_id}": + delete: + operationId: remove_video_from_album_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + responses: + "204": + description: The video was removed. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't edit the album. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Remove a video from an album + tags: + - Albums\Album videos + get: + description: This method gets a single video from an album. You can use this method to determine whether the album contains the specified video. + operationId: get_album_video_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + - description: The password of the album. + in: query + name: password + required: false + schema: + example: hunter1 + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or the video wasn't found in it. + summary: Get a specific video in an album + tags: + - Albums\Album videos + put: + operationId: add_video_to_album_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + responses: + "204": + description: The video was added. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't edit the album. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Add a specific video to an album + tags: + - Albums\Album videos + "/me/albums/{album_id}/videos/{video_id}/set_album_thumbnail": + post: + operationId: set_video_as_album_thumbnail_alt1 + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + requestBody: + content: + application/json: + schema: + properties: + time_code: + description: The video frame time in seconds to use as the album thumbnail. + example: 300 + type: number + type: object + required: false + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/album" + description: The album was updated with a new thumbnail. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3429: The authenticated user can't edit the album." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such album, or user, or video exists." + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4016: Unexpected error while setting thumbnail." + security: + - oauth2: + - edit + summary: Set a video as the album thumbnail + tags: + - Albums\Album videos + /me/appearances: + get: + operationId: get_appearances_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos in which a user appears + tags: + - Videos\Essentials + /me/categories: + get: + operationId: get_category_subscriptions_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - name + type: string + responses: + "200": + content: + application/vnd.vimeo.category+json: + schema: + items: + $ref: "#/components/schemas/category" + type: array + description: The categories were returned. + "403": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: You can't view another user." + security: + - oauth2: + - private + summary: Get all the categories that a user follows + tags: + - Categories\Subscriptions + "/me/categories/{category}": + delete: + operationId: unsubscribe_from_category_alt1 + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + responses: + "204": + description: The user was unsubscribed. + security: + - oauth2: + - interact + summary: Unsubscribe a user from a category + tags: + - Categories\Subscriptions + get: + operationId: check_if_user_subscribed_to_category_alt1 + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + responses: + "204": + description: The user is following the category. + security: + - oauth2: + - private + summary: Check if a user follows a category + tags: + - Categories\Subscriptions + put: + operationId: subscribe_to_category_alt1 + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: 0 + type: number + responses: + "204": + description: The user was subscribed. + security: + - oauth2: + - interact + summary: Subscribe a user to a single category + tags: + - Categories\Subscriptions + /me/channels: + get: + operationId: get_channel_subscriptions_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - moderated + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - followers + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + items: + $ref: "#/components/schemas/channel" + type: array + description: The channels were returned. + "304": + description: No channel has been followed since the given `If-Modified-Since` header. + summary: Get all the channels to which a user subscribes + tags: + - Channels\Essentials + "/me/channels/{channel_id}": + delete: + operationId: unsubscribe_from_channel_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + description: The user is no longer a follower of the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + security: + - oauth2: + - interact + summary: Unsubscribe a user from a specific channel + tags: + - Channels\Subscriptions and subscribers + get: + operationId: check_if_user_subscribed_to_channel_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + description: The user follows the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Check if a user follows a channel + tags: + - Channels\Subscriptions and subscribers + put: + operationId: subscribe_to_channel_alt1 + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + responses: + "204": + description: The user is now a follower of the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + security: + - oauth2: + - interact + summary: Subscribe a user to a specific channel + tags: + - Channels\Subscriptions and subscribers + /me/customlogos: + get: + operationId: get_custom_logos_alt1 + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The custom logos were returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The user can't view this custom logo. + * The user can't view custom logos. + summary: Get all the custom logos that belong to a user + tags: + - Embed Presets\Custom Logos + post: + operationId: create_custom_logo_alt1 + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was created. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * You can't upload pictures for another user's videos. + * The user can't add a custom logo. + security: + - oauth2: + - upload + summary: Add a custom logo + tags: + - Embed Presets\Custom Logos + "/me/customlogos/{logo_id}": + get: + operationId: get_custom_logo_alt1 + parameters: + - description: The ID of the custom logo. + in: path + name: logo_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user can't view custom logos. + summary: Get a specific custom logo + tags: + - Embed Presets\Custom Logos + /me/feed: + get: + operationId: get_feed_alt1 + parameters: + - description: Necessary for proper pagination. You shouldn't provide this value yourself, and instead use the pagination links in the feed response. Please see our [pagination documentation](https://developer.vimeo.com/api/common-formats#using-the-pagination-parameter) for more information. + in: query + name: offset + required: false + schema: + example: "280" + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The feed type. + in: query + name: type + required: false + schema: + enum: + - appears + - category_featured + - channel + - facebook_feed + - following + - group + - likes + - ondemand_publish + - share + - tagged_with + - twitter_timeline + - uploads + type: string + responses: + "200": + content: + application/vnd.vimeo.activity+json: + schema: + items: + $ref: "#/components/schemas/activity-3-1" + type: array + description: The videos were returned. + security: + - oauth2: + - private + summary: Get all videos in a user's feed + tags: + - Users\Feed + /me/followers: + get: + operationId: get_followers_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The user's followers were returned. + summary: Get all the followers of a user + tags: + - Users\Follows + /me/following: + get: + operationId: get_user_following_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - online + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The followed users were returned. + summary: Get all the users that a user is following + tags: + - Users\Follows + post: + operationId: follow_users_alt1 + requestBody: + content: + application/json: + schema: + properties: + users: + description: An array of user URIs for the list of users to follow. + items: + type: string + type: array + required: + - users + type: object + required: true + responses: + "204": + description: The users were followed. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: The request body is empty. + * Error code 2205: The `users` array is invalid. + * Error code 2205: The list of users doesn't contain URIs. + * Error code 2900: A user in the list doesn't exist. + * Error code 2901: The list contains more than 100 users. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user access token is invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3417: The current user can't follow other users." + "429": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 9006: The current user is rate-limited from following other users." + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4005: An unexpected error occurred." + security: + - oauth2: + - interact + summary: Follow a list of users + tags: + - Users\Follows + "/me/following/{follow_user_id}": + delete: + operationId: unfollow_user_alt1 + parameters: + - description: The ID of the following user. + in: path + name: follow_user_id + required: true + schema: + example: 3766357 + type: number + responses: + "204": + description: The user was unfollowed. + security: + - oauth2: + - interact + summary: Unfollow a user + tags: + - Users\Follows + get: + operationId: check_if_user_is_following_alt1 + parameters: + - description: The ID of the following user. + in: path + name: follow_user_id + required: true + schema: + example: 3766357 + type: number + responses: + "204": + description: The authenticated user follows the user in question. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user in question doesn't follow the authenticated user. + summary: Check if a user is following another user + tags: + - Users\Follows + put: + operationId: follow_user_alt1 + parameters: + - description: The ID of the following user. + in: path + name: follow_user_id + required: true + schema: + example: 3766357 + type: number + responses: + "204": + description: The user was followed. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't add followers. + security: + - oauth2: + - interact + summary: Follow a specific user + tags: + - Users\Follows + /me/groups: + get: + operationId: get_user_groups_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - moderated + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - members + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.group+json: + schema: + items: + $ref: "#/components/schemas/group" + type: array + description: The groups were returned. + summary: Get all the groups that a user has joined + tags: + - Groups\Users + "/me/groups/{group_id}": + delete: + operationId: leave_group_alt1 + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + responses: + "204": + description: The user left the group. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user owns the group. To remove this user, first apply a new group owner through PATCH. + security: + - oauth2: + - interact + summary: Remove a user from a group + tags: + - Groups\Subscription + get: + operationId: check_if_user_joined_group_alt1 + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + responses: + "204": + description: The user has joined the group. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such group exists. + * The authenticated user isn't a member of this group. + summary: Check if a user has joined a group + tags: + - Groups\Users + put: + operationId: join_group_alt1 + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + responses: + "204": + description: The user joined the group. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user can't join groups. + * The group prohibits the authenticated user from joining, either because the group is not public or because the group's privacy setting is `members`. + security: + - oauth2: + - interact + summary: Add a user to a group + tags: + - Groups\Subscription + /me/likes: + get: + operationId: get_likes_alt1 + parameters: + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos that a user has liked + tags: + - Likes\Essentials + "/me/likes/{video_id}": + delete: + operationId: unlike_video_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was unliked. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't like videos. + security: + - oauth2: + - interact + summary: Cause a user to unlike a video + tags: + - Likes\Essentials + get: + operationId: check_if_user_liked_video_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The user has liked the video. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user hasn't liked the video. + summary: Check if a user has liked a video + tags: + - Likes\Essentials + put: + operationId: like_video_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was liked. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user owns the video. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't like videos. + security: + - oauth2: + - interact + summary: Cause a user to like a video + tags: + - Likes\Essentials + /me/ondemand/pages: + get: + operationId: get_user_vods_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The type of On Demand pages to return. + in: query + name: filter + required: false + schema: + enum: + - film + - series + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - added + - alphabetical + - date + - modified_time + - name + - publish.time + - rating + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + items: + $ref: "#/components/schemas/on-demand-page" + type: array + description: The On Demand pages were returned. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such user exists. + summary: Get all the On Demand pages of a user + tags: + - On Demand\Essentials + post: + operationId: create_vod_alt1 + requestBody: + content: + application/json: + schema: + properties: + accepted_currencies: + description: | + An array of accepted currencies. + + Option descriptions: + * `AUD` - Australian Dollar + * `CAD` - Canadian Dollar + * `CHF` - Swiss Franc + * `DKK` - Danish Krone + * `EUR` - Euro + * `GBP` - British Pound + * `JPY` - Japanese Yen + * `KRW` - South Korean Won + * `NOK` - Norwegian Krone + * `PLN` - Polish Zloty + * `SEK` - Swedish Krona + * `USD` - US Dollar + enum: + - AUD + - CAD + - CHF + - DKK + - EUR + - GBP + - JPY + - KRW + - NOK + - PLN + - SEK + - USD + type: string + buy: + properties: + active: + description: Whether the Buy action is active. *Required if `rent.active` is false. + example: "true" + type: boolean + download: + description: Whether people who buy the video can download it. To use this field, `type` must be `film`. + example: "true" + type: boolean + price: + properties: + AUD: + description: The purchase price of this video in AUD. + example: 2.99 + type: number + CAD: + description: The purchase price of this video in CAD. + example: 2.99 + type: number + CHF: + description: The purchase price of this video in CHF. + example: 2.99 + type: number + DKK: + description: The purchase price of this video in DKK. + example: 2.99 + type: number + EUR: + description: The purchase price of this video in EUR. + example: 2.99 + type: number + GBP: + description: The purchase price of this video in GBP. + example: 2.99 + type: number + JPY: + description: The purchase price of this video in JPY. + example: 2.99 + type: number + KRW: + description: The purchase price of this video in KRW. + example: 2.99 + type: number + NOK: + description: The purchase price of this video in NOK. + example: 2.99 + type: number + PLN: + description: The purchase price of this video in PLN. + example: 2.99 + type: number + SEK: + description: The purchase price of this video in SEK. + example: 2.99 + type: number + USD: + description: The purchase price of this video in USD when `type` is `film`, or the purchase price of the entire collection in USD when `type` is `series`. + example: 2.99 + type: number + type: object + type: object + content_rating: + description: One or more ratings, either as a comma-separated list or as a JSON array depending on the request format. + enum: + - drugs + - language + - nudity + - safe + - unrated + - violence + type: string + description: + description: The description of the On Demand page. + example: DARBY FOREVER follows the fantasies of Darby, a shopgirl at "Bobbins & Notions". + type: string + domain_link: + description: The custom domain of the On Demand page. + example: https://example.com + type: string + episodes: + properties: + buy: + properties: + active: + description: Whether episodes can be bought. + example: "true" + type: boolean + download: + description: Whether people who buy the episode can download it. To use this field, `type` must be `series`. + example: "true" + type: boolean + price: + properties: + USD: + description: The purchase price per episode. *Required if `episodes.buy.active` is true. + example: 1.99 + type: number + type: object + type: object + rent: + properties: + active: + description: Whether episodes can be rented + example: "true" + type: boolean + period: + description: The period in which this episode can be rented for. + enum: + - 1 week + - 1 year + - 24 hour + - 3 month + - 30 day + - 48 hour + - 6 month + - 72 hour + type: string + price: + properties: + USD: + description: The default price to rent an episode. This field is applicable only when `type` is `series`. *Required if `episodes.rent.active` is true. + example: 0.99 + type: number + type: object + type: object + type: object + link: + description: The custom string to use in this On Demand page's Vimeo URL. + example: darbyforever + type: string + name: + description: The name of the On Demand page. + example: Darby Forever + type: string + rent: + properties: + active: + description: Whether the video can be rented. *Required if `buy.active` is false. + example: "true" + type: boolean + period: + description: The period in which this can be rented for. + enum: + - 1 week + - 1 year + - 24 hour + - 3 month + - 30 day + - 48 hour + - 6 month + - 72 hour + type: string + price: + properties: + AUD: + description: The rental price of this video in AUD. + example: 0.99 + type: number + CAD: + description: The rental price of this video in CAD. + example: 0.99 + type: number + CHF: + description: The rental price of this video in CHF. + example: 0.99 + type: number + DKK: + description: The rental price of this video in DKK. + example: 0.99 + type: number + EUR: + description: The rental price of this video in EUR. + example: 0.99 + type: number + GBP: + description: The rental price of this video in GBP. + example: 0.99 + type: number + JPY: + description: The rental price of this video in JPY. + example: 0.99 + type: number + KRW: + description: The rental price of this video in KRW. + example: 0.99 + type: number + NOK: + description: The rental price of this video in NOK. + example: 0.99 + type: number + PLN: + description: The rental price of this video in PLN. + example: 0.99 + type: number + SEK: + description: The rental price of this video in SEK. + example: 0.99 + type: number + USD: + description: The rental price of this video in USD when `type` is `film`, or the rental price of the entire collection in USD when `type` is `series`. + example: 0.99 + type: number + type: object + type: object + subscription: + properties: + monthly: + properties: + active: + description: Whether monthly subscription is active. *Required if `rent.active` and `buy.active` are false. + example: "true" + type: boolean + price: + properties: + USD: + description: The monthly subscription price in USD. *Required if `subscription.active` is true. + example: 9.99 + type: number + type: object + type: object + type: object + type: + description: The type of On Demand page. + enum: + - film + - series + type: string + required: + - content_rating + - description + - name + - type + type: object + required: true + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: The On Demand page was created. + summary: Create an On Demand page + tags: + - On Demand\Essentials + /me/ondemand/purchases: + get: + operationId: get_vod_purchases + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: | + The type of On Demand videos to show. + + Option descriptions: + * `important` - Will show all pages which are about to expire. + in: query + name: filter + required: false + schema: + enum: + - all + - expiring_soon + - film + - important + - purchased + - rented + - series + - subscription + - unwatched + - watched + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - added + - alphabetical + - date + - name + - purchase_time + - rating + - release_date + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + items: + $ref: "#/components/schemas/on-demand-page" + type: array + description: The purchases and rentals were returned. + "403": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't view the purchases and rentals for another user's account. + security: + - oauth2: + - purchased + summary: Get all the On Demand purchases and rentals that a user has made + tags: + - On Demand\Purchases and Rentals + "/me/ondemand/purchases/{ondemand_id}": + get: + operationId: check_if_vod_was_purchased_alt1 + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: You have purchased the On Demand page. + "403": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The requested user isn't the same as the authenticated user. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such user or On Demand page exists. + security: + - oauth2: + - purchased + summary: Check if a user has made a purchase or rental from an On Demand page + tags: + - On Demand\Purchases and Rentals + /me/pictures: + get: + operationId: get_pictures_alt1 + parameters: + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The pictures were returned. + summary: Get all the pictures that belong to a user + tags: + - Users\Pictures + post: + operationId: create_picture_alt1 + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The user picture was created. + security: + - oauth2: + - upload + summary: Add a user picture + tags: + - Users\Pictures + "/me/pictures/{portraitset_id}": + delete: + operationId: delete_picture_alt1 + parameters: + - description: The ID of the picture. + in: path + name: portraitset_id + required: true + schema: + example: 12345 + type: number + responses: + "204": + description: The picture was deleted. + security: + - oauth2: + - delete + summary: Delete a user picture + tags: + - Users\Pictures + get: + operationId: get_picture_alt1 + parameters: + - description: The ID of the picture. + in: path + name: portraitset_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The picture was returned. + summary: Get a specific user picture + tags: + - Users\Pictures + patch: + operationId: edit_picture_alt1 + parameters: + - description: The ID of the picture. + in: path + name: portraitset_id + required: true + schema: + example: 12345 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether the picture is the user's active portrait. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The picture was edited. + security: + - oauth2: + - edit + summary: Edit a user picture + tags: + - Users\Pictures + /me/portfolios: + get: + operationId: get_portfolios_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.portfolio+json: + schema: + items: + $ref: "#/components/schemas/portfolio" + type: array + description: The portfolios were returned. + summary: Get all the portfolios that belong to a user + tags: + - Portfolios\Essentials + "/me/portfolios/{portfolio_id}": + get: + operationId: get_portfolio_alt1 + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.portfolio+json: + schema: + $ref: "#/components/schemas/portfolio" + description: The portfolio was returned. + summary: Get a specific portfolio + tags: + - Portfolios\Essentials + "/me/portfolios/{portfolio_id}/videos": + get: + operationId: get_portfolio_videos_alt1 + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The page that contains the video URI. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: | + The way to sort the results. + + Option descriptions: + * `default` - This will sort to the default sort set on the portfolio. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - default + - likes + - manual + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos in a portfolio + tags: + - Portfolios\Videos + "/me/portfolios/{portfolio_id}/videos/{video_id}": + delete: + operationId: delete_video_from_portfolio_alt1 + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The portfolio wasn't found, or the video wasn't found. + security: + - oauth2: + - edit + summary: Remove a video from a portfolio + tags: + - Portfolios\Videos + get: + operationId: get_portfolio_video_alt1 + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + summary: Get a specific video in a portfolio + tags: + - Portfolios\Videos + put: + operationId: add_video_to_portfolio_alt1 + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The portfolio wasn't found, or the video wasn't found. + security: + - oauth2: + - edit + summary: Add a video to a portfolio + tags: + - Portfolios\Videos + /me/presets: + get: + operationId: get_embed_presets_alt1 + parameters: + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.preset+json: + schema: + items: + $ref: "#/components/schemas/presets" + type: array + description: The embed presets were returned. + summary: Get all the embed presets that a user has created + tags: + - Embed Presets\Essentials + "/me/presets/{preset_id}": + get: + operationId: get_embed_preset_alt1 + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/presets" + description: The embed preset was returned. + summary: Get a specific embed preset + tags: + - Embed Presets\Essentials + patch: + operationId: edit_embed_preset_alt1 + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + requestBody: + content: + application/vnd.vimeo.preset+json: + schema: + properties: + outro: + description: Disable the outro. + enum: + - nothing + type: string + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/presets" + description: The embed preset was edited. + "400": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The outro type is invalid. + "404": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The preset doesn't exist. + * The authenticated user doesn't own the preset. + summary: Edit an embed preset + tags: + - Embed Presets\Essentials + "/me/presets/{preset_id}/videos": + get: + operationId: get_embed_preset_videos_alt1 + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos that have been added to an embed preset + tags: + - Embed Presets\Videos + /me/projects: + get: + description: This method gets all the projects that belong to the specified user. + operationId: get_projects_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - date + - default + - modified_time + - name + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/project" + type: array + description: The projects were returned. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + security: + - oauth2: + - private + summary: Get all the projects that belong to a user + tags: + - Projects\Essentials + post: + description: This method creates a new project for the specified user. + operationId: create_project_alt1 + requestBody: + content: + application/json: + schema: + properties: + name: + description: The name of the project. + example: Rough cuts + type: string + required: + - name + type: object + required: true + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/project" + description: The project was created. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: The input is empty. + * Error code 2204: The input is invalid. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't create projects." + security: + - oauth2: + - create + summary: Create a project + tags: + - Projects\Essentials + "/me/projects/{project_id}": + delete: + description: This method deletes a project and optionally also the videos that it contains. + operationId: delete_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: Whether to delete all the videos in the project along with the project itself. + in: query + name: should_delete_clips + required: false + schema: + example: "true" + type: boolean + responses: + "204": + description: The project was deleted. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't delete the project." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - delete + summary: Delete a project + tags: + - Projects\Essentials + get: + description: This method gets a single project that belongs to the specified user. + operationId: get_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/project" + description: The project was returned. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - private + summary: Get a specific project + tags: + - Projects\Essentials + patch: + description: This method edits an existing project. + operationId: edit_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + requestBody: + content: + application/json: + schema: + properties: + name: + description: The name of the project. + example: Rough cuts + type: string + required: + - name + type: object + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/project" + description: The project was edited. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2204: The input is invalid. + * Error code 2205: The input is empty. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't edit the project." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - edit + summary: Edit a project + tags: + - Projects\Essentials + "/me/projects/{project_id}/videos": + delete: + description: This method removed multiple videos from the specified project. + operationId: remove_videos_from_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: Whether to delete the videos when removing them from the project. + in: query + name: should_delete_clips + required: false + schema: + example: "false" + type: boolean + - description: A comma-separated list of the video URIs to remove. + in: query + name: uris + required: true + schema: + example: /videos/258684937,/videos/273576296 + type: string + responses: + "204": + description: The videos were removed. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: The input is invalid." + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - interact + summary: Remove a list of videos from a project + tags: + - Projects\Videos + get: + description: This method gets all the videos that belong to the specified project. + operationId: get_project_videos_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - default + - duration + - last_user_action_event_date + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - private + summary: Get all the videos in a project + tags: + - Projects\Videos + put: + description: This method adds multiple videos to the specified project. + operationId: add_videos_to_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: A comma-separated list of video URIs to add. + in: query + name: uris + required: true + schema: + example: /videos/258684937,/videos/273576296 + type: string + responses: + "204": + description: The videos were added. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: The input is invalid." + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project or video exists." + security: + - oauth2: + - interact + summary: Add a list of videos to a project + tags: + - Projects\Videos + "/me/projects/{project_id}/videos/{video_id}": + delete: + description: This method removes a single video from the specified project. + operationId: remove_video_from_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was removed. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: The input is invalid." + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such video exists in the project." + security: + - oauth2: + - delete + summary: Remove a specific video from a project + tags: + - Projects\Videos + put: + description: This method adds a single video to the specified project. + operationId: add_video_to_project_alt1 + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such user, project, or video exists." + security: + - oauth2: + - interact + summary: Add a specific video to a project + tags: + - Projects\Videos + /me/videos: + get: + operationId: get_videos_alt1 + parameters: + - description: The page that contains the video URI. Only available when not paired with `query`. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - app_only + - embeddable + - featured + - playable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: Whether to filter by all playable videos or by all videos that are not playable. + in: query + name: filter_playable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - default + - duration + - last_user_action_event_date + - likes + - modified_time + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "304": + description: This user hasn't created any videos since the given `If-Modified-Since` header. + summary: Get all the videos that a user has uploaded + tags: + - Videos\Essentials + post: + description: Begin the video upload process. For more information, see our [upload documentation](https://developer.vimeo.com/api/upload/videos). + operationId: upload_video_alt1 + requestBody: + content: + application/vnd.vimeo.video+json: + schema: + properties: + content_rating: + description: A list of values describing the content in this video. Find the full list in the [/contentratings](https://developer.vimeo.com/api/endpoints/videos#GET/contentratings) endpoint. + items: + type: string + type: array + description: + description: The description of the video. + example: A celebration of 10 years of Staff Picks. + type: string + embed: + properties: + buttons: + properties: + embed: + description: Show or hide the Embed button. + example: "true" + type: boolean + fullscreen: + description: Show or hide the Fullscreen button. + example: "true" + type: boolean + hd: + description: Show or hide the HD button. + example: "true" + type: boolean + like: + description: Show or hide the Like button. + example: "true" + type: boolean + scaling: + description: Show or hide the Scaling button (shown only in Fullscreen mode). + example: "true" + type: boolean + share: + description: Show or hide the Share button. + example: "true" + type: boolean + watchlater: + description: Show or hide the Watch Later button. + example: "true" + type: boolean + type: object + color: + description: The main color of the embed player. + example: "#1ab7ea" + type: string + logos: + properties: + custom: + properties: + active: + description: Show or hide your custom logo. + example: "true" + type: boolean + link: + description: The URL that loads when the user clicks your custom logo. + example: https://example.com + type: string + sticky: + description: Whether always to show the custom logo or to hide it after time with the rest of the UI. + example: "true" + type: boolean + type: object + vimeo: + description: Show or hide the Vimeo logo. + example: "true" + type: boolean + type: object + playbar: + description: Show or hide the playbar. + example: "true" + type: boolean + title: + properties: + name: + description: Show or hide the video title, or enable the user to determine whether the video title appears. + enum: + - hide + - show + - user + type: string + owner: + description: Show or hide the owner information, or enable the user to determine whether the owner information appears. + enum: + - hide + - show + - user + type: string + portrait: + description: Show or hide the owner portrait, or enable the user to determine whether the owner portrait appears. + enum: + - hide + - show + - user + type: string + type: object + volume: + description: Show or hide the volume selector. + example: "true" + type: boolean + type: object + license: + description: The Creative Commons license. + enum: + - by + - by-nc + - by-nc-nd + - by-nc-sa + - by-nd + - by-sa + - cc0 + type: string + locale: + description: The video's default language. For a full list of valid languages, use the [/languages?filter=texttracks](https://developer.vimeo.com/api/endpoints/videos#GET/languages) endpoint. + example: en_US + type: string + name: + description: The title of the video. + example: Celebrating 10 Years of Staff Picks + type: string + password: + description: The password. When you set `privacy.view` to `password`, you must provide the password as an additional parameter. + example: hunter1 + type: string + privacy: + properties: + add: + description: Whether a user can add the video to an album, channel, or group. + example: "true" + type: boolean + comments: + description: The privacy level required to comment on the video. + enum: + - anybody + - contacts + - nobody + type: string + download: + description: Whether a user can download the video. Not available to users with a Basic membership + example: "true" + type: boolean + embed: + description: The video's embed settings. The `whitelist` value enables you to define all valid embed domains. See our [documentation](https://developer.vimeo.com/api/endpoints/videos#/{video_id}/privacy/domains) for details on adding and removing domains. + enum: + - private + - public + - whitelist + type: string + view: + description: The video's privacy setting. When privacy is `users`, `application/json` is the only valid content type. Basic users can't set privacy to `unlisted`. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + type: string + type: object + ratings: + properties: + mpaa: + properties: + reason: + description: | + The reason for the video's MPAA rating. + + Option descriptions: + * `at` - Adult themes + * `bn` - Brief nudity + * `n` - Nudity + * `sl` - Strong language + * `ss` - Sexual situations + * `v` - Violence + enum: + - at + - bn + - n + - sl + - ss + - v + type: string + type: object + tv: + properties: + reason: + description: | + The reason for the video's TV rating. + + Option descriptions: + * `d` - Suggestive dialogue + * `fv` - Fantasy violence + * `l` - Language + * `ss` - Sexual situations + * `v` - Violence + enum: + - d + - fv + - l + - ss + - v + type: string + type: object + type: object + review_page: + properties: + active: + description: Enable or disable video review. + example: "true" + type: boolean + type: object + spatial: + properties: + director_timeline: + description: The 360 director timeline. + items: + properties: + pitch: + description: The timeline pitch. This value must be between -90 and 90. + example: 70 + type: number + roll: + description: The timeline roll. + type: number + time_code: + description: The 360 director timeline time code. + example: 5 + type: number + yaw: + description: The timeline yaw. This value must be between 0 and 360. + example: 125 + type: number + required: + - pitch + - time_code + - yaw + type: object + type: array + field_of_view: + description: "The 360 field of view: default 50, minimum 30, maximum 90." + example: 50 + type: number + projection: + description: The 360 spatial projection. + enum: + - cubical + - cylindrical + - dome + - equirectangular + - pyramid + type: string + stereo_format: + description: The 360 spatial stereo format. + enum: + - left-right + - mono + - top-bottom + type: string + type: object + upload: + properties: + approach: + description: The upload approach. + enum: + - post + - pull + - streaming + - tus + type: string + link: + description: The public URL at which the video is hosted. The URL must be valid for at least 24 hours. Use this parameter when `approach` is `pull`. + example: https://example.com/video.mp4 + type: string + redirect_url: + description: The app's redirect URL. Use this parameter when `approach` is `post`. + example: https://example.com + type: string + size: + description: The size in bytes of the video to upload. + example: "13623861" + type: string + required: + - approach + type: object + required: + - upload + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The upload procedure has begun. + "400": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: The body of the request isn't formatted properly. + * Error code 2204: The request contains invalid parameters. + * Error code 2204: The request contains invalid body parameters. + * Error code 2230: The upload type is invalid. + * Error code 3116: If a `type` payload parameter was supplied instead of `upload.approach`. + "401": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8002: No user is associated with the authentication token." + "403": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 4102: The user's allotted quota has been reached. + * Error code 4101: The user's maximum disk space has been reached. + "500": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4003: There is a problem initiating the upload." + summary: Upload a video + tags: + - Videos\Upload + "/me/videos/{video_id}": + get: + operationId: check_if_user_owns_video_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The user owns the video. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the video. + summary: Check if a user owns a video + tags: + - Videos\Essentials + /me/watched/videos: + delete: + operationId: delete_watch_history + responses: + "204": + description: The watch history was deleted. + security: + - oauth2: + - delete + summary: Delete a user's watch history + tags: + - Users\Watch History + get: + operationId: get_watch_history + parameters: + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "403": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user can't view another user's watch history. + security: + - oauth2: + - private + summary: Get all the videos that a user has watched + tags: + - Users\Watch History + "/me/watched/videos/{video_id}": + delete: + operationId: delete_from_watch_history + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted from your watch history. + security: + - oauth2: + - delete + summary: Delete a specific video from a user's watch history + tags: + - Users\Watch History + /me/watchlater: + get: + operationId: get_watch_later_queue_alt1 + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "304": + description: The user hasn't added any videos to their Watch Later queue since the given `If-Modified-Since` header. + security: + - oauth2: + - private + summary: Get all the videos in a user's Watch Later queue + tags: + - Watch Later Queue\Essentials + "/me/watchlater/{video_id}": + delete: + operationId: delete_video_from_watch_later_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted. + security: + - oauth2: + - interact + summary: Remove a video from a user's Watch Later queue + tags: + - Watch Later Queue\Essentials + get: + operationId: check_watch_later_queue_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video appears in the user's Watch Later queue. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video doesn't appear in the user's Watch Later queue. + security: + - oauth2: + - private + summary: Check if a user has added a specific video to their Watch Later queue + tags: + - Watch Later Queue\Essentials + put: + operationId: add_video_to_watch_later_alt1 + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + security: + - oauth2: + - interact + summary: Add a video to a user's Watch Later queue + tags: + - Watch Later Queue\Essentials + /oauth/access_token: + post: + operationId: exchange_auth_code + requestBody: + content: + application/vnd.vimeo.auth+json: + schema: + properties: + code: + description: The authorization code received from the authorization server. + example: 1234abcd + type: string + grant_type: + description: The grant type. Must be set to `authorization_code`. + enum: + - authorization_code + type: string + redirect_uri: + description: The redirect URI. Must match the URI from `/oauth/authorize`. + example: https://example.com + type: string + required: + - code + - grant_type + - redirect_uri + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth" + description: The authorization code was exchanged. + "400": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth-error" + description: |- + * The grant type is invalid. + * The authorization code is invalid. + * The redirect URI doesn't match the URI to create the authorization code. + summary: Exchange an authorization code for an access token + tags: + - Authentication Extras\Essentials + /oauth/authorize/client: + post: + description: |- + For information on utilizing OAuth client authorization, see our + [authentication](/api/authentication#generate-unauthenticated-tokens) documentation or the + [Client Credentials Grant](https://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4) section of the + [OAuth spec](https://tools.ietf.org/html/draft-ietf-oauth-v2-31. + operationId: client_auth + requestBody: + content: + application/vnd.vimeo.auth+json: + schema: + properties: + grant_type: + description: The grant type. Must be set to `client_credentials`. + enum: + - client_credentials + type: string + scope: + description: A space-separated list of the authentication [scopes](https://developer.vimeo.com/api/authentication#supported-scopes) that you want to access. The default is `public`. + example: public + type: string + required: + - grant_type + - scope + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth" + description: The authorization was successful. + "401": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8001: No such client secret exists." + summary: Authorize a client with OAuth + tags: + - Authentication Extras\Essentials + /oauth/authorize/vimeo_oauth1: + post: + operationId: convert_access_token + requestBody: + content: + application/vnd.vimeo.auth+json: + schema: + properties: + grant_type: + description: The grant type. Must be set to `vimeo_oauth1`. + enum: + - vimeo_oauth1 + type: string + token: + description: The OAuth 1 token. + example: 58037c0078d5f54e15e638cc0dd882a570b13c50 + type: string + token_secret: + description: The OAuth 1 token secret. + example: NTgwMzdjMDA3OGQ1ZjU0ZTE1ZTYzOGNjMGRkODgyYTU3MGIxM2M1MA== + type: string + required: + - grant_type + - token + - token_secret + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth" + description: The tokens were converted. + "400": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth-error" + description: |- + * The token is invalid. + * The token has unauthorized scopes. + summary: Convert OAuth 1 access tokens to OAuth 2 access tokens + tags: + - Authentication Extras\Essentials + /oauth/verify: + get: + operationId: verify_token + responses: + "200": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth" + description: The token was verified. + "401": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The token isn't a valid OAuth 2 token. + summary: Verify an OAuth 2 token + tags: + - Authentication Extras\Essentials + /ondemand/genres: + get: + operationId: get_vod_genres + responses: + "200": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + items: + $ref: "#/components/schemas/on-demand-genre" + type: array + description: The On Demand genres were returned. + summary: Get all On Demand genres + tags: + - On Demand\Genres + "/ondemand/genres/{genre_id}": + get: + operationId: get_vod_genre + parameters: + - description: The ID of the genre. + in: path + name: genre_id + required: true + schema: + example: animation + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/on-demand-genre" + description: The On Demand genre was returned. + "404": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand genre exists. + summary: Get a specific On Demand genre + tags: + - On Demand\Genres + "/ondemand/genres/{genre_id}/pages": + get: + operationId: get_genre_vods + parameters: + - description: The ID of the genre. + in: path + name: genre_id + required: true + schema: + example: animation + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - country + - my_region + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - name + - publish.time + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + items: + $ref: "#/components/schemas/on-demand-page" + type: array + description: The On Demand pages were returned. + summary: Get all the On Demand pages in a genre + tags: + - On Demand\Genres + "/ondemand/genres/{genre_id}/pages/{ondemand_id}": + get: + description: Check whether a genre contains an On Demand page. + operationId: get_genre_vod + parameters: + - description: The ID of the genre. + in: path + name: genre_id + required: true + schema: + example: animation + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: The On Demand page belongs to the genre. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or genre exists. + summary: Get a specific On Demand page in a genre + tags: + - On Demand\Genres + "/ondemand/pages/{ondemand_id}": + delete: + operationId: delete_vod_draft + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "204": + description: The page draft was deleted. + "403": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + security: + - oauth2: + - delete + summary: Delete a draft of an On Demand page + tags: + - On Demand\Essentials + get: + operationId: get_vod + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: The On Demand page was returned. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + summary: Get a specific On Demand page + tags: + - On Demand\Essentials + patch: + description: Enable preorders or publish the page. + operationId: edit_vod + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + requestBody: + content: + application/vnd.vimeo.ondemand.page+json: + schema: + properties: + link: + description: The custom string to use in this On Demand page's Vimeo URL. + example: darbyforever + type: string + preorder: + properties: + active: + description: If set to true, you will enable pre-orders on the On Demand page. + example: "true" + type: boolean + publish_time: + description: The time that the On Demand page will be published. *Required if `preorder.active` is `true`. + example: 2017-05-16T15:05:43+00:00 + type: string + type: object + publish: + properties: + active: + description: Whether to publish the On Demand page. + example: "true" + type: boolean + type: object + publish_when_ready: + description: Whether to publish the On Demand page automatically after all videos are finished transcoding. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: The On Demand page was edited. + "403": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't edit the On Demand page. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + security: + - oauth2: + - edit + summary: Edit an On Demand page + tags: + - On Demand\Essentials + "/ondemand/pages/{ondemand_id}/backgrounds": + get: + operationId: get_vod_backgrounds + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The background images were returned. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + summary: Get all the backgrounds of an On Demand page + tags: + - On Demand\Backgrounds + post: + operationId: create_vod_background + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The background was created. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + security: + - oauth2: + - upload + summary: Add a background to an On Demand page + tags: + - On Demand\Backgrounds + "/ondemand/pages/{ondemand_id}/backgrounds/{background_id}": + delete: + operationId: delete_vod_background + parameters: + - description: The ID of the background. + in: path + name: background_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "204": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The background image was deleted. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: If you are attempting to modify an On Demand page you don't own. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or background image exists. + security: + - oauth2: + - edit + summary: Remove a background from an On Demand page + tags: + - On Demand\Backgrounds + get: + operationId: get_vod_background + parameters: + - description: The ID of the background. + in: path + name: background_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The background image was returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't view another user's On Demand page background. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or background image exists. + summary: Get a specific background of an On Demand page + tags: + - On Demand\Backgrounds + patch: + operationId: edit_vod_background + parameters: + - description: The ID of the background. + in: path + name: background_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether to make this background the active background. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The background was edited. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or background image exists. + security: + - oauth2: + - edit + summary: Edit a background of an On Demand page + tags: + - On Demand\Backgrounds + "/ondemand/pages/{ondemand_id}/genres": + get: + operationId: get_vod_genres_by_ondemand_id + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + items: + $ref: "#/components/schemas/on-demand-genre" + type: array + description: The genres were returned. + "404": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + summary: Get all the genres of an On Demand page + tags: + - On Demand\Genres + "/ondemand/pages/{ondemand_id}/genres/{genre_id}": + delete: + operationId: delete_vod_genre + parameters: + - description: The ID of the genre. + in: path + name: genre_id + required: true + schema: + example: animation + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "204": + description: The On Demand genre was deleted. + "400": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The On Demand page must belong to at least one genre. + "403": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or genre exists. + security: + - oauth2: + - edit + summary: Remove a genre from an On Demand page + tags: + - On Demand\Genres + get: + operationId: get_vod_genre_by_ondemand_id + parameters: + - description: The ID of the genre. + in: path + name: genre_id + required: true + schema: + example: animation + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/on-demand-genre" + description: The On Demand page's genre was returned. + "404": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or genre exists. + summary: Check whether an On Demand page belongs to a genre + tags: + - On Demand\Genres + put: + operationId: add_vod_genre + parameters: + - description: The ID of the genre. + in: path + name: genre_id + required: true + schema: + example: animation + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "201": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/on-demand-genre" + description: The genre was added. + "400": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't add more than two genres to an On Demand page. + "403": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.genre+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or genre exists. + security: + - oauth2: + - edit + summary: Add a genre to an On Demand page + tags: + - On Demand\Genres + "/ondemand/pages/{ondemand_id}/likes": + get: + description: This method gets all the users who have liked a particular video on an On Demand page. + operationId: get_vod_likes + parameters: + - description: The ID of the On Demand page. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - extra + - main + - trailer + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users were returned. + summary: Get all the users who have liked a video on an On Demand page + tags: + - Likes\Essentials + "/ondemand/pages/{ondemand_id}/pictures": + get: + operationId: get_vod_posters + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The posters were returned. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + summary: Get all the posters of an On Demand page + tags: + - On Demand\Posters + post: + operationId: add_vod_poster + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The poster was added. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify another user's On Demand page. + security: + - oauth2: + - upload + summary: Add a poster to an On Demand page + tags: + - On Demand\Posters + "/ondemand/pages/{ondemand_id}/pictures/{poster_id}": + get: + operationId: get_vod_poster + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the picture. + in: path + name: poster_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The poster was returned. + summary: Get a specific poster of an On Demand page + tags: + - On Demand\Posters + patch: + operationId: edit_vod_poster + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the picture. + in: path + name: poster_id + required: true + schema: + example: 12345 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether to make this picture the active picture. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The poster was edited. + security: + - oauth2: + - edit + summary: Edit a poster of an On Demand page + tags: + - On Demand\Posters + "/ondemand/pages/{ondemand_id}/promotions": + get: + operationId: get_vod_promotions + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The filter to apply to the results. + in: query + name: filter + required: true + schema: + enum: + - batch + - default + - single + - vip + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/on-demand-promotion" + description: The promotions were returned. + "400": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The filter is invalid. + "403": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't view promotions for an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + security: + - oauth2: + - promo_codes + summary: Get all the promotions on an On Demand page + tags: + - On Demand\Promotions + post: + operationId: create_vod_promotion + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + requestBody: + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + properties: + access_type: + description: | + The promotion access type, which is a purchase option that isn't available on the container. VIP promotions always make the content free of charge. If you use this type, you must further define the promotion with the `download` or `stream_period` fields. + + Option descriptions: + * `default` - Promotions grant discount on the existing purchase options for an On Demand Container. + * `vip` - Promotions can be used to grant free access to VOD content before it is released, or to offer a purchase option that isn't available on the container. "vip" promotions will always make the content free, and must be further defined with the `download` or `stream_period` fields. + enum: + - default + - vip + type: string + code: + description: The promotion code. This field is ignored for batch promotions. + example: sxsw2018 + type: string + discount_type: + description: | + The type of discount offered by the promo code. When `access_type` is `vip`, the value of this field must be `free`. + + Option descriptions: + * `free` - Reduces the price to zero. + * `percent` - Reduces the price by an amount defined in the "percent_off" field. + enum: + - free + - percent + type: string + download: + description: Whether the promotion grants download access to VOD content. This is necessary only when not previously defined in the On Demand container or when `access_type` is `vip` or `product_type` is `buy`. + example: "true" + type: boolean + end_time: + description: The end of the promotion period. If you don't specify a value, the promotion will never expire. + example: "1526089920" + type: string + label: + description: The description of a batch promotion. This field is ignored for single promotions. + example: sxsw + type: string + percent_off: + description: The percentage of the discount by using this promo code. This field is applicable only when `discount_type` is `percent`. + example: 50 + type: number + product_type: + description: The type of transaction to which the promotion applies. When `access_type` is `default`, the default value is `any`, but the default value is `rent` when `access_type` is `vip`. Also, when `access_type` is `vip`, the only valid product types are `buy` and `rent`. + enum: + - any + - buy + - buy_episode + - rent + - rent_episode + - subscribe + type: string + start_time: + description: The start of the promotion period. If you don't specify a value, the start time defaults to the time that the promotion was created. + example: "1526089920" + type: string + stream_period: + description: The amount of time that a user has access to the VOD content upon redeeming a promo code. This field is necessary only when not defined in the On Demand container or when creating promotions when `access_type` is `vip` or `product_type` is `rent`. + enum: + - 1_week + - 1_year + - 24_hour + - 30_day + - 3_month + - 48_hour + - 6_month + - 72_hour + type: string + total: + description: The number of promotions to generate when `type` is `batch`, or the number of uses of the promotion when `type` is `single`. + example: 9 + type: number + type: + description: | + The type of promotion. When `access_type` is `vip`, the value for this field must be `batch`. + + Option descriptions: + * `batch` - Generates many random promo codes with one use each. + * `single` - Generates one promo code that can be used many times. + enum: + - batch + - single + type: string + required: + - download + - stream_period + - total + - type + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/on-demand-promotion" + description: The promotion was added. + "400": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * There are errors in the request. + * The promo code already exists. + "403": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't create promotions for an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + security: + - oauth2: + - promo_codes + - create + summary: Add a promotion to an On Demand page + tags: + - On Demand\Promotions + "/ondemand/pages/{ondemand_id}/promotions/{promotion_id}": + delete: + operationId: delete_vod_promotion + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the promotion. + in: path + name: promotion_id + required: true + schema: + example: 12345 + type: number + responses: + "204": + description: The promotion was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't delete a promotion for an On Demand page that you not own. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or promotion exists. + security: + - oauth2: + - promo_codes + - delete + summary: Remove a promotion from an On Demand page + tags: + - On Demand\Promotions + get: + operationId: get_vod_promotion + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the promotion. + in: path + name: promotion_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/on-demand-promotion" + description: The promotion was returned. + "403": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't view a promotion for an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.promotion+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or promotion exists. + security: + - oauth2: + - promo_codes + summary: Get a specific promotion on an On Demand page + tags: + - On Demand\Promotions + "/ondemand/pages/{ondemand_id}/promotions/{promotion_id}/codes": + get: + operationId: get_vod_promotion_codes + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the promotion. + in: path + name: promotion_id + required: true + schema: + example: 12345 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.promocode+json: + schema: + $ref: "#/components/schemas/on-demand-promotion-code" + description: The codes were returned. + "403": + content: + application/vnd.vimeo.ondemand.promocode+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't create promotions for an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.promocode+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + security: + - oauth2: + - promo_codes + summary: Get all the codes of a promotion on an On Demand page + tags: + - On Demand\Promotions + "/ondemand/pages/{ondemand_id}/regions": + delete: + operationId: delete_vod_regions + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + items: + $ref: "#/components/schemas/on-demand-region" + type: array + description: The On Demand regions were deleted. + "403": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or region exists. + security: + - oauth2: + - edit + summary: Remove a list of regions from an On Demand page + tags: + - On Demand\Regions + get: + operationId: get_vod_regions + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + items: + $ref: "#/components/schemas/on-demand-region" + type: array + description: The regions were returned. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + summary: Get all the regions of an On Demand page + tags: + - On Demand\Regions + put: + operationId: set_vod_regions + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + requestBody: + content: + application/vnd.vimeo.ondemand.region+json: + schema: + properties: + countries: + description: An array of country codes. + items: + type: string + type: array + required: + - countries + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/on-demand-region" + description: The list of regions was set. + "403": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or region exists. + security: + - oauth2: + - edit + summary: Add a list of regions to an On Demand page + tags: + - On Demand\Regions + "/ondemand/pages/{ondemand_id}/regions/{country}": + delete: + operationId: delete_vod_region + parameters: + - description: The country code. + in: path + name: country + required: true + schema: + example: US + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "204": + description: The On Demand region was deleted. + "403": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or region exists. + security: + - oauth2: + - edit + summary: Remove a specific region from an On Demand page + tags: + - On Demand\Regions + get: + description: Checks whether an On Demand page belongs to a region. + operationId: get_vod_region + parameters: + - description: The country code. + in: path + name: country + required: true + schema: + example: US + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/on-demand-region" + description: The On Demand page's region was returned. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or region exists. + summary: Get a specific region of an On Demand page + tags: + - On Demand\Regions + put: + operationId: add_vod_region + parameters: + - description: The country code. + in: path + name: country + required: true + schema: + example: US + type: string + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + responses: + "201": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/on-demand-region" + description: The region was added. + "403": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or region exists. + security: + - oauth2: + - edit + summary: Add a specific region to an On Demand page + tags: + - On Demand\Regions + "/ondemand/pages/{ondemand_id}/seasons": + get: + operationId: get_vod_seasons + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - viewable + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - date + - manual + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.season+json: + schema: + items: + $ref: "#/components/schemas/on-demand-season" + type: array + description: The seasons were returned. + "404": + content: + application/vnd.vimeo.ondemand.season+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page exists. + summary: Get all the seasons on an On Demand page + tags: + - On Demand\Seasons + "/ondemand/pages/{ondemand_id}/seasons/{season_id}": + get: + operationId: get_vod_season + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the season. + in: path + name: season_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.season+json: + schema: + $ref: "#/components/schemas/on-demand-season" + description: The season was returned. + "404": + content: + application/vnd.vimeo.ondemand.season+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand page or season exists. + summary: Get a specific season on an On Demand page + tags: + - On Demand\Seasons + "/ondemand/pages/{ondemand_id}/seasons/{season_id}/videos": + get: + operationId: get_vod_season_videos + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the season. + in: path + name: season_id + required: true + schema: + example: 12345 + type: number + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - viewable + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - date + - default + - manual + - name + - purchase_time + - release_date + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos in a season on an On Demand page + tags: + - On Demand\Seasons + "/ondemand/pages/{ondemand_id}/videos": + get: + operationId: get_vod_videos + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - all + - buy + - expiring_soon + - extra + - main + - main.viewable + - rent + - trailer + - unwatched + - viewable + - watched + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - date + - default + - episode + - manual + - name + - purchase_time + - release_date + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: |- + * The videos were returned. + * The videos were returned. + summary: Get all the videos on an On Demand page + tags: + - On Demand\Videos + "/ondemand/pages/{ondemand_id}/videos/{video_id}": + delete: + operationId: delete_video_from_vod + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 12345 + type: number + responses: + "204": + description: The video was deleted. + "403": + content: + application/vnd.vimeo.ondemand.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + security: + - oauth2: + - edit + summary: Remove a video from an On Demand page + tags: + - On Demand\Videos + get: + operationId: get_vod_video + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 12345 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video is on the On Demand page. + summary: Get a specific video on an On Demand page + tags: + - On Demand\Videos + put: + operationId: add_video_to_vod + parameters: + - description: The ID of the On Demand. + in: path + name: ondemand_id + required: true + schema: + example: 61326 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 12345 + type: number + requestBody: + content: + application/vnd.vimeo.ondemand.video+json: + schema: + properties: + buy: + properties: + price: + properties: + AUD: + description: The purchase price of this video in AUD. + example: 1.99 + type: number + CAD: + description: The purchase price of this video in CAD. + example: 1.99 + type: number + CHF: + description: The purchase price of this video in CHF. + example: 1.99 + type: number + DKK: + description: The purchase price of this video in DKK. + example: 1.99 + type: number + EUR: + description: The purchase price of this video in EUR. + example: 1.99 + type: number + GBP: + description: The purchase price of this video in GBP. + example: 1.99 + type: number + JPY: + description: The purchase price of this video in JPY. + example: 1.99 + type: number + KRW: + description: The purchase price of this video in KRW. + example: 1.99 + type: number + NOK: + description: The purchase price of this video in NOK. + example: 1.99 + type: number + PLN: + description: The purchase price of this video in PLN. + example: 1.99 + type: number + SEK: + description: The purchase price of this video in SEK. + example: 1.99 + type: number + USD: + description: The purchase price of this video in USD. *Required if `buy.active` is true. + example: 1.99 + type: number + type: object + type: object + position: + description: The position of this video in the On Demand collection. + example: 10 + type: number + release_year: + description: The video release year. + example: 2018 + type: number + rent: + properties: + price: + properties: + AUD: + description: The rental price of this video in AUD. + example: 0.99 + type: number + CAD: + description: The rental price of this video in CAD. + example: 0.99 + type: number + CHF: + description: The rental price of this video in CHF. + example: 0.99 + type: number + DKK: + description: The rental price of this video in DKK. + example: 0.99 + type: number + EUR: + description: The rental price of this video in EUR. + example: 0.99 + type: number + GBP: + description: The rental price of this video in GBP. + example: 0.99 + type: number + JPY: + description: The rental price of this video in JPY. + example: 0.99 + type: number + KRW: + description: The rental price of this video in KRW. + example: 0.99 + type: number + NOK: + description: The rental price of this video in NOK. + example: 0.99 + type: number + PLN: + description: The rental price of this video in PLN. + example: 0.99 + type: number + SEK: + description: The rental price of this video in SEK. + example: 0.99 + type: number + USD: + description: The rental price of this video in USD. *Required if `rent.active` is true. + example: 0.99 + type: number + type: object + type: object + type: + description: The type of video that you are adding to the On Demand page. + enum: + - extra + - main + - trailer + type: string + required: + - type + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.ondemand.video+json: + schema: + $ref: "#/components/schemas/on-demand-video" + description: The video was added. + "400": + content: + application/vnd.vimeo.ondemand.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't add the video to this On Demand page. + "403": + content: + application/vnd.vimeo.ondemand.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't modify an On Demand page that you don't own. + security: + - oauth2: + - edit + summary: Add a video to an On Demand page + tags: + - On Demand\Videos + /ondemand/regions: + get: + operationId: get_regions + responses: + "200": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + items: + $ref: "#/components/schemas/on-demand-region" + type: array + description: The On Demand regions were returned. + summary: Get all the On Demand regions + tags: + - On Demand\Regions + "/ondemand/regions/{country}": + get: + operationId: get_region + parameters: + - description: The country code. + in: path + name: country + required: true + schema: + example: US + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/on-demand-region" + description: The On Demand region was returned. + "404": + content: + application/vnd.vimeo.ondemand.region+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such On Demand region exists. + summary: Get a specific On Demand region + tags: + - On Demand\Regions + "/tags/{word}": + get: + operationId: get_tag + parameters: + - description: The tag to return. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "200": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/tag" + description: The tag was returned. + summary: Get a specific tag + tags: + - Tags\Essentials + "/tags/{word}/videos": + get: + operationId: get_videos_with_tag + parameters: + - description: The tag word. + in: path + name: word + required: true + schema: + example: awesome + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - created_time + - duration + - name + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such tag exists. + summary: Get all the videos with a specific tag + tags: + - Videos\Tags + /tokens: + delete: + description: This method enables an app to notify the API that it is done with a token and that the token can be discarded. + operationId: delete_token + responses: + "204": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/auth" + description: The token was revoked. + "400": + content: + application/vnd.vimeo.auth+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You can't revoke access for an OAuth 1 token. + summary: Revoke the current access token + tags: + - Authentication Extras\Essentials + /users: + get: + operationId: search_users + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - followers + - relevant + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The search results were returned. + "500": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: There was an internal search error. + "503": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: Search is disabled. + summary: Search for users + tags: + - Users\Internal + "/users/{user_id}": + get: + operationId: get_user + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The user was returned. + summary: Get a user + tags: + - Users\Essentials + patch: + operationId: edit_user + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.user+json: + schema: + properties: + bio: + description: The user's bio. + example: This is where you will find videos and news updates from the staff + type: string + content_filter: + description: A list of values describing the content in this video. Find the full list in the [/contentratings](https://developer.vimeo.com/api/endpoints/videos#GET/contentratings) endpoint. You must provide a comma-separated list if you are using a query string or an array if you are using JSON. + items: + type: string + type: array + link: + description: The user's custom Vimeo URL slug. + example: staff + type: string + location: + description: The user's location. + example: New York City + type: string + name: + description: The user's display name. + example: Vimeo Staff + type: string + password: + description: The default password for all future videos that this user uploads. To use this field, the `videos.privacy.view` field must be `password`. + example: hunter1 + type: string + videos: + properties: + privacy: + properties: + add: + description: Whether a user can add the video to an album, channel, or group. This value becomes the default add setting for all future videos uploaded by the user. + example: "true" + type: boolean + comments: + description: Who can comment on the video. This value becomes the default comment setting for all future videos that this user uploads. + enum: + - anybody + - contacts + - nobody + type: string + download: + description: Whether a user can download the video. This value becomes the default download setting for all future videos that this user uploads. + example: "true" + type: boolean + embed: + description: The privacy for embed videos. The `whitelist` value enables you to define all valid embed domains. See our [documentation](https://developer.vimeo.com/api/endpoints/videos#/{video_id}/privacy/domains) for adding and removing domains. + enum: + - private + - public + - whitelist + type: string + view: + description: Who can view the video. This value becomes the default view setting for all future videos that this user uploads. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + type: string + type: object + type: object + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The user was edited. + summary: Edit a user + tags: + - Users\Essentials + "/users/{user_id}/albums": + get: + operationId: get_albums + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - duration + - videos + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/album" + type: array + description: The albums were returned. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + summary: Get all the albums that belong to a user + tags: + - Albums\Essentials + post: + operationId: create_album + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.album+json: + schema: + properties: + brand_color: + description: The hexadecimal code for the color of the player buttons. + example: ff66ee + type: string + description: + description: The description of the album. + example: Vimeo holiday videos! + type: string + hide_nav: + description: Whether to hide Vimeo navigation when displaying the album. + example: "true" + type: boolean + layout: + description: The type of layout for presenting the album. + enum: + - grid + - player + type: string + name: + description: The name of the album. + example: Vimeo Holiday Videos! + type: string + password: + description: The album's password. Required only if **privacy** is `password`. + example: hunter1 + type: string + privacy: + description: The privacy level of the album. + enum: + - anybody + - embed_only + - password + type: string + review_mode: + description: Whether album videos should use the review mode URL. + example: "true" + type: boolean + sort: + description: The default sort order of the album's videos. + enum: + - added_first + - added_last + - alphabetical + - arranged + - comments + - likes + - newest + - oldest + - plays + type: string + theme: + description: The color theme of the album. + enum: + - dark + - standard + type: string + required: + - name + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/album" + description: The album was created. + "400": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't create an album. + security: + - oauth2: + - create + summary: Create an album + tags: + - Albums\Essentials + "/users/{user_id}/albums/{album_id}": + delete: + operationId: delete_album + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The album was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't delete the album. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - delete + summary: Delete an album + tags: + - Albums\Essentials + get: + operationId: get_album + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/album" + description: The album was returned. + "404": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + summary: Get a specific album + tags: + - Albums\Essentials + patch: + operationId: edit_album + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.album+json: + schema: + properties: + brand_color: + description: The hexadecimal code for the color of the player buttons. + example: ff66ee + type: string + description: + description: The description of the album. + example: Vimeo holiday videos! + type: string + domain: + description: The custom domain a user has selected for their album. + example: mycustomdomain.com + nullable: true + type: string + hide_nav: + description: Whether to hide Vimeo navigation when displaying the album. + example: "true" + type: boolean + layout: + description: The type of layout for presenting the album. + enum: + - grid + - player + type: string + name: + description: The name of the album. + example: Vimeo Holiday Videos! + type: string + password: + description: The album's password. Required only if **privacy** is `password`. + example: hunter1 + type: string + privacy: + description: The privacy level of the album. + enum: + - anybody + - embed_only + - password + type: string + review_mode: + description: Whether album videos should use the review mode URL. + example: "true" + type: boolean + sort: + description: The default sort order of the album's videos. + enum: + - added_first + - added_last + - alphabetical + - arranged + - comments + - likes + - newest + - oldest + - plays + type: string + theme: + description: The color theme of the album. + enum: + - dark + - standard + type: string + url: + description: The custom Vimeo URL a user has selected for their album. + example: my-custom-url + nullable: true + type: string + use_custom_domain: + description: Whether the user has opted in to use a custom domain for their album. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/album" + description: The album was edited. + "400": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the album, the supplied token doesn't have the proper scopes, or the authenticated user can't edit the album. + "404": + content: + application/vnd.vimeo.album+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Edit an album + tags: + - Albums\Essentials + "/users/{user_id}/albums/{album_id}/custom_thumbnails": + get: + operationId: get_album_custom_thumbs + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The custom uploaded thumbnails were returned. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + summary: Get all the custom upload thumbnails of an album + tags: + - Albums\Custom album thumbnails + post: + operationId: create_album_custom_thumb + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom thumbnail was added to the album. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this album. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - upload + summary: Add a custom uploaded thumbnail + tags: + - Albums\Custom album thumbnails + "/users/{user_id}/albums/{album_id}/custom_thumbnails/{thumbnail_id}": + delete: + description: This method removes a custom uploaded thumbnail from the specified album. + operationId: delete_album_custom_thumbnail + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the custom thumbnail. + in: path + name: thumbnail_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The custom thumbnail was removed. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this album. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or it doesn't contain the specified custom thumbnail. + security: + - oauth2: + - edit + summary: Remove a custom uploaded album thumbnail + tags: + - Albums\Custom album thumbnails + get: + operationId: get_album_custom_thumbnail + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the custom thumbnail. + in: path + name: thumbnail_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom thumbnail was returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't view this custom thumbnail. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or it doesn't contain the specified custom thumbnail. + summary: Get a specific custom uploaded album thumbnail + tags: + - Albums\Custom album thumbnails + patch: + operationId: replace_album_custom_thumb + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the custom thumbnail. + in: path + name: thumbnail_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether to make this the active album thumbnail. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom thumbnail was replaced. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this album. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or it doesn't contain the specified custom thumbnail. + security: + - oauth2: + - edit + summary: Replace a custom uploaded album thumbnail + tags: + - Albums\Custom album thumbnails + "/users/{user_id}/albums/{album_id}/logos": + get: + operationId: get_album_logos + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The custom logos were returned. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + summary: Get all the custom logos of an album + tags: + - Albums\Custom album logos + post: + operationId: create_album_logo + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The logo was added to the album. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this album. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - upload + summary: Add a custom album logo + tags: + - Albums\Custom album logos + "/users/{user_id}/albums/{album_id}/logos/{logo_id}": + delete: + description: This method removes a custom logo from the specified album. + operationId: delete_album_logo + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the custom logo. + in: path + name: logo_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The custom logo was removed. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this album. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or it doesn't contain the specified custom logo. + security: + - oauth2: + - edit + summary: Remove a custom album logo + tags: + - Albums\Custom album logos + get: + operationId: get_album_logo + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the custom logo. + in: path + name: logo_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't view this custom logo. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or it doesn't contain the specified custom logo. + summary: Get a specific custom album logo + tags: + - Albums\Custom album logos + patch: + operationId: replace_album_logo + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the custom logo. + in: path + name: logo_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether to make this the active album logo. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was replaced. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't modify this album. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or it doesn't contain the specified custom logo. + security: + - oauth2: + - edit + summary: Replace a custom album logo + tags: + - Albums\Custom album logos + "/users/{user_id}/albums/{album_id}/videos": + get: + operationId: get_album_videos + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page containing the video URI. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The password of the album. + in: query + name: password + required: false + schema: + example: hunter1 + type: string + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - default + - duration + - likes + - manual + - modified_time + - plays + type: string + - description: Whether to include private videos in the search. Please note that a separate search service provides this functionality. The service performs a partial text search on the video's name. + in: query + name: weak_search + required: false + schema: + example: "false" + type: boolean + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + summary: Get all the videos in an album + tags: + - Albums\Album videos + put: + description: This method replaces all the existing videos in an album with one or more videos. + operationId: replace_videos_in_album + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/json: + schema: + properties: + videos: + description: A comma-separated list of video URIs. + example: /videos/258684937,/videos/273576296 + type: string + required: + - videos + type: object + required: true + responses: + "201": + description: The videos were added. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't add videos to albums. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Replace all the videos in an album + tags: + - Albums\Album videos + "/users/{user_id}/albums/{album_id}/videos/{video_id}": + delete: + operationId: remove_video_from_album + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + responses: + "204": + description: The video was removed. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't edit the album. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Remove a video from an album + tags: + - Albums\Album videos + get: + description: This method gets a single video from an album. You can use this method to determine whether the album contains the specified video. + operationId: get_album_video + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 3706071 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + - description: The password of the album. + in: query + name: password + required: false + schema: + example: hunter1 + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists, or the video wasn't found in it. + summary: Get a specific video in an album + tags: + - Albums\Album videos + put: + operationId: add_video_to_album + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + responses: + "204": + description: The video was added. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The supplied token doesn't have the proper scopes, or the authenticated user can't edit the album. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such album exists. + security: + - oauth2: + - edit + summary: Add a specific video to an album + tags: + - Albums\Album videos + "/users/{user_id}/albums/{album_id}/videos/{video_id}/set_album_thumbnail": + post: + operationId: set_video_as_album_thumbnail + parameters: + - description: The ID of the album. + in: path + name: album_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 196367152 + type: number + requestBody: + content: + application/json: + schema: + properties: + time_code: + description: The video frame time in seconds to use as the album thumbnail. + example: 300 + type: number + type: object + required: false + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/album" + description: The album was updated with a new thumbnail. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3429: The authenticated user can't edit the album." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such album, or user, or video exists." + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4016: Unexpected error while setting thumbnail." + security: + - oauth2: + - edit + summary: Set a video as the album thumbnail + tags: + - Albums\Album videos + "/users/{user_id}/appearances": + get: + operationId: get_appearances + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos in which a user appears + tags: + - Videos\Essentials + "/users/{user_id}/categories": + get: + operationId: get_category_subscriptions + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - name + type: string + responses: + "200": + content: + application/vnd.vimeo.category+json: + schema: + items: + $ref: "#/components/schemas/category" + type: array + description: The categories were returned. + "403": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: You can't view another user." + security: + - oauth2: + - private + summary: Get all the categories that a user follows + tags: + - Categories\Subscriptions + "/users/{user_id}/categories/{category}": + delete: + operationId: unsubscribe_from_category + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user was unsubscribed. + security: + - oauth2: + - interact + summary: Unsubscribe a user from a category + tags: + - Categories\Subscriptions + get: + operationId: check_if_user_subscribed_to_category + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: animation + type: string + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user is following the category. + security: + - oauth2: + - private + summary: Check if a user follows a category + tags: + - Categories\Subscriptions + put: + operationId: subscribe_to_category + parameters: + - description: The name of the category. + in: path + name: category + required: true + schema: + example: 0 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user was subscribed. + security: + - oauth2: + - interact + summary: Subscribe a user to a single category + tags: + - Categories\Subscriptions + "/users/{user_id}/channels": + get: + operationId: get_channel_subscriptions + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - moderated + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - followers + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + items: + $ref: "#/components/schemas/channel" + type: array + description: The channels were returned. + "304": + description: No channel has been followed since the given `If-Modified-Since` header. + summary: Get all the channels to which a user subscribes + tags: + - Channels\Essentials + "/users/{user_id}/channels/{channel_id}": + delete: + operationId: unsubscribe_from_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user is no longer a follower of the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + security: + - oauth2: + - interact + summary: Unsubscribe a user from a specific channel + tags: + - Channels\Subscriptions and subscribers + get: + operationId: check_if_user_subscribed_to_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user follows the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + summary: Check if a user follows a channel + tags: + - Channels\Subscriptions and subscribers + put: + operationId: subscribe_to_channel + parameters: + - description: The ID of the channel. + in: path + name: channel_id + required: true + schema: + example: 927 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user is now a follower of the channel. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such channel exists. + security: + - oauth2: + - interact + summary: Subscribe a user to a specific channel + tags: + - Channels\Subscriptions and subscribers + "/users/{user_id}/customlogos": + get: + operationId: get_custom_logos + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The custom logos were returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The user can't view this custom logo. + * The user can't view custom logos. + summary: Get all the custom logos that belong to a user + tags: + - Embed Presets\Custom Logos + post: + operationId: create_custom_logo + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was created. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * You can't upload pictures for another user's videos. + * The user can't add a custom logo. + security: + - oauth2: + - upload + summary: Add a custom logo + tags: + - Embed Presets\Custom Logos + "/users/{user_id}/customlogos/{logo_id}": + get: + operationId: get_custom_logo + parameters: + - description: The ID of the custom logo. + in: path + name: logo_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user can't view custom logos. + summary: Get a specific custom logo + tags: + - Embed Presets\Custom Logos + "/users/{user_id}/feed": + get: + operationId: get_feed + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: Necessary for proper pagination. You shouldn't provide this value yourself, and instead use the pagination links in the feed response. Please see our [pagination documentation](https://developer.vimeo.com/api/common-formats#using-the-pagination-parameter) for more information. + in: query + name: offset + required: false + schema: + example: "280" + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The feed type. + in: query + name: type + required: false + schema: + enum: + - appears + - category_featured + - channel + - facebook_feed + - following + - group + - likes + - ondemand_publish + - share + - tagged_with + - twitter_timeline + - uploads + type: string + responses: + "200": + content: + application/vnd.vimeo.activity+json: + schema: + items: + $ref: "#/components/schemas/activity-3-1" + type: array + description: The videos were returned. + security: + - oauth2: + - private + summary: Get all videos in a user's feed + tags: + - Users\Feed + "/users/{user_id}/followers": + get: + operationId: get_followers + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The user's followers were returned. + summary: Get all the followers of a user + tags: + - Users\Follows + "/users/{user_id}/following": + get: + operationId: get_user_following + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - online + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The followed users were returned. + summary: Get all the users that a user is following + tags: + - Users\Follows + post: + operationId: follow_users + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/json: + schema: + properties: + users: + description: An array of user URIs for the list of users to follow. + items: + type: string + type: array + required: + - users + type: object + required: true + responses: + "204": + description: The users were followed. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: The request body is empty. + * Error code 2205: The `users` array is invalid. + * Error code 2205: The list of users doesn't contain URIs. + * Error code 2900: A user in the list doesn't exist. + * Error code 2901: The list contains more than 100 users. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user access token is invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3417: The current user can't follow other users." + "429": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 9006: The current user is rate-limited from following other users." + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4005: An unexpected error occurred." + security: + - oauth2: + - interact + summary: Follow a list of users + tags: + - Users\Follows + "/users/{user_id}/following/{followUserId}": + delete: + operationId: unfollow_user + parameters: + - description: The ID of the following user. + in: path + name: followUserId + required: true + schema: + example: 3766357 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user was unfollowed. + security: + - oauth2: + - interact + summary: Unfollow a user + tags: + - Users\Follows + get: + operationId: check_if_user_is_following + parameters: + - description: The ID of the following user. + in: path + name: followUserId + required: true + schema: + example: 3766357 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The authenticated user follows the user in question. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user in question doesn't follow the authenticated user. + summary: Check if a user is following another user + tags: + - Users\Follows + put: + operationId: follow_user + parameters: + - description: The ID of the following user. + in: path + name: followUserId + required: true + schema: + example: 3766357 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user was followed. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't add followers. + security: + - oauth2: + - interact + summary: Follow a specific user + tags: + - Users\Follows + "/users/{user_id}/groups": + get: + operationId: get_user_groups + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - moderated + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - members + - videos + type: string + responses: + "200": + content: + application/vnd.vimeo.group+json: + schema: + items: + $ref: "#/components/schemas/group" + type: array + description: The groups were returned. + summary: Get all the groups that a user has joined + tags: + - Groups\Users + "/users/{user_id}/groups/{group_id}": + delete: + operationId: leave_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user left the group. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user owns the group. To remove this user, first apply a new group owner through PATCH. + security: + - oauth2: + - interact + summary: Remove a user from a group + tags: + - Groups\Subscription + get: + operationId: check_if_user_joined_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user has joined the group. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such group exists. + * The authenticated user isn't a member of this group. + summary: Check if a user has joined a group + tags: + - Groups\Users + put: + operationId: join_group + parameters: + - description: The ID of the group. + in: path + name: group_id + required: true + schema: + example: 1108 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The user joined the group. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user can't join groups. + * The group prohibits the authenticated user from joining, either because the group is not public or because the group's privacy setting is `members`. + security: + - oauth2: + - interact + summary: Add a user to a group + tags: + - Groups\Subscription + "/users/{user_id}/likes": + get: + operationId: get_likes + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos that a user has liked + tags: + - Likes\Essentials + "/users/{user_id}/likes/{video_id}": + delete: + operationId: unlike_video + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was unliked. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't like videos. + security: + - oauth2: + - interact + summary: Cause a user to unlike a video + tags: + - Likes\Essentials + get: + operationId: check_if_user_liked_video + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The user has liked the video. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The user hasn't liked the video. + summary: Check if a user has liked a video + tags: + - Likes\Essentials + put: + operationId: like_video + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was liked. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user owns the video. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't like videos. + security: + - oauth2: + - interact + summary: Cause a user to like a video + tags: + - Likes\Essentials + "/users/{user_id}/ondemand/pages": + get: + operationId: get_user_vods + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The type of On Demand pages to return. + in: query + name: filter + required: false + schema: + enum: + - film + - series + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - added + - alphabetical + - date + - modified_time + - name + - publish.time + - rating + type: string + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + items: + $ref: "#/components/schemas/on-demand-page" + type: array + description: The On Demand pages were returned. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such user exists. + summary: Get all the On Demand pages of a user + tags: + - On Demand\Essentials + post: + operationId: create_vod + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/json: + schema: + properties: + accepted_currencies: + description: | + An array of accepted currencies. + + Option descriptions: + * `AUD` - Australian Dollar + * `CAD` - Canadian Dollar + * `CHF` - Swiss Franc + * `DKK` - Danish Krone + * `EUR` - Euro + * `GBP` - British Pound + * `JPY` - Japanese Yen + * `KRW` - South Korean Won + * `NOK` - Norwegian Krone + * `PLN` - Polish Zloty + * `SEK` - Swedish Krona + * `USD` - US Dollar + enum: + - AUD + - CAD + - CHF + - DKK + - EUR + - GBP + - JPY + - KRW + - NOK + - PLN + - SEK + - USD + type: string + buy: + properties: + active: + description: Whether the Buy action is active. *Required if `rent.active` is false. + example: "true" + type: boolean + download: + description: Whether people who buy the video can download it. To use this field, `type` must be `film`. + example: "true" + type: boolean + price: + properties: + AUD: + description: The purchase price of this video in AUD. + example: 2.99 + type: number + CAD: + description: The purchase price of this video in CAD. + example: 2.99 + type: number + CHF: + description: The purchase price of this video in CHF. + example: 2.99 + type: number + DKK: + description: The purchase price of this video in DKK. + example: 2.99 + type: number + EUR: + description: The purchase price of this video in EUR. + example: 2.99 + type: number + GBP: + description: The purchase price of this video in GBP. + example: 2.99 + type: number + JPY: + description: The purchase price of this video in JPY. + example: 2.99 + type: number + KRW: + description: The purchase price of this video in KRW. + example: 2.99 + type: number + NOK: + description: The purchase price of this video in NOK. + example: 2.99 + type: number + PLN: + description: The purchase price of this video in PLN. + example: 2.99 + type: number + SEK: + description: The purchase price of this video in SEK. + example: 2.99 + type: number + USD: + description: The purchase price of this video in USD when `type` is `film`, or the purchase price of the entire collection in USD when `type` is `series`. + example: 2.99 + type: number + type: object + type: object + content_rating: + description: One or more ratings, either as a comma-separated list or as a JSON array depending on the request format. + enum: + - drugs + - language + - nudity + - safe + - unrated + - violence + type: string + description: + description: The description of the On Demand page. + example: DARBY FOREVER follows the fantasies of Darby, a shopgirl at "Bobbins & Notions". + type: string + domain_link: + description: The custom domain of the On Demand page. + example: https://example.com + type: string + episodes: + properties: + buy: + properties: + active: + description: Whether episodes can be bought. + example: "true" + type: boolean + download: + description: Whether people who buy the episode can download it. To use this field, `type` must be `series`. + example: "true" + type: boolean + price: + properties: + USD: + description: The purchase price per episode. *Required if `episodes.buy.active` is true. + example: 1.99 + type: number + type: object + type: object + rent: + properties: + active: + description: Whether episodes can be rented + example: "true" + type: boolean + period: + description: The period in which this episode can be rented for. + enum: + - 1 week + - 1 year + - 24 hour + - 3 month + - 30 day + - 48 hour + - 6 month + - 72 hour + type: string + price: + properties: + USD: + description: The default price to rent an episode. This field is applicable only when `type` is `series`. *Required if `episodes.rent.active` is true. + example: 0.99 + type: number + type: object + type: object + type: object + link: + description: The custom string to use in this On Demand page's Vimeo URL. + example: darbyforever + type: string + name: + description: The name of the On Demand page. + example: Darby Forever + type: string + rent: + properties: + active: + description: Whether the video can be rented. *Required if `buy.active` is false. + example: "true" + type: boolean + period: + description: The period in which this can be rented for. + enum: + - 1 week + - 1 year + - 24 hour + - 3 month + - 30 day + - 48 hour + - 6 month + - 72 hour + type: string + price: + properties: + AUD: + description: The rental price of this video in AUD. + example: 0.99 + type: number + CAD: + description: The rental price of this video in CAD. + example: 0.99 + type: number + CHF: + description: The rental price of this video in CHF. + example: 0.99 + type: number + DKK: + description: The rental price of this video in DKK. + example: 0.99 + type: number + EUR: + description: The rental price of this video in EUR. + example: 0.99 + type: number + GBP: + description: The rental price of this video in GBP. + example: 0.99 + type: number + JPY: + description: The rental price of this video in JPY. + example: 0.99 + type: number + KRW: + description: The rental price of this video in KRW. + example: 0.99 + type: number + NOK: + description: The rental price of this video in NOK. + example: 0.99 + type: number + PLN: + description: The rental price of this video in PLN. + example: 0.99 + type: number + SEK: + description: The rental price of this video in SEK. + example: 0.99 + type: number + USD: + description: The rental price of this video in USD when `type` is `film`, or the rental price of the entire collection in USD when `type` is `series`. + example: 0.99 + type: number + type: object + type: object + subscription: + properties: + monthly: + properties: + active: + description: Whether monthly subscription is active. *Required if `rent.active` and `buy.active` are false. + example: "true" + type: boolean + price: + properties: + USD: + description: The monthly subscription price in USD. *Required if `subscription.active` is true. + example: 9.99 + type: number + type: object + type: object + type: object + type: + description: The type of On Demand page. + enum: + - film + - series + type: string + required: + - content_rating + - description + - name + - type + type: object + required: true + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: The On Demand page was created. + summary: Create an On Demand page + tags: + - On Demand\Essentials + "/users/{user_id}/ondemand/purchases": + get: + operationId: check_if_vod_was_purchased + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/on-demand-page" + description: You have purchased the On Demand page. + "403": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The requested user isn't the same as the authenticated user. + "404": + content: + application/vnd.vimeo.ondemand.page+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such user or On Demand page exists. + security: + - oauth2: + - purchased + summary: Check if a user has made a purchase or rental from an On Demand page + tags: + - On Demand\Purchases and Rentals + "/users/{user_id}/pictures": + get: + operationId: get_pictures + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The pictures were returned. + summary: Get all the pictures that belong to a user + tags: + - Users\Pictures + post: + operationId: create_picture + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The user picture was created. + security: + - oauth2: + - upload + summary: Add a user picture + tags: + - Users\Pictures + "/users/{user_id}/pictures/{portraitset_id}": + delete: + operationId: delete_picture + parameters: + - description: The ID of the picture. + in: path + name: portraitset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "204": + description: The picture was deleted. + security: + - oauth2: + - delete + summary: Delete a user picture + tags: + - Users\Pictures + get: + operationId: get_picture + parameters: + - description: The ID of the picture. + in: path + name: portraitset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The picture was returned. + summary: Get a specific user picture + tags: + - Users\Pictures + patch: + operationId: edit_picture + parameters: + - description: The ID of the picture. + in: path + name: portraitset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether the picture is the user's active portrait. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The picture was edited. + security: + - oauth2: + - edit + summary: Edit a user picture + tags: + - Users\Pictures + "/users/{user_id}/portfolios": + get: + operationId: get_portfolios + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.portfolio+json: + schema: + items: + $ref: "#/components/schemas/portfolio" + type: array + description: The portfolios were returned. + summary: Get all the portfolios that belong to a user + tags: + - Portfolios\Essentials + "/users/{user_id}/portfolios/{portfolio_id}": + get: + operationId: get_portfolio + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.portfolio+json: + schema: + $ref: "#/components/schemas/portfolio" + description: The portfolio was returned. + summary: Get a specific portfolio + tags: + - Portfolios\Essentials + "/users/{user_id}/portfolios/{portfolio_id}/videos": + get: + operationId: get_portfolio_videos + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page that contains the video URI. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: | + The way to sort the results. + + Option descriptions: + * `default` - This will sort to the default sort set on the portfolio. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - default + - likes + - manual + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos in a portfolio + tags: + - Portfolios\Videos + "/users/{user_id}/portfolios/{portfolio_id}/videos/{video_id}": + delete: + operationId: delete_video_from_portfolio + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The portfolio wasn't found, or the video wasn't found. + security: + - oauth2: + - edit + summary: Remove a video from a portfolio + tags: + - Portfolios\Videos + get: + operationId: get_portfolio_video + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + summary: Get a specific video in a portfolio + tags: + - Portfolios\Videos + put: + operationId: add_video_to_portfolio + parameters: + - description: The ID of the portfolio. + in: path + name: portfolio_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The portfolio wasn't found, or the video wasn't found. + security: + - oauth2: + - edit + summary: Add a video to a portfolio + tags: + - Portfolios\Videos + "/users/{user_id}/presets": + get: + operationId: get_embed_presets + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.preset+json: + schema: + items: + $ref: "#/components/schemas/presets" + type: array + description: The embed presets were returned. + summary: Get all the embed presets that a user has created + tags: + - Embed Presets\Essentials + "/users/{user_id}/presets/{preset_id}": + get: + operationId: get_embed_preset + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/presets" + description: The embed preset was returned. + summary: Get a specific embed preset + tags: + - Embed Presets\Essentials + patch: + operationId: edit_embed_preset + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.preset+json: + schema: + properties: + outro: + description: Disable the outro. + enum: + - nothing + type: string + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/presets" + description: The embed preset was edited. + "400": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The outro type is invalid. + "404": + content: + application/vnd.vimeo.preset+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The preset doesn't exist. + * The authenticated user doesn't own the preset. + summary: Edit an embed preset + tags: + - Embed Presets\Essentials + "/users/{user_id}/presets/{preset_id}/videos": + get: + operationId: get_embed_preset_videos + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + summary: Get all the videos that have been added to an embed preset + tags: + - Embed Presets\Videos + "/users/{user_id}/projects": + get: + description: This method gets all the projects that belong to the specified user. + operationId: get_projects + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - date + - default + - modified_time + - name + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/project" + type: array + description: The projects were returned. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + security: + - oauth2: + - private + summary: Get all the projects that belong to a user + tags: + - Projects\Essentials + post: + description: This method creates a new project for the specified user. + operationId: create_project + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/json: + schema: + properties: + name: + description: The name of the project. + example: Rough cuts + type: string + required: + - name + type: object + required: true + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/project" + description: The project was created. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: The input is empty. + * Error code 2204: The input is invalid. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't create projects." + security: + - oauth2: + - create + summary: Create a project + tags: + - Projects\Essentials + "/users/{user_id}/projects/{project_id}": + delete: + description: This method deletes a project and optionally also the videos that it contains. + operationId: delete_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: Whether to delete all the videos in the project along with the project itself. + in: query + name: should_delete_clips + required: false + schema: + example: "true" + type: boolean + responses: + "204": + description: The project was deleted. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't delete the project." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - delete + summary: Delete a project + tags: + - Projects\Essentials + get: + description: This method gets a single project that belongs to the specified user. + operationId: get_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/project" + description: The project was returned. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - private + summary: Get a specific project + tags: + - Projects\Essentials + patch: + description: This method edits an existing project. + operationId: edit_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/json: + schema: + properties: + name: + description: The name of the project. + example: Rough cuts + type: string + required: + - name + type: object + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/project" + description: The project was edited. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2204: The input is invalid. + * Error code 2205: The input is empty. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3200: The authenticated user can't edit the project." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - edit + summary: Edit a project + tags: + - Projects\Essentials + "/users/{user_id}/projects/{project_id}/videos": + delete: + description: This method removed multiple videos from the specified project. + operationId: remove_videos_from_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: Whether to delete the videos when removing them from the project. + in: query + name: should_delete_clips + required: false + schema: + example: "false" + type: boolean + - description: A comma-separated list of the video URIs to remove. + in: query + name: uris + required: true + schema: + example: /videos/258684937,/videos/273576296 + type: string + responses: + "204": + description: The videos were removed. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: The input is invalid." + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - interact + summary: Remove a list of videos from a project + tags: + - Projects\Videos + get: + description: This method gets all the videos that belong to the specified project. + operationId: get_project_videos + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + - default + - duration + - last_user_action_event_date + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project exists." + security: + - oauth2: + - private + summary: Get all the videos in a project + tags: + - Projects\Videos + put: + description: This method adds multiple videos to the specified project. + operationId: add_videos_to_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: A comma-separated list of video URIs to add. + in: query + name: uris + required: true + schema: + example: /videos/258684937,/videos/273576296 + type: string + responses: + "204": + description: The videos were added. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: The input is invalid." + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such project or video exists." + security: + - oauth2: + - interact + summary: Add a list of videos to a project + tags: + - Projects\Videos + "/users/{user_id}/projects/{project_id}/videos/{video_id}": + delete: + description: This method removes a single video from the specified project. + operationId: remove_video_from_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was removed. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2204: The input is invalid." + "401": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8000: The user credentials are invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such video exists in the project." + security: + - oauth2: + - delete + summary: Remove a specific video from a project + tags: + - Projects\Videos + put: + description: This method adds a single video to the specified project. + operationId: add_video_to_project + parameters: + - description: The ID of the project. + in: path + name: project_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 5000: No such user, project, or video exists." + security: + - oauth2: + - interact + summary: Add a specific video to a project + tags: + - Projects\Videos + "/users/{user_id}/uploads/{upload}": + delete: + operationId: complete_streaming_upload + parameters: + - description: The ID of the upload attempt. + in: path + name: upload + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The crypto signature of the completed upload. + in: query + name: signature + required: true + schema: + example: cd89a20adde7a608f3331e71c37bdfa087bacbf3 + type: string + - description: The ID of the uploaded file. + in: query + name: video_file_id + required: true + schema: + example: 1234 + type: number + responses: + "201": + description: The streaming upload is complete. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2502: The format of the video file is invalid." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 5006: The video file doesn't exist. + * Error code 5007: The signature doesn't exist. + * Error code 8400: The signature is invalid. + "500": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4011: The upload server returns an HTTP status code other than 200." + security: + - oauth2: + - upload + summary: Complete a user's streaming upload + tags: + - Videos\Upload + get: + operationId: get_upload_attempt + parameters: + - description: The ID of the upload attempt. + in: path + name: upload + required: true + schema: + example: 12345 + type: number + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + responses: + "200": + content: + application/vnd.vimeo.uploadattempt+json: + schema: + $ref: "#/components/schemas/upload-attempt" + description: The upload attempt was returned. + security: + - oauth2: + - upload + summary: Get a user's upload attempt + tags: + - Videos\Upload + "/users/{user_id}/videos": + get: + operationId: get_videos + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The page that contains the video URI. Only available when not paired with `query`. + in: query + name: containing_uri + required: false + schema: + example: /videos/258684937 + type: string + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - app_only + - embeddable + - featured + - playable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: Whether to filter by all playable videos or by all videos that are not playable. + in: query + name: filter_playable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - default + - duration + - last_user_action_event_date + - likes + - modified_time + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "304": + description: This user hasn't created any videos since the given `If-Modified-Since` header. + summary: Get all the videos that a user has uploaded + tags: + - Videos\Essentials + post: + description: Begin the video upload process. For more information, see our [upload documentation](https://developer.vimeo.com/api/upload/videos). + operationId: upload_video + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + requestBody: + content: + application/vnd.vimeo.video+json: + schema: + properties: + content_rating: + description: A list of values describing the content in this video. Find the full list in the [/contentratings](https://developer.vimeo.com/api/endpoints/videos#GET/contentratings) endpoint. + items: + type: string + type: array + description: + description: The description of the video. + example: A celebration of 10 years of Staff Picks. + type: string + embed: + properties: + buttons: + properties: + embed: + description: Show or hide the Embed button. + example: "true" + type: boolean + fullscreen: + description: Show or hide the Fullscreen button. + example: "true" + type: boolean + hd: + description: Show or hide the HD button. + example: "true" + type: boolean + like: + description: Show or hide the Like button. + example: "true" + type: boolean + scaling: + description: Show or hide the Scaling button (shown only in Fullscreen mode). + example: "true" + type: boolean + share: + description: Show or hide the Share button. + example: "true" + type: boolean + watchlater: + description: Show or hide the Watch Later button. + example: "true" + type: boolean + type: object + color: + description: The main color of the embed player. + example: "#1ab7ea" + type: string + logos: + properties: + custom: + properties: + active: + description: Show or hide your custom logo. + example: "true" + type: boolean + link: + description: The URL that loads when the user clicks your custom logo. + example: https://example.com + type: string + sticky: + description: Whether always to show the custom logo or to hide it after time with the rest of the UI. + example: "true" + type: boolean + type: object + vimeo: + description: Show or hide the Vimeo logo. + example: "true" + type: boolean + type: object + playbar: + description: Show or hide the playbar. + example: "true" + type: boolean + title: + properties: + name: + description: Show or hide the video title, or enable the user to determine whether the video title appears. + enum: + - hide + - show + - user + type: string + owner: + description: Show or hide the owner information, or enable the user to determine whether the owner information appears. + enum: + - hide + - show + - user + type: string + portrait: + description: Show or hide the owner portrait, or enable the user to determine whether the owner portrait appears. + enum: + - hide + - show + - user + type: string + type: object + volume: + description: Show or hide the volume selector. + example: "true" + type: boolean + type: object + license: + description: The Creative Commons license. + enum: + - by + - by-nc + - by-nc-nd + - by-nc-sa + - by-nd + - by-sa + - cc0 + type: string + locale: + description: The video's default language. For a full list of valid languages, use the [/languages?filter=texttracks](https://developer.vimeo.com/api/endpoints/videos#GET/languages) endpoint. + example: en_US + type: string + name: + description: The title of the video. + example: Celebrating 10 Years of Staff Picks + type: string + password: + description: The password. When you set `privacy.view` to `password`, you must provide the password as an additional parameter. + example: hunter1 + type: string + privacy: + properties: + add: + description: Whether a user can add the video to an album, channel, or group. + example: "true" + type: boolean + comments: + description: The privacy level required to comment on the video. + enum: + - anybody + - contacts + - nobody + type: string + download: + description: Whether a user can download the video. Not available to users with a Basic membership + example: "true" + type: boolean + embed: + description: The video's embed settings. The `whitelist` value enables you to define all valid embed domains. See our [documentation](https://developer.vimeo.com/api/endpoints/videos#/{video_id}/privacy/domains) for details on adding and removing domains. + enum: + - private + - public + - whitelist + type: string + view: + description: The video's privacy setting. When privacy is `users`, `application/json` is the only valid content type. Basic users can't set privacy to `unlisted`. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + type: string + type: object + ratings: + properties: + mpaa: + properties: + reason: + description: | + The reason for the video's MPAA rating. + + Option descriptions: + * `at` - Adult themes + * `bn` - Brief nudity + * `n` - Nudity + * `sl` - Strong language + * `ss` - Sexual situations + * `v` - Violence + enum: + - at + - bn + - n + - sl + - ss + - v + type: string + type: object + tv: + properties: + reason: + description: | + The reason for the video's TV rating. + + Option descriptions: + * `d` - Suggestive dialogue + * `fv` - Fantasy violence + * `l` - Language + * `ss` - Sexual situations + * `v` - Violence + enum: + - d + - fv + - l + - ss + - v + type: string + type: object + type: object + review_page: + properties: + active: + description: Enable or disable video review. + example: "true" + type: boolean + type: object + spatial: + properties: + director_timeline: + description: The 360 director timeline. + items: + properties: + pitch: + description: The timeline pitch. This value must be between -90 and 90. + example: 70 + type: number + roll: + description: The timeline roll. + type: number + time_code: + description: The 360 director timeline time code. + example: 5 + type: number + yaw: + description: The timeline yaw. This value must be between 0 and 360. + example: 125 + type: number + required: + - pitch + - time_code + - yaw + type: object + type: array + field_of_view: + description: "The 360 field of view: default 50, minimum 30, maximum 90." + example: 50 + type: number + projection: + description: The 360 spatial projection. + enum: + - cubical + - cylindrical + - dome + - equirectangular + - pyramid + type: string + stereo_format: + description: The 360 spatial stereo format. + enum: + - left-right + - mono + - top-bottom + type: string + type: object + upload: + properties: + approach: + description: The upload approach. + enum: + - post + - pull + - streaming + - tus + type: string + link: + description: The public URL at which the video is hosted. The URL must be valid for at least 24 hours. Use this parameter when `approach` is `pull`. + example: https://example.com/video.mp4 + type: string + redirect_url: + description: The app's redirect URL. Use this parameter when `approach` is `post`. + example: https://example.com + type: string + size: + description: The size in bytes of the video to upload. + example: "13623861" + type: string + required: + - approach + type: object + required: + - upload + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The upload procedure has begun. + "400": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2205: The body of the request isn't formatted properly. + * Error code 2204: The request contains invalid parameters. + * Error code 2204: The request contains invalid body parameters. + * Error code 2230: The upload type is invalid. + * Error code 3116: If a `type` payload parameter was supplied instead of `upload.approach`. + "401": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8002: No user is associated with the authentication token." + "403": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 4102: The user's allotted quota has been reached. + * Error code 4101: The user's maximum disk space has been reached. + "500": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 4003: There is a problem initiating the upload." + summary: Upload a video + tags: + - Videos\Upload + "/users/{user_id}/videos/{video_id}": + get: + operationId: check_if_user_owns_video + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The user owns the video. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the video. + summary: Check if a user owns a video + tags: + - Videos\Essentials + "/users/{user_id}/watchlater": + get: + operationId: get_watch_later_queue + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - embeddable + type: string + - description: Whether to filter the results by embeddable videos (`true`) or non-embeddable videos (`false`). Required only if **filter** is `embeddable`. + in: query + name: filter_embeddable + required: false + schema: + example: "true" + type: boolean + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The videos were returned. + "304": + description: The user hasn't added any videos to their Watch Later queue since the given `If-Modified-Since` header. + security: + - oauth2: + - private + summary: Get all the videos in a user's Watch Later queue + tags: + - Watch Later Queue\Essentials + "/users/{user_id}/watchlater/{video_id}": + delete: + operationId: delete_video_from_watch_later + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted. + security: + - oauth2: + - interact + summary: Remove a video from a user's Watch Later queue + tags: + - Watch Later Queue\Essentials + get: + operationId: check_watch_later_queue + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video appears in the user's Watch Later queue. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video doesn't appear in the user's Watch Later queue. + security: + - oauth2: + - private + summary: Check if a user has added a specific video to their Watch Later queue + tags: + - Watch Later Queue\Essentials + put: + operationId: add_video_to_watch_later + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was added. + security: + - oauth2: + - interact + summary: Add a video to a user's Watch Later queue + tags: + - Watch Later Queue\Essentials + /videos: + get: + operationId: search_videos + parameters: + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The attribute by which to filter the results. `CC` and related filters target videos with the corresponding Creative Commons licenses. For more information, see our [Creative Commons](https://vimeo.com/creativecommons) page. + in: query + name: filter + required: false + schema: + enum: + - CC + - CC-BY + - CC-BY-NC + - CC-BY-NC-ND + - CC-BY-NC-SA + - CC-BY-ND + - CC-BY-SA + - CC0 + - categories + - duration + - in-progress + - minimum_likes + - trending + - upload_date + type: string + - description: A comma-separated list of video URLs to find. + in: query + name: links + required: false + schema: + example: https://vimeo.com/122375452,https://vimeo.com/273576296 + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: Search query. + in: query + name: query + required: true + schema: + example: staff picks + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - comments + - date + - duration + - likes + - plays + - relevant + type: string + - description: The comma-separated list of videos to find. + in: query + name: uris + required: false + schema: + example: /videos/122375452,/videos/273576296 + type: string + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The search results were returned. + "400": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2101: Either the `uris` or `links` parameter has filtering or sorting arguments. + * Error code 2204: There is a problem with the batch request. + "503": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * Search is disabled. + * Error code 7300: There was an internal search error. + summary: Search for videos + tags: + - Videos\Essentials + "/videos/{video_id}": + delete: + operationId: delete_video + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the video and can't delete it. + security: + - oauth2: + - delete + summary: Delete a video + tags: + - Videos\Essentials + get: + operationId: get_video + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was returned. + "404": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video exists. + summary: Get a specific video + tags: + - Videos\Essentials + patch: + operationId: edit_video + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.video+json: + schema: + properties: + content_rating: + description: A list of values describing the content in this video. You can find the full list in the [`/contentratings`](https://developer.vimeo.com/api/endpoints/videos#GET/contentratings) endpoint. + items: + type: string + type: array + description: + description: The new description of the video. + example: A celebration of 10 years of Staff Picks. + type: string + embed: + properties: + buttons: + properties: + embed: + description: Show or hide the Embed button. + example: "true" + type: boolean + fullscreen: + description: Show or hide the Fullscreen button. + example: "true" + type: boolean + hd: + description: Show or hide the HD button. + example: "true" + type: boolean + like: + description: Show or hide the Like button. + example: "true" + type: boolean + scaling: + description: Show or hide the Scaling button (shown only in Fullscreen mode). + example: "true" + type: boolean + share: + description: Show or hide the Share button. + example: "true" + type: boolean + watchlater: + description: Show or hide the Watch Later button. + example: "true" + type: boolean + type: object + color: + description: The main color of the embed player. + example: "#1ab7ea" + type: string + logos: + properties: + custom: + properties: + active: + description: Show or hide your custom logo. + example: "true" + type: boolean + link: + description: The URL that loads when the user clicks your custom logo. + example: https://example.com + type: string + sticky: + description: Whether always to show the custom logo or to hide it after time with the rest of the UI. + example: "true" + type: boolean + type: object + vimeo: + description: Show or hide the Vimeo logo. + example: "true" + type: boolean + type: object + playbar: + description: Show or hide the playbar. + example: "true" + type: boolean + title: + properties: + name: + description: Show or hide the video title, or enable the user to determine whether the video title appears. + enum: + - hide + - show + - user + type: string + owner: + description: Show or hide the owner information, or enable the user to determine whether the owner information appears. + enum: + - hide + - show + - user + type: string + portrait: + description: Show or hide the owner portrait, or enable the user to determine whether the owner portrait appears. + enum: + - hide + - show + - user + type: string + type: object + volume: + description: Show or hide the volume selector. + example: "true" + type: boolean + type: object + license: + description: The Creative Commons license. + enum: + - by + - by-nc + - by-nc-nd + - by-nc-sa + - by-nd + - by-sa + - cc0 + type: string + locale: + description: The video's default language. For a full list of valid languages, use the [/languages?filter=texttracks](https://developer.vimeo.com/api/endpoints/videos#GET/languages) endpoint. + example: en-US + type: string + name: + description: The new title for the video. + example: Celebrating 10 Years of Staff Picks + type: string + password: + description: The password. When you set `privacy.view` to `password`, you must provide the password as an additional parameter. + example: hunter1 + type: string + privacy: + properties: + add: + description: Whether a user can add the video to an album, channel, or group. + example: "true" + type: boolean + comments: + description: The privacy level required to comment on the video. + enum: + - anybody + - contacts + - nobody + type: string + download: + description: Whether a user can download the video. Not available to users with a Basic membership. + example: "true" + type: boolean + embed: + description: The video's new embed settings. The `whitelist` value enables you to define all valid embed domains. See our [documentation](https://developer.vimeo.com/api/endpoints/videos#/{video_id}/privacy/domains) for details on adding and removing domains. + enum: + - private + - public + - whitelist + type: string + view: + description: The video's new privacy setting. When privacy is `users`, `application/json` is the only valid content type. Basic users can't set privacy to `unlisted`. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + type: string + type: object + ratings: + properties: + mpaa: + properties: + reason: + description: | + The reason for the video's MPAA rating. + + Option descriptions: + * `at` - Adult themes + * `bn` - Brief nudity + * `n` - Nudity + * `sl` - Strong language + * `ss` - Sexual situations + * `v` - Violence + enum: + - at + - bn + - n + - sl + - ss + - v + type: string + type: object + tv: + properties: + reason: + description: | + The reason for the video's TV rating. + + Option descriptions: + * `d` - Suggestive dialogue + * `fv` - Fantasy violence + * `l` - Language + * `ss` - Sexual situations + * `v` - Violence + enum: + - d + - fv + - l + - ss + - v + type: string + type: object + type: object + review_page: + properties: + active: + description: Enable or disable video review. + example: "true" + type: boolean + type: object + spatial: + properties: + director_timeline: + description: The 360 director timeline. + items: + properties: + pitch: + description: The timeline pitch. This value must be between -90 and 90. + example: 70 + type: number + roll: + description: The timeline roll. + type: number + time_code: + description: The 360 director timeline time code. + example: 5 + type: number + yaw: + description: The timeline yaw. This value must be between 0 and 360. + example: 125 + type: number + required: + - pitch + - time_code + - yaw + type: object + type: array + field_of_view: + description: "The 360 field of view: default 50, minimum 30, maximum 90." + example: 50 + type: number + projection: + description: The 360 spatial projection. + enum: + - cubical + - cylindrical + - dome + - equirectangular + - pyramid + type: string + stereo_format: + description: The 360 spatial stereo format. + enum: + - left-right + - mono + - top-bottom + type: string + type: object + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/video" + description: The video was edited. + "400": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "403": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user doesn't own the video. + * The `privacy` field is `disable` and the authenticated user can't set extra embed options. + * The `privacy` field is `contacts` and the authenticated user can't follow creators. + * The authenticated user has an opted-out PRO account and `privacy.view` is `users`, `password`, `nobody`, or `public`. + security: + - oauth2: + - edit + summary: Edit a video + tags: + - Videos\Essentials + "/videos/{video_id}/available_channels": + get: + operationId: get_available_video_channels + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.channel+json: + schema: + items: + $ref: "#/components/schemas/channel" + type: array + description: The channels were returned. + "403": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't add or remove this video from any channel. + "404": + content: + application/vnd.vimeo.channel+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user can't moderate channels. + summary: Get all the channels to which a user can add or remove a specific video + tags: + - Channels\Videos + "/videos/{video_id}/categories": + get: + operationId: get_video_categories + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.category+json: + schema: + items: + $ref: "#/components/schemas/category" + type: array + description: The categories were returned. + "404": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video exists. + summary: Get all the categories to which a video belongs + tags: + - Categories\Videos + put: + description: |- + With this method, you can suggest up to two categories and one subcategory for a video. Vimeo makes the final determination about whether the video + belongs in these categories. + operationId: suggest_video_category + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.category+json: + schema: + properties: + category: + description: The array of the names of the categories that you're suggesting. + items: + type: string + type: array + required: + - category + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/category" + description: The categories were suggested. + "403": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: You don't own this video. + "404": + content: + application/vnd.vimeo.category+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video exists, or no such category exists. + security: + - oauth2: + - edit + summary: Suggest categories for a video + tags: + - Categories\Videos + "/videos/{video_id}/comments": + get: + operationId: get_comments + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.comment+json: + schema: + items: + $ref: "#/components/schemas/comment" + type: array + description: The comments were returned. + summary: Get all the comments on a video + tags: + - Videos\Comments + post: + operationId: create_comment + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.comment+json: + schema: + properties: + text: + description: The text of the comment. + example: I love this! + type: string + required: + - text + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/comment" + description: The comment was added. + "400": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2207: The comment text is missing." + "401": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 8003: The user credentials are invalid." + "403": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 3413: Comments are disabled for this video. + * Error code 3411: The authenticated user is unverified. + * Error code 3412: The authenticated user can't comment. + * Error code 3301: The comment was flagged as spam. + security: + - oauth2: + - interact + summary: Add a comment to a video + tags: + - Videos\Comments + "/videos/{video_id}/comments/{comment_id}": + delete: + operationId: delete_comment + parameters: + - description: The ID of the comment. + in: path + name: comment_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The comment was deleted. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3415: The authenticated user didn't write this comment and can't delete it." + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such video or comment exists. + * Error code 5000: The deleted comment still exists. + security: + - oauth2: + - delete + summary: Delete a video comment + tags: + - Videos\Comments + get: + operationId: get_comment + parameters: + - description: The ID of the comment. + in: path + name: comment_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/comment" + description: The comment was returned. + "404": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or comment exists. + summary: Get a specific video comment + tags: + - Videos\Comments + patch: + operationId: edit_comment + parameters: + - description: The ID of the comment. + in: path + name: comment_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.comment+json: + schema: + properties: + text: + description: The next text of the comment. + example: I love this! + type: string + required: + - text + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/comment" + description: The comment was edited. + "400": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2207: The comment text is missing." + "403": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 3411: The authenticated user is unverified. + * Error code 3412: The authenticated user can't post comments. + * Error code 3414: The authenticated user didn't write the comment and can't edit it. + * Error code 3301: The supplied comment was flagged as spam. + security: + - oauth2: + - edit + summary: Edit a video comment + tags: + - Videos\Comments + "/videos/{video_id}/comments/{comment_id}/replies": + get: + operationId: get_comment_replies + parameters: + - description: The ID of the comment. + in: path + name: comment_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.comment+json: + schema: + items: + $ref: "#/components/schemas/comment" + type: array + description: The replies were returned. + "404": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or comment exists. + summary: Get all the replies to a video comment + tags: + - Videos\Comments + post: + operationId: create_comment_reply + parameters: + - description: The ID of the comment. + in: path + name: comment_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.comment+json: + schema: + properties: + text: + description: The reply to the comment. + example: I love this! + type: string + required: + - text + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/comment" + description: The reply was added. + "400": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 2207: The comment text is missing." + "403": + content: + application/vnd.vimeo.comment+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 3413: Comments are disabled on this video. + * Error code 3411: The authenticated user is unverified. + * Error code 3412: The authenticated user can't comment. + * Error code 3301: The comment was flagged as spam. + security: + - oauth2: + - interact + summary: Add a reply to a video comment + tags: + - Videos\Comments + "/videos/{video_id}/credits": + get: + operationId: get_video_credits + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The search query to use to filter the results. + in: query + name: query + required: false + schema: + example: Stop motion + type: string + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.credit+json: + schema: + items: + $ref: "#/components/schemas/credit" + type: array + description: The users were returned. + summary: Get all the credited users in a video + tags: + - Videos\Credits + post: + operationId: add_video_credit + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.credit+json: + schema: + properties: + email: + description: The email address of the credited person. + example: user@example.com + type: string + name: + description: The name of the credited person. + example: Sam Doe + type: string + role: + description: The role of the credited person. + example: Producer + type: string + user_uri: + description: The URI of the Vimeo user who should be given credit in this video. + example: /users/152184 + type: string + required: + - email + - name + - role + - user_uri + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/credit" + description: The credit was added. + "400": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The credit was added. + * A parameter is invalid. + * The authenticated user has an unverified email address. + * There is a user block between the video owner and the person receiving credit. + "403": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user doesn't own the video. + summary: Credit a user in a video + tags: + - Videos\Credits + "/videos/{video_id}/credits/{credit_id}": + delete: + operationId: delete_video_credit + parameters: + - description: The ID of the credit. + in: path + name: credit_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The credit was deleted. + "400": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The authenticated user is neither the creator of the credit nor the credited user. + security: + - oauth2: + - edit + summary: Delete a credit for a user in a video + tags: + - Videos\Credits + get: + operationId: get_video_credit + parameters: + - description: The ID of the credit. + in: path + name: credit_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/credit" + description: The credit was returned. + "404": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or credit exists. + summary: Get a specific credited user in a video + tags: + - Videos\Credits + patch: + operationId: edit_video_credit + parameters: + - description: The ID of the credit. + in: path + name: credit_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.credit+json: + schema: + properties: + name: + description: The name of the person being credited. + example: Sam Doe + type: string + role: + description: The role of the person being credited. + example: Producer + type: string + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/credit" + description: The credit was edited. + "400": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: A parameter is invalid. + "404": + content: + application/vnd.vimeo.credit+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or credit exists. + security: + - oauth2: + - edit + summary: Edit a credit for a user in a video + tags: + - Videos\Credits + "/videos/{video_id}/likes": + get: + operationId: get_video_likes + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The sort direction of the results. + in: query + name: direction + required: false + schema: + enum: + - asc + - desc + example: asc + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + - description: The way to sort the results. + in: query + name: sort + required: false + schema: + enum: + - alphabetical + - date + type: string + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users were returned. + summary: Get all the users who have liked a video + tags: + - Likes\Essentials + "/videos/{video_id}/pictures": + get: + operationId: get_video_thumbnails + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + items: + $ref: "#/components/schemas/picture" + type: array + description: The thumbnails were returned. + summary: Get all the thumbnails of a video + tags: + - Videos\Thumbnails + post: + operationId: create_video_thumbnail + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether the image created by the `time` field should be the default thumbnail for the video. + example: "true" + type: boolean + time: + description: Creates an image of the video from the given time offset. + example: 300 + type: number + type: object + required: false + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The thumbnail was created. + security: + - oauth2: + - upload + summary: Add a video thumbnail + tags: + - Videos\Thumbnails + "/videos/{video_id}/pictures/{picture_id}": + delete: + operationId: delete_video_thumbnail + parameters: + - description: The ID of the picture. + in: path + name: picture_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The thumbnail was deleted. + security: + - oauth2: + - edit + summary: Delete a video thumbnail + tags: + - Videos\Thumbnails + get: + operationId: get_video_thumbnail + parameters: + - description: The ID of the picture. + in: path + name: picture_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The thumbnail was returned. + summary: Get a video thumbnail + tags: + - Videos\Thumbnails + patch: + operationId: edit_video_thumbnail + parameters: + - description: The ID of the picture. + in: path + name: picture_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.picture+json: + schema: + properties: + active: + description: Whether this thumbnail is the default. + example: "true" + type: boolean + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The thumbnail was edited. + security: + - oauth2: + - edit + summary: Edit a video thumbnail + tags: + - Videos\Thumbnails + "/videos/{video_id}/presets/{preset_id}": + delete: + operationId: delete_video_embed_preset + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The embed preset was unassigned. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or embed preset exists. + security: + - oauth2: + - edit + summary: Remove an embed preset from a video + tags: + - Embed Presets\Videos + get: + operationId: get_video_embed_preset + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The embed presets exists. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video or embed preset exists. + summary: Check if an embed preset has been added to a video + tags: + - Embed Presets\Videos + put: + operationId: add_video_embed_preset + parameters: + - description: The ID of the preset. + in: path + name: preset_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The embed preset was assigned. + security: + - oauth2: + - edit + summary: Add an embed preset to a video + tags: + - Embed Presets\Videos + "/videos/{video_id}/privacy/domains": + get: + operationId: get_video_privacy_domains + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.domain+json: + schema: + items: + $ref: "#/components/schemas/domain" + type: array + description: The domains were returned. + "403": + content: + application/vnd.vimeo.domain+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: There are no domains on which the video can be embedded. + summary: Get all the domains on which a video can be embedded + tags: + - Videos\Embed Privacy + "/videos/{video_id}/privacy/domains/{domain}": + delete: + operationId: delete_video_privacy_domain + parameters: + - description: The domain name. + in: path + name: domain + required: true + schema: + example: example.com + type: string + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video was disallowed from being embedded on the domain. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video isn't set to a user-defined access list. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such domain exists. + security: + - oauth2: + - edit + summary: Restrict a video from being embedded on a domain + tags: + - Videos\Embed Privacy + put: + description: If domain privacy is enabled for this video, this method permits the video to be embedded on the specified domain. + operationId: add_video_privacy_domain + parameters: + - description: The domain name. + in: path + name: domain + required: true + schema: + example: example.com + type: string + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The video is now embeddable on the domain. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video doesn't have a user-defined access list. + security: + - oauth2: + - edit + summary: Permit a video to be embedded on a domain + tags: + - Videos\Embed Privacy + "/videos/{video_id}/privacy/users": + get: + operationId: get_video_privacy_users + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users were returned. + "400": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No users can view the private video. + summary: Get all the users who can view a user's private videos by default + tags: + - Videos\Viewing Privacy + put: + description: |- + The body of this request should follow our + [batch request format](https://developer.vimeo.com/api/common-formats#batch-requests). Each object must contain + a single `URI` field, and the value of this field must be the URI of the user who can view this video. + operationId: add_video_privacy_users + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + items: + $ref: "#/components/schemas/user" + type: array + description: The users can now view the private video. + security: + - oauth2: + - edit + summary: Permit a list of users to view a private video + tags: + - Videos\Viewing Privacy + "/videos/{video_id}/privacy/users/{user_id}": + delete: + operationId: delete_video_privacy_user + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The user was disallowed from viewing the private video. + "403": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video isn't set to a user-defined access list. + "404": + content: + application/json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such user exists. + security: + - oauth2: + - edit + summary: Restrict a user from viewing a private video + tags: + - Videos\Viewing Privacy + put: + operationId: add_video_privacy_user + parameters: + - description: The ID of the user. + in: path + name: user_id + required: true + schema: + example: 152184 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/user" + description: The user can now view the private video. + "204": + description: The user can already view this private video. + "403": + content: + application/vnd.vimeo.user+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The video doesn't have a user-defined access list. + security: + - oauth2: + - edit + summary: Permit a specific user to view a private video + tags: + - Videos\Viewing Privacy + "/videos/{video_id}/tags": + get: + operationId: get_video_tags + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.tag+json: + schema: + items: + $ref: "#/components/schemas/tag" + type: array + description: The tags were returned. + summary: Get all the tags of a video + tags: + - Videos\Tags + put: + operationId: add_video_tags + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.tag+json: + schema: + properties: + name: + description: The name of the tag to apply. See our documentation on [batch requests](https://developer.vimeo.com/api/common-formats#batch-requests) for more information. + example: awesome + type: string + page: + description: The page number of the results to show. + example: 1 + type: number + per_page: + description: The number of items to show on each page of results, up to a maximum of 100. + example: 10 + type: number + required: + - name + type: object + required: true + responses: + "200": + content: + application/vnd.vimeo.tag+json: + schema: + items: + $ref: "#/components/schemas/tag" + type: array + description: The tags that were added. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The request body wasn't supplied. + * A parameter is invalid. + * The request body isn't a JSON-encoded list of tags. + "403": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user can't add tags to a video. + * The number of tags would exceed 20. + security: + - oauth2: + - edit + summary: Add a list of tags to a video + tags: + - Videos\Tags + "/videos/{video_id}/tags/{word}": + delete: + operationId: delete_video_tag + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The tag word. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "204": + description: The tag was deleted. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * A parameter is invalid. + * The tag is invalid. + security: + - oauth2: + - edit + summary: Remove a tag from a video + tags: + - Videos\Tags + get: + operationId: check_video_for_tag + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The tag word. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "204": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/tag" + description: The tag has been added. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * A parameter is invalid. + * The tag is invalid. + "404": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such tag exists within the video. + summary: Check if a tag has been added to a video + tags: + - Videos\Tags + put: + operationId: add_video_tag + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The tag word. + in: path + name: word + required: true + schema: + example: awesome + type: string + responses: + "204": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/tag" + description: The tag was added. + "400": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The tag is invalid. + * An unsupported parameter was supplied. + "403": + content: + application/vnd.vimeo.tag+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The number of tags on the video would exceed 20. + security: + - oauth2: + - edit + summary: Add a specific tag to a video + tags: + - Videos\Tags + "/videos/{video_id}/texttracks": + get: + operationId: get_text_tracks + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + items: + $ref: "#/components/schemas/text-track" + type: array + description: The text tracks were returned. + "404": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video exists. + summary: Get all the text tracks of a video + tags: + - Videos\Text Tracks + post: + description: For additional information, see our [text track upload guide](https://developer.vimeo.com/api/upload/texttracks). + operationId: create_text_track + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.video.texttrack+json: + schema: + properties: + active: + description: Active text tracks appear in the player and are visible to other users. Only one text track per language can be active. + example: "true" + type: boolean + language: + description: The language of the text track. For a complete list of valid languages, use the [/languages?filter=texttracks](https://developer.vimeo.com/api/endpoints/videos#GET/languages) endpoint. + example: en-US + type: string + name: + description: The name of the text track. + example: Commentary + type: string + type: + description: The type of the text track. + enum: + - captions + - chapters + - descriptions + - metadata + - subtitles + type: string + required: + - language + - name + - type + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/text-track" + description: The text track was added. + "403": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user can't edit the text track. + * Error code 2204: The request contains errors. + security: + - oauth2: + - upload + summary: Add a text track to a video + tags: + - Videos\Text Tracks + "/videos/{video_id}/texttracks/{texttrack_id}": + delete: + operationId: delete_text_track + parameters: + - description: The ID of the text track. + in: path + name: texttrack_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "204": + description: The text track was deleted. + "403": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 3430: You don't have permission to access this text track. + * Error code 3431: This text track is disabled. + "404": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such video or text track exists. + * The authenticated user can't delete the text track. + * Error code 5014: The text track that you specified doesn't exist. + * Error code 5015: The text track that you specified belongs to a different video. + security: + - oauth2: + - delete + summary: Delete a text track + tags: + - Videos\Text Tracks + get: + operationId: get_text_track + parameters: + - description: The ID of the text track. + in: path + name: texttrack_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/text-track" + description: The text track was returned. + "403": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 3430: You don't have permission to access this text track. + * Error code 3431: This text track is disabled. + "404": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such video or text track exists. + * Error code 5014: The text track that you specified doesn't exist. + * Error code 5015: The text track that you specified belongs to a different video. + summary: Get a specific text track + tags: + - Videos\Text Tracks + patch: + operationId: edit_text_track + parameters: + - description: The ID of the text track. + in: path + name: texttrack_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.video.texttrack+json: + schema: + properties: + active: + description: Whether the text track is active, meaning that it appears in the player. Only one text track per language, and type, can be active. + example: "true" + type: boolean + language: + description: The language of the text track. For a full list of valid languages, use the [/languages?filter=texttracks](https://developer.vimeo.com/api/endpoints/videos#GET/languages) endpoint. + example: en-US + type: string + name: + description: The name of the text track. + example: Commentary + type: string + type: + description: The text track type. + enum: + - captions + - chapters + - descriptions + - metadata + - subtitles + type: string + type: object + required: false + responses: + "200": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/text-track" + description: The text track was edited. + "403": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * The authenticated user can't edit the text track. + * Error code 2204: There are errors in the request. + * Error code 3430: You don't have permission to access this text track. + * Error code 3431: This text track is disabled. + "404": + content: + application/vnd.vimeo.video.texttrack+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: |- + * No such video or text track exists. + * Error code 5014: The text track that you specified doesn't exist. + * Error code 5015: The text track that you specified belongs to a different video. + security: + - oauth2: + - edit + summary: Edit a text track + tags: + - Videos\Text Tracks + "/videos/{video_id}/timelinethumbnails": + post: + operationId: create_video_custom_logo + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "201": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: Standard request. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: If the user is attempting to upload pictures for another user's videos. + "404": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: No such video exists. + security: + - oauth2: + - upload + summary: Add a new custom logo to a video + tags: + - Embed Presets\Videos + "/videos/{video_id}/timelinethumbnails/{thumbnail_id}": + get: + operationId: get_video_custom_logo + parameters: + - description: The ID of the picture. + in: path + name: thumbnail_id + required: true + schema: + example: 12345 + type: number + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + responses: + "200": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/picture" + description: The custom logo was returned. + "403": + content: + application/vnd.vimeo.picture+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: If the user isn't permitted to view this custom logo. + summary: Get a custom video logo + tags: + - Embed Presets\Videos + "/videos/{video_id}/versions": + post: + operationId: create_video_version + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + requestBody: + content: + application/vnd.vimeo.video.version+json: + schema: + properties: + file_name: + description: The name of the version + example: untitled.mp4 + type: string + upload: + properties: + approach: + description: Upload approach + enum: + - post + - pull + - streaming + - tus + type: string + link: + description: If your upload approach is pull, Vimeo will download the video hosted at this public URL. This URL must be valid for at least 24 hours. + example: https://example.com + type: string + redirect_url: + description: The app's redirect URL. Use this parameter when `approach` is `post`. + example: https://example.com + type: string + size: + description: Upload size + example: "13623861" + type: string + required: + - approach + type: object + required: + - file_name + - upload + type: object + required: true + responses: + "201": + content: + application/vnd.vimeo.video.version+json: + schema: + $ref: "#/components/schemas/video-versions" + description: Standard request. + "400": + content: + application/vnd.vimeo.video.version+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 2204: If the request input contains invalid upload data. + * Error code 2204: If the request input contains invalid versions data. + "403": + content: + application/vnd.vimeo.video.version+json: + schema: + $ref: "#/components/schemas/error" + description: "Error code 3427: If a user isn't permitted to edit the video" + "404": + content: + application/vnd.vimeo.video.version+json: + schema: + $ref: "#/components/schemas/error" + description: |- + * Error code 5011: If an upload associated with the version isn't found. + * Error code 5012: If a video associated with the upload isn't found. + * Error code 5013: If the version of the API used is less than 3.4 and isn't of approach `tus`, the endpoint isn't available. + summary: Add a version to a video + tags: + - Videos\Versions + "/videos/{video_id}/videos": + get: + operationId: get_related_videos + parameters: + - description: The ID of the video. + in: path + name: video_id + required: true + schema: + example: 258684937 + type: number + - description: The attribute by which to filter the results. + in: query + name: filter + required: false + schema: + enum: + - related + type: string + - description: The page number of the results to show. + in: query + name: page + required: false + schema: + example: 1 + type: number + - description: The number of items to show on each page of results, up to a maximum of 100. + in: query + name: per_page + required: false + schema: + example: 10 + type: number + responses: + "200": + content: + application/vnd.vimeo.video+json: + schema: + items: + $ref: "#/components/schemas/video" + type: array + description: The related videos were returned. + "400": + content: + application/vnd.vimeo.video+json: + schema: + $ref: "#/components/schemas/legacy-error" + description: The value of `filter` isn' `related`. + summary: Get all the related videos of a video + tags: + - Videos\Recommendations +components: + schemas: + activity-3-1: + properties: + category: + allOf: + - $ref: "#/components/schemas/category" + description: The category that this event occurred for. This will be preset for only "category" activity types. + channel: + allOf: + - $ref: "#/components/schemas/channel" + description: The channel that this event occurred for. This will be present for only "channel" activity types. + clip: + allOf: + - $ref: "#/components/schemas/video" + description: Video associated with ths activity. + group: + allOf: + - $ref: "#/components/schemas/group" + description: The group that this event occurred for. This will be present for only "group" activity types. + metadata: + description: The activity's metadata. + properties: + connections: + description: A list of resource URIs related to the activity. + properties: + related: + description: Related content for this activity. + nullable: true + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/activities?offset=20 + type: string + required: + - options + - uri + type: object + required: + - related + type: object + required: + - connections + type: object + tag: + allOf: + - $ref: "#/components/schemas/tag" + description: The tag that this event occurred for. This will be present for only "tag" activity types. + time: + description: Time that the event occurred. + example: 2017-05-17T17:46:09+00:00 + type: string + type: + description: Activity type + enum: + - appearance + - category + - channel + - facebook_feed + - group + - like + - ondemand + - share + - tag + - twitter_timeline + - upload + example: appearance + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The user that this event occurred for. This will be present for "like", "appearance", and "share" activity types. + required: + - clip + - metadata + - time + - type + title: Activity 3.1 + type: object + album: + properties: + allow_continuous_play: + description: Whether an album should allow continuous play. + example: "true" + type: boolean + allow_downloads: + description: Whether an album should allow downloads. + example: "true" + type: boolean + allow_share: + description: Whether an album should allow sharing. + example: "true" + type: boolean + brand_color: + description: Hexadecimal color code for the decorative color. For example, album videos use this color for player buttons. + example: ff66ee + nullable: true + type: string + created_time: + description: The time in ISO 8601 format that the album was created. + example: 2015-12-17T21:32:44+00:00 + type: string + custom_logo: + allOf: + - $ref: "#/components/schemas/picture" + description: The custom logo for this album. + nullable: true + description: + description: A brief description of the album's content. + example: Vimeo holiday videos! + nullable: true + type: string + domain: + description: The custom domain a user has selected for their album. + example: mycustomdomain.com + nullable: true + type: string + duration: + description: The total duration in seconds of all the videos in the album. + example: 1163 + type: number + embed: + description: Embed data for the album. + properties: + html: + description: The responsive HTML code to embed the playlist on a website. This is present only when `privacy.view` isn't password and when the album has embeddable videos. + nullable: true + type: string + required: + - html + type: object + embed_brand_color: + description: Whether to show the album's custom brand color in the player of the album's embedded playlist. + example: "true" + nullable: true + type: boolean + embed_custom_logo: + description: Whether to show the album's custom logo in the player of the album's embedded playlist. + example: "true" + nullable: true + type: boolean + hide_nav: + description: Whether to hide the Vimeo navigation when viewing the album. + example: "true" + type: boolean + hide_vimeo_logo: + description: Whether to hide the Vimeo logo in the player of the album's embedded playlist. + example: "true" + nullable: true + type: boolean + layout: + description: The album's layout preference + enum: + - grid + - player + example: grid + type: string + link: + description: The URL to access the album. + example: https://vimeo.com/album/Vimeo Holiday Videos! + type: string + metadata: + description: Metadata about the album. + properties: + connections: + description: A collection of information that is connected to this resource. + properties: + videos: + description: Information about the videos that belong to this album. + properties: + options: + description: An array of the HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 6 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /albums/3706071/videos + type: string + required: + - options + - total + - uri + type: object + required: + - videos + type: object + interactions: + description: A list of resource URIs related to the album. + nullable: true + properties: + add_custom_thumbnails: + description: An action indicating that the authenticated user is an admin of the album and may therefore add custom thumbnails. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /users/123456/albums/654321/custom_thumbnails + type: string + required: + - options + - uri + type: object + add_logos: + description: An action indicating that the authenticated user is an admin of the album and may therefore add custom logos. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /users/123456/albums/654321/logos + type: string + required: + - options + - uri + type: object + add_videos: + description: An action indicating that the authenticated user is an admin of the album and may therefore add videos. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods allowed on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /users/123456/albums/654321/videos + type: string + required: + - options + - uri + type: object + required: + - add_custom_thumbnails + - add_logos + - add_videos + type: object + required: + - connections + - interactions + type: object + modified_time: + description: The time in ISO 8601 format when the album was last modified. + example: 2018-02-06T21:24:17+00:00 + type: string + name: + description: The album's display name. + example: Vimeo Holiday Videos! + type: string + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active image for the album; defaults to the thumbnail of the last video added to the album. + privacy: + description: The privacy settings of the album. + properties: + password: + description: The privacy-enabled password to see this album. Present only when `privacy.view` is `password`. + example: hunter1 + type: string + view: + description: | + Who can view the album: + + Option descriptions: + * `anybody` - Anyone can view the album. + * `embed_only` - Only owner can see album, can be embedded off-site + * `password` - Only those with the password can view the album. + enum: + - anybody + - embed_only + - password + example: anybody + type: string + required: + - view + type: object + resource_key: + description: The album resource key. + example: e5595241643259c658ed6c85ca82985a6341edc7 + type: string + review_mode: + description: Whether album videos should use the review mode URL. + example: "true" + type: boolean + sort: + description: Sort type of the album. + enum: + - added_first + - added_last + - alphabetical + - arranged + - comments + - likes + - newest + - oldest + - plays + example: added_first + type: string + theme: + description: The album's color theme preference + enum: + - dark + - standard + example: dark + type: string + uri: + description: The album's URI. + example: /albums/3706071 + type: string + url: + description: The custom Vimeo URL a user has selected for their album. + example: my-custom-url + nullable: true + type: string + use_custom_domain: + description: Whether the user has opted in to use a custom domain for their album. + example: "false" + type: boolean + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the album. + web_brand_color: + description: Whether an album should show the brand color in the web layout. + example: "true" + type: boolean + web_custom_logo: + description: Whether an album's custom logo should be shown in the web layout. + example: "true" + type: boolean + required: + - allow_continuous_play + - allow_downloads + - allow_share + - brand_color + - created_time + - custom_logo + - description + - domain + - duration + - embed + - embed_brand_color + - embed_custom_logo + - hide_nav + - hide_vimeo_logo + - layout + - link + - metadata + - modified_time + - name + - pictures + - privacy + - resource_key + - review_mode + - sort + - theme + - uri + - url + - use_custom_domain + - user + - web_brand_color + - web_custom_logo + title: Album + type: object + api-app: + properties: + name: + description: The name of the API app. + example: Vimeo Android + type: string + uri: + description: The canonical URI of the API app. + example: /apps/12345 + type: string + required: + - name + - uri + title: API App + type: object + auth: + properties: + access_token: + description: The access token string. + example: 01019a4a62aec63db077317ab7bb429db75652401e + type: string + app: + allOf: + - $ref: "#/components/schemas/api-app" + description: The API application associated with the token. + expires_on: + description: The date and time that the token expires. + example: "1495048954" + type: string + refresh_token: + description: The refresh token string. + example: 3d3bc8a9cb7debfd01b270e419b2d265983362f9 + type: string + scope: + description: The scope or scopes that the token supports. + example: private create edit upload public + type: string + token_type: + description: | + The token type: + + Option descriptions: + * `bearer` - The token is of the `bearer` type. + enum: + - bearer + example: bearer + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The user associated with the token. + required: + - access_token + - app + - scope + - token_type + title: Auth + type: object + auth-error: + properties: + error: + description: The name of the error. + example: server_error + type: string + error_description: + description: The description of the error. + example: An error has occurred on Vimeo's servers. Please try again. + type: string + required: + - error + - error_description + title: Auth Error + type: object + category: + properties: + icon: + allOf: + - $ref: "#/components/schemas/picture" + description: The active icon for the category. + last_video_featured_time: + description: The last time, in ISO 8601 format, that a video was featured. + example: 2017-05-17T17:46:09+00:00 + type: string + link: + description: The URL to access the category in a browser. + example: https://vimeo.com/categories/animation + type: string + metadata: + description: Metadata about the category. + properties: + connections: + description: A collection of information that is connected to this resource. + properties: + channels: + description: Information about the channels related to this category. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of channels on this connection. + example: 90 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /categories/animation/channels + type: string + required: + - options + - total + - uri + type: object + groups: + description: Information about the groups related to this category. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of groups on this connection. + example: 15 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /categories/animation/groups + type: string + required: + - options + - total + - uri + type: object + users: + description: Information about the users related to this category. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of users on this connection. + example: 140 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /categories/animation/videos + type: string + required: + - options + - total + - uri + type: object + videos: + description: Information about the videos related to this category. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 960 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /categories/animation/videos + type: string + required: + - options + - total + - uri + type: object + required: + - channels + - groups + - users + - videos + type: object + interactions: + description: The permissible actions related to the category. + properties: + follow: + description: An action indicating if the authenticated user has followed this category. + properties: + added: + description: Whether the authenticated user has followed this category. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format that the user followed this category, or the null value if the user hasn't followed this category. + example: 2017-05-17T17:46:09+00:00 + nullable: true + type: string + uri: + description: "The URI for following or unfollowing this category: PUT to this URI to follow the category, or DELETE to this URI to unfollow the category." + example: /users/152184/categories/animation + type: string + required: + - added + - added_time + - uri + type: object + required: + - follow + type: object + required: + - connections + - interactions + type: object + name: + description: The display name that identifies the category. + example: Animation + type: string + parent: + description: The container of this category's parent category, if the current category is a subcategory. + nullable: true + properties: + link: + description: The URL to access the parent category in a browser. + example: https://vimeo.com/categories/animation + type: string + name: + description: The display name that identifies the parent category. + example: Animation + type: string + uri: + description: The unique identifier to access the parent of this category resource. + example: /categories/animation + type: string + required: + - link + - name + - uri + type: object + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active picture for this category; defaults to vertical color bars. + resource_key: + description: The resource key of the category. + example: e5595241643259c658ed6c85ca82985a6341edc7 + type: string + subcategories: + description: All the subcategories that belong to this category, if the current category is a top-level parent. + items: + properties: + link: + description: The URL to access the subcategory in a browser. + example: https://vimeo.com/categories/animation/2d/videos + type: string + name: + description: The display name that identifies the subcategory. + example: 2D + type: string + uri: + description: The unique identifier to access the subcategory resource. + example: /categories/animation/subcategories/2d + type: string + required: + - link + - name + - uri + type: object + type: array + top_level: + description: Whether the category isn't a subcategory of another category. + example: "true" + type: boolean + uri: + description: The unique identifier to access the category resource. + example: /categories/animation + type: string + required: + - last_video_featured_time + - link + - metadata + - name + - parent + - pictures + - resource_key + - top_level + - uri + title: Category + type: object + channel: + properties: + categories: + description: The categories to which this channel belongs as specified by the channel moderators. + items: + $ref: "#/components/schemas/category" + type: array + created_time: + description: The time in ISO 8601 format when the channel was created. + example: 2007-10-23T17:00:43+00:00 + type: string + description: + description: A brief explanation of the channel's content. + example: We really love videos, and these are the videos we really, really love. + nullable: true + type: string + header: + allOf: + - $ref: "#/components/schemas/picture" + description: The banner that appears by default at the top of the channel page. + link: + description: The URL to access the channel in a browser. + example: https://vimeo.com/channels/staffpicks + type: string + metadata: + description: Metadata about the channel. + properties: + connections: + description: A collection of information that is connected to this resource. + properties: + privacy_users: + description: Information provided to channel moderators about which users they have specifically permitted to access a private channel. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + total: + description: The total number of users on this connection. This data requires a bearer token with the `private` scope. + example: 36 + type: number + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /channels/927/privacy/users + type: string + required: + - options + - total + - uri + type: object + users: + description: Information about the users following or moderating this channel. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of users on this connection. + example: 794634 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /channels/927/users + type: string + required: + - options + - total + - uri + type: object + videos: + description: Information about the videos that belong to this channel. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 12448 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /channels/927/videos + type: string + required: + - options + - total + - uri + type: object + required: + - privacy_users + - users + - videos + type: object + interactions: + description: A list of resource URIs related to the channel. + nullable: true + properties: + add_moderators: + description: An action indicating that the authenticated user is the owner of the channel and may therefore add other users as channel moderators. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /channels/1234/moderators + type: string + required: + - options + - uri + type: object + add_to: + description: When a channel appears in the context of adding or removing a video from it (`/videos/{video_id}/available_channels`), include information about adding or removing the video. This data requires a bearer token with the `private` scope. + nullable: true + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /channels/1234/videos/5678 + type: string + required: + - options + - uri + type: object + follow: + description: An action indicating if the authenticated user has followed this channel. This data requires a bearer token with the `private` scope. + properties: + added: + description: Whether the authenticated user has followed this channel. This data requires a bearer token with the `private` scope. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format that the user followed this channel, or the null value if the user hasn't followed the channel. This data requires a bearer token with the `private` scope. + example: 2017-05-22T17:50:11+00:00 + nullable: true + type: string + type: + description: | + Whether the authenticated user is a moderator or subscriber. This data requires a bearer token with the `private` scope. + + Option descriptions: + * `moderator` - The authenticated user is a moderator. + * `subscriber` - The authenticated user is a subscriber. + enum: + - moderator + - subscriber + example: moderator + nullable: true + type: string + uri: + description: The URI for following or unfollowing this channel. PUT to this URI to follow the channel, or DELETE to this URI to unfollow the channel. This data requires a bearer token with the `private` scope. + example: /users/1234/channels/927 + type: string + required: + - added + - added_time + - type + - uri + type: object + moderate_videos: + description: An action indicating that the authenticated user is a moderator of the channel and may therefore add or remove videos from the channel. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods allowed on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /channels/1234/videos + type: string + required: + - options + - uri + type: object + required: + - add_moderators + - add_to + - follow + - moderate_videos + type: object + required: + - connections + - interactions + type: object + modified_time: + description: The time in ISO 8601 format when the album was last modified. + example: 2018-03-21T22:52:29+00:00 + type: string + name: + description: The display name that identifies the channel. + example: Vimeo Staff Picks + type: string + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active image for the channel; defaults to the thumbnail of the last video added to the channel. + privacy: + description: The privacy settings of the channel. + properties: + view: + description: | + Who can view the channel: + + Option descriptions: + * `anybody` - Anyone can view the channel. + * `moderators` - Only moderators can view the channel. + * `users` - Only registered users can view the channel. + enum: + - anybody + - moderators + - users + example: anybody + type: string + required: + - view + type: object + resource_key: + description: The channel resource key. + example: e5595241643259c658ed6c85ca82985a6341edc7 + type: string + tags: + description: An array of all tags assigned to this channel. + items: + $ref: "#/components/schemas/tag" + type: array + uri: + description: The unique identifier to access the channel resource. + example: /channels/927 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The Vimeo user who owns the channel. + required: + - categories + - created_time + - description + - header + - link + - metadata + - modified_time + - name + - pictures + - privacy + - resource_key + - tags + - uri + - user + title: Channel + type: object + comment: + properties: + created_on: + description: The time in ISO 8601 format when the comment was posted. + example: 2018-03-05T21:04:47+00:00 + type: string + metadata: + properties: + connections: + properties: + replies: + description: Information about this comment's replies. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of replies on this connection. + example: 42 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/comments/12345/replies + type: string + required: + - options + - total + - uri + type: object + required: + - replies + type: object + required: + - connections + type: object + resource_key: + description: The resource key string for the comment. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + text: + description: The content of the comment. + example: I love this! + type: string + type: + description: | + The Vimeo content to which the comment relates: + + Option descriptions: + * `video` - The comment is about a video. + enum: + - video + example: video + type: string + uri: + description: The unique identifier to access the comment resource. + example: /videos/258684937/comments/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The user who posted the comment. + nullable: true + required: + - created_on + - metadata + - resource_key + - text + - type + - uri + - user + title: Comment + type: object + content-rating: + properties: + code: + description: | + The code that uniquely identifies this content rating: + + Option descriptions: + * `drugs` - Drug or alcohol use. + * `language` - Profanity or sexually suggestive content. + * `nudity` - Nudity. + * `safe` - Suitable for all audiences. + * `unrated` - No rating. + * `violence` - Violent or graphic content. + enum: + - drugs + - language + - nudity + - safe + - unrated + - violence + example: violence + type: string + name: + description: The description of this content rating. + example: Violence + type: string + uri: + description: The canonical relative URI of the content rating. + example: /contentrating/violence + nullable: true + type: string + required: + - code + - name + - uri + title: Content Rating + type: object + creative-commons: + properties: + code: + description: | + The code that uniquely identifies this Creative Commons license: + + Option descriptions: + * `by` - Attribution + * `by-nc` - Attribution Non-Commercial + * `by-nc-nd` - Attribution Non-Commercial No Derivatives + * `by-nc-sa` - Attribution Non-Commercial Share Alike + * `by-nd` - Attribution No Derivatives + * `by-sa` - Attribution Share Alike + * `cc0` - Public Domain Dedication + enum: + - by + - by-nc + - by-nc-nd + - by-nc-sa + - by-nd + - by-sa + - cc0 + example: by-sa + type: string + name: + description: The description of this Creative Commons license. + example: Attribution Share Alike + type: string + uri: + description: The canonical relative URI of the Creative Commons license. + example: /creativecommons/by-sa + nullable: true + type: string + required: + - code + - name + - uri + title: Creative Commons + type: object + credit: + properties: + name: + description: The name of the person credited. + example: Sam Doe + type: string + role: + description: The character that this person portrayed, or the job that this person performed. + example: Themselves + type: string + uri: + description: The unique identifier to access the credits resource. + example: /videos/258684937/credits/1234 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The Vimeo user associated with this credit. + video: + allOf: + - $ref: "#/components/schemas/video" + description: The video associated with this credit. + required: + - name + - role + - uri + title: Credit + type: object + domain: + properties: + allow_hd: + description: Whether to permit HD embeds on this domain. + example: "true" + type: boolean + domain: + description: The domain name. + example: example.com + type: string + uri: + description: The URI of the domain. + example: /videos/258684937/privacy/domains/example.com + type: string + required: + - allow_hd + - domain + - uri + title: Domain + type: object + embed-settings: + properties: + buttons: + description: A collection of information about the buttons that appear on the interface of the embeddable player. + properties: + embed: + description: Whether the Embed button appears in the embeddable player for this video. + example: "true" + type: boolean + fullscreen: + description: Whether the Fullscreen button appears in the embeddable player for this video. + example: "true" + type: boolean + hd: + description: Whether the HD button appears in the embeddable player for this video. + example: "true" + type: boolean + like: + description: Whether the Like button appears in the embeddable player for this video. + example: "true" + type: boolean + scaling: + description: Whether the Scaling button appears in the embeddable player for this video. + example: "true" + type: boolean + share: + description: Whether the Share button appears in the embeddable player for this video. + example: "true" + type: boolean + watchlater: + description: Whether the Watch Later button appears in the embeddable player for this video. + example: "true" + type: boolean + required: + - embed + - fullscreen + - hd + - like + - scaling + - share + - watchlater + type: object + color: + description: The primary player color, which controls the color of the progress bar, buttons, and more. + example: "#0a0808" + type: string + logos: + description: A collection of information about the logo in the corner of the embeddable player. + properties: + custom: + description: A collection of information relating to custom logos in the embeddable player. + properties: + active: + description: Whether the custom logo appears in the embeddable player. + example: "true" + type: boolean + link: + description: The URL that loads upon clicking the custom logo. + example: http://example.com + type: string + sticky: + description: Whether the custom logo appears even when the player interface is hidden. + example: "true" + type: boolean + required: + - active + - link + - sticky + type: object + vimeo: + description: Whether the Vimeo logo appears in the embeddable player for this video. + example: "true" + type: boolean + required: + - custom + - vimeo + type: object + playbar: + description: Whether the playbar appears in the embeddable player for this video. + example: "true" + type: boolean + speed: + description: Whether the speed controls appear in the embeddable player for this video. + example: "true" + type: boolean + title: + description: A collection of information relating to the embeddable player's title bar. + properties: + name: + description: | + How the embeddable player handles the video title: + + Option descriptions: + * `hide` - The title is hidden. + * `show` - The title is shown. + enum: + - hide + - show + - user + example: hide + type: string + owner: + description: | + How the embeddable player handles the video owner's information: + + Option descriptions: + * `hide` - The owner's information is hidden. + * `show` - The owner's information is shown. + enum: + - hide + - show + - user + example: hide + type: string + portrait: + description: | + How the embeddable player handles the video owner's portrait: + + Option descriptions: + * `hide` - The owner's portrait is hidden + * `show` - The owner's portrait is shown. + enum: + - hide + - show + - user + example: hide + type: string + required: + - name + - owner + - portrait + type: object + uri: + description: The URI of the embed preset. + example: /videos/258684937/presets/12345 + type: string + volume: + description: Whether the volume controls appear in the embeddable player for this video. + example: "true" + type: boolean + required: + - buttons + - color + - logos + - playbar + - speed + - title + - volume + title: Embed Settings + type: object + endpoint: + properties: + methods: + description: All HTTP methods permitted on this endpoint. + items: + type: string + type: array + path: + description: The path section of the URL, which, when appended to the API host `https:///api.vimeo.com`, builds a full API endpoint. + example: /me + type: string + required: + - methods + - path + title: Endpoint + type: object + error: + properties: + developer_message: + description: The error message that developers receive. + example: The specified resource does not exist. + type: string + error: + description: The error message that non-developer users receive. + example: Something strange occurred. Please try again. + type: string + error_code: + description: The error code. + example: 5000 + type: number + link: + description: A link to more information about the error. + type: string + required: + - developer_message + - error + - error_code + - link + title: Error + type: object + group: + properties: + created_time: + description: The time in ISO 8601 format when the group was created. + example: 2008-07-05T14:52:43+00:00 + type: string + description: + description: The group's description. + example: Want to participate in our weekly Challenges? Join the Group to receive messages and new Challenges! + nullable: true + type: string + link: + description: The link to the group. + example: https://vimeo.com/groups/weekendchallenge + type: string + metadata: + description: Metadata about the group. + properties: + connections: + description: A collection of information that is connected to this resource. + properties: + users: + description: Information about the members or moderators of this group. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of users on this connection. + example: 25798 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /groups/1108/users + type: string + required: + - options + - total + - uri + type: object + videos: + description: Information about the videos contained within this group. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 7252 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /groups/1108/videos + type: string + required: + - options + - total + - uri + type: object + required: + - users + - videos + type: object + interactions: + description: User actions that have involved the group. This data requires a bearer token with the `private` scope. + properties: + join: + description: An action indicating that someone has joined the group. This data requires a bearer token with the `private` scope. + properties: + added: + description: Whether the authenticated user has followed this group. This data requires a bearer token with the `private` scope. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the user joined this group. This data requires a bearer token with the `private` scope. + nullable: true + type: string + title: + description: The user's title, or the null value if not applicable. This data requires a bearer token with the `private` scope. + example: Vimeo Staff + nullable: true + type: string + type: + description: | + Whether the authenticated user is a moderator or subscriber. This data requires a bearer token with the `private` scope. + + Option descriptions: + * `member` - The authenticated user is a member. + * `moderator` - The authenticated user is a moderator. + enum: + - member + - moderator + example: member + nullable: true + type: string + uri: + description: The URI for following. PUT to this URI to follow, or DELETE to this URI to unfollow. This data requires a bearer token with the `private` scope. + example: /users/152184/groups/1108 + type: string + required: + - added + - added_time + - title + - type + - uri + type: object + required: + - join + type: object + required: + - connections + - interactions + type: object + modified_time: + description: The time in ISO 8601 format when the group was last modified. + example: 2018-09-16T15:41:45+00:00 + type: string + name: + description: The group's display name. + example: Vimeo Weekend Challenge + type: string + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active picture for this group. + privacy: + description: The group's privacy settings. + properties: + comment: + description: | + Who can comment on the group: + + Option descriptions: + * `all` - Anyone can comment on the group. + * `members` - Only members can comment on the group. + enum: + - all + - members + example: all + type: string + invite: + description: | + Who can invite new members to the group: + + Option descriptions: + * `all` - Anyone can invite new members to join. + * `members` - Only group members can invite new members to join. + enum: + - all + - members + example: all + type: string + join: + description: | + Who can join the group: + + Option descriptions: + * `anybody` - Anyone can join the group. + * `members` - Only people with a Vimeo account can join the group. + enum: + - anybody + - members + example: anybody + type: string + videos: + description: | + Who can add videos to the group: + + Option descriptions: + * `all` - Anyone can add videos to the group. + * `members` - Only group members can add videos to the group. + enum: + - all + - members + example: all + type: string + view: + description: | + Who can view the group: + + Option descriptions: + * `anybody` - Anyone can view the group. + * `members` - Only group members can view the group. + enum: + - anybody + - members + example: anybody + type: string + required: + - comment + - invite + - join + - videos + - view + type: object + resource_key: + description: The resource key of the group. + example: dc724af18fbdd4e59189f5fe768a5f8311527050 + type: string + uri: + description: The canonical relative URI of this group. + example: /groups/1108 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the group. + nullable: true + required: + - created_time + - description + - link + - metadata + - modified_time + - name + - pictures + - privacy + - resource_key + - uri + title: Group + type: object + language: + properties: + code: + description: The code that represents this language. + example: en-US + type: string + name: + description: The name of the language. + example: English (United States) + type: string + required: + - code + - name + title: Language + type: object + legacy-error: + properties: + error: + description: User-friendly error message + example: Something strange occurred. Please try again. + type: string + required: + - error + title: Legacy Error + type: object + on-demand-genre: + properties: + canonical: + description: The canonical name or URL slug of the genre. + example: horror + type: string + interactions: + properties: + page: + description: Interactions for On Demand pages that are in this genre. + properties: + added: + description: Whether this On Demand genre was added. + example: "true" + type: boolean + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The URI to access the On Demand page. + example: /ondemand/genres/horror/pages/12345 + type: string + required: + - added + - options + - uri + type: object + required: + - page + type: object + link: + description: The Vimeo URL for this genre. + example: http://vimeo.com/ondemand/browse/horror + type: string + metadata: + properties: + connections: + description: A collection of information connected to this resource. + properties: + pages: + description: Information about the On Demand pages related to this group. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/genres/horror/pages + type: string + required: + - options + - uri + type: object + required: + - pages + type: object + required: + - connections + type: object + name: + description: The descriptive name of the genre. + example: Horror + type: string + uri: + description: The relative URI of the On Demand genre. + example: /ondemand/genres/horror + type: string + required: + - canonical + - interactions + - link + - metadata + - name + - uri + title: On Demand Genre + type: object + on-demand-page: + properties: + background: + allOf: + - $ref: "#/components/schemas/picture" + description: The background image for the On Demand page on Vimeo. + nullable: true + colors: + description: The primary and secondary colors used for rendering this On Demand page. + properties: + primary: + description: The hexadecimal color code for the page's primary color. + example: "#0a0808" + type: string + secondary: + description: The hexadecimal color code for the page's secondary color. + example: "#ba4a17" + type: string + required: + - primary + - secondary + type: object + content_rating: + description: An array of the page's content ratings. + items: + type: string + type: array + created_time: + description: The time in ISO 8601 format when the page was created. + example: 2017-05-15T13:42:25+00:00 + type: string + description: + description: The description of this On Demand page. + example: DARBY FOREVER follows the fantasies of Darby, a shopgirl at "Bobbins & Notions" + nullable: true + type: string + domain_link: + description: The link to this page on its own domain. + example: https://example.com + nullable: true + type: string + episodes: + description: Information about this On Demand page's episodes, if the page is for a series. + properties: + buy: + properties: + active: + description: Whether all the videos on this On Demand page can be purchased as a whole. + example: "true" + type: boolean + price: + description: The default price to buy an episode. + example: 9.99 + nullable: true + type: number + required: + - active + - price + type: object + rent: + properties: + active: + description: Whether all the videos on this On Demand page can be rented as a whole. + example: "true" + type: boolean + period: + description: | + The rental period for the video: + + Option descriptions: + * `1 day` - The rental period is one day. + * `1 month` - The rental period is one month. + * `1 week` - The rental period is one week. + * `1 year` - The rental period is one year. + * `2 day` - The rental period is two days. + * `24 hour` - The rental period is 24 hours. + * `3 day` - The rental period is three days. + * `3 month` - The rental period is three months. + * `30 day` - The rental period is 30 days. + * `48 hour` - The rental period is 48 hours. + * `6 month` - The rental period is six months. + * `60 day` - The rental period is 60 days. + * `7 day` - The rental period is 7 days. + * `72 hour` - The rental period is 72 hours. + enum: + - 1 day + - 1 month + - 1 week + - 1 year + - 2 day + - 24 hour + - 3 day + - 3 month + - 30 day + - 48 hour + - 6 month + - 60 day + - 7 day + - 72 hour + example: 1 day + nullable: true + type: string + price: + description: The default price to rent an episode. + example: 2.99 + nullable: true + type: number + required: + - active + - period + - price + type: object + required: + - buy + - rent + type: object + film: + allOf: + - $ref: "#/components/schemas/video" + description: This On Demand page's film, if it is a film. + genres: + description: All the genres assigned to this page. + items: + $ref: "#/components/schemas/on-demand-genre" + type: array + link: + description: The link to the page on Vimeo. + example: https://vimeo.com/ondemand/darbyforever + type: string + metadata: + description: Metadata about the On Demand page. + properties: + connections: + description: A collection of information that is connected to this resource, including videos, genres, and pictures connections. + properties: + metadata: + properties: + connections: + properties: + comments: + description: Information about the comments associated with this page. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of comments on this connection. + example: 4 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/comments + type: string + required: + - options + - total + - uri + type: object + genres: + description: Information about the genres associated with this page. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of genres on this connection. + example: 9 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/genres + type: string + required: + - options + - total + - uri + type: object + likes: + description: Information about the likes associated with this page. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of likes on this connection. + example: 15 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/likes + type: string + required: + - options + - total + - uri + type: object + pictures: + description: Information about the pictures associated with this page. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of pictures on this connection. + example: 3 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/pictures + type: string + required: + - options + - total + - uri + type: object + seasons: + description: Information about the seasons associated with this page. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of seasons on this connection. + example: 3 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/seasons + type: string + required: + - options + - total + - uri + type: object + videos: + description: Information about the videos associated with this page. + properties: + extra_total: + description: The total number of extra videos. + example: 14 + type: number + main_total: + description: The total number of main videos. + example: 36 + type: number + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 50 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/videos + type: string + viewable_total: + description: The total number of viewable videos. + example: 50 + type: number + required: + - extra_total + - main_total + - options + - total + - uri + - viewable_total + type: object + required: + - comments + - genres + - likes + - pictures + - seasons + - videos + type: object + required: + - connections + type: object + required: + - metadata + type: object + interactions: + allOf: + - $ref: "#/components/schemas/purchase-interaction" + description: The user's available purchase interactions. + required: + - connections + - interactions + type: object + modified_time: + description: he time in ISO 8601 format when the page was last modified. + example: 2017-05-15T13:42:25+00:00 + type: string + name: + description: A descriptive title of this On Demand page. + example: Darby Forever + type: string + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active poster for this On Demand page. + nullable: true + preorder: + properties: + active: + description: Whether this page is available for preorder. + example: "true" + type: boolean + cancel_time: + description: The time in ISO 8601 format when the preorder was cancelled. + example: 2017-05-16T13:13:46+00:00 + type: string + publish_time: + description: The time in ISO 8601 format when the preorder was released to the public. + example: 2017-05-15T13:12:52+00:00 + type: string + time: + description: The time in ISO 8601 format when the preorder started. + example: 2017-05-15T13:13:31+00:00 + type: string + required: + - active + - cancel_time + - publish_time + - time + type: object + published: + properties: + enabled: + description: Whether this On Demand page has been published. + example: "true" + type: boolean + time: + description: The time in IS 8601 format when this page was published. + example: 2017-05-15T13:12:52+00:00 + type: string + required: + - enabled + - time + type: object + rating: + description: The rating of this page. + example: 7 + nullable: true + type: number + resource_key: + description: The VOD resource key. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + sku: + description: The creator-designated SKU for this On Demand page. + example: VIME0001 + nullable: true + type: string + subscription: + description: Information about subscribing to this On Demand page, if enabled. + nullable: true + properties: + active: + description: Whether this product is active. + example: "true" + type: boolean + link: + description: The link to this product on Vimeo. + example: https://vimeo.com/ondemand/darbyforever + nullable: true + type: string + period: + description: The product's rental period. + type: string + price: + description: The accepted currencies and respective pricing for this product. + type: object + required: + - active + - link + - price + type: object + theme: + description: The graphical theme for this On Demand page. + example: vader + type: string + thumbnail: + allOf: + - $ref: "#/components/schemas/picture" + description: The thumbnail image for the On Demand page on Vimeo. + nullable: true + trailer: + allOf: + - $ref: "#/components/schemas/video" + description: The trailer for this On Demand page. + nullable: true + type: + description: | + Whether this On Demand page is for a film or a series. + + Option descriptions: + * `film` - The On Demand page is for a film. + * `series` - The On Demand page is for a series. + enum: + - film + - series + example: film + type: string + uri: + description: The relative URI of the On Demand page. + example: /ondemand/pages/61326 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The user who created this On Demand page. + nullable: true + required: + - background + - colors + - content_rating + - description + - domain_link + - episodes + - genres + - link + - metadata + - name + - pictures + - preorder + - published + - rating + - resource_key + - subscription + - theme + - thumbnail + - trailer + - type + - uri + - user + title: On Demand Page + type: object + on-demand-promotion: + properties: + access_type: + description: | + The type of access that this promotion grants: + + Option descriptions: + * `default` - Grants discounts on existing product offerings. + * `vip` - Grants free access either to VOD content before it is released or to access types that aren't part of the existing product offerings. + enum: + - default + - vip + example: default + type: string + discount_type: + description: | + The type of discount for which this promotion can be used. + + Option descriptions: + * `dollars` - The discount is a certain fixed amount. + * `free` - The discount is the full purchase price. VIP access promotions always use this discount type. + * `percent` - The discount is a certain percentage of the full price. + enum: + - dollars + - free + - percent + example: free + type: string + download: + description: Whether this promotion grants download access to On Demand content. + example: "true" + type: boolean + label: + description: The prefix string for batch codes, or the null value for single codes. + example: 8jgaieumbzstujhn8k304iwwezawkvwm + nullable: true + type: string + metadata: + description: The video's metadata. + properties: + connections: + description: A list of resource URIs related to the On Demand promotion. + properties: + codes: + description: Information about the codes associated with this promotion. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of uses on this connection. + example: 1 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/promotion/12345/codes + type: string + required: + - options + - total + - uri + type: object + required: + - codes + type: object + required: + - connections + type: object + percent_off: + description: The percentage amount that is deducted from the product price. + example: 100 + type: number + product_type: + description: | + The type of product to which this promotion can be applied. Only `buy` and `rent` are available for the VIP access type: + + Option descriptions: + * `any` - The promotion can be applied to any product. + * `buy` - The promotion can be applied to a buyable single video. + * `buy_episode` - The promotion can be applied to a buyable single episode. + * `rent` - The promotion can be applied to a rentable single video. + * `rent_episode` - The promotion can be applied to a rentable single episode. + * `subscribe` - The promotion can be applied to a subscription. + enum: + - any + - buy + - buy_episode + - rent + - rent_episode + - subscribe + example: any + type: string + stream_period: + description: | + The amount of time that the user has access to the VOD content after redeeming a promo code. + + Option descriptions: + * `1_week` - Access lasts for one week. + * `1_year` - Access lasts for one year. + * `24_hour` - Access lasts for 24 hours. + * `30_days` - Access lasts for 30 days. + * `3_month` - Access lasts for 3 months. + * `48_hour` - Access lasts for 48 hours. + * `6_month` - Access lasts for 6 months. + * `72_hour` - Access lasts for 72 hours. + enum: + - 1_week + - 1_year + - 24_hour + - 30_days + - 3_month + - 48_hour + - 6_month + - 72_hour + example: 1_week + nullable: true + type: string + total: + description: The total amount of times that this promotion can be used. + example: 1 + type: number + type: + description: | + The way in which this promotion can generate promo codes: + + Option descriptions: + * `batch` - Provides many unique promo codes that can only be used once each. + * `batch_prefix` - Similar to `batch`, except that all codes have a similar prefix string. This mode is deprecated, yet it may still appear for some users. + * `single` - Provides a single promo code with many uses. + enum: + - batch + - batch_prefix + - single + example: batch + type: string + uri: + description: The promotion's canonical relative URI. + example: /ondemand/pages/61326/promotions/12345 + type: string + required: + - access_type + - discount_type + - download + - label + - metadata + - percent_off + - product_type + - stream_period + - total + - type + - uri + title: On Demand Promotion + type: object + on-demand-promotion-code: + properties: + code: + description: A promotion code that can be redeemed on Vimeo. + example: 8jgaieumbzstujhn8k304iwwezawkvwm + type: string + link: + description: A link to redeem the promotion code instantly. + example: https://vimeo.com/r/0trBLg/OGpnYWlldW + type: string + max_uses: + description: The total amount of times this code can be used. + example: 1 + type: number + uses: + description: The number of times that this code has been used. + example: 0 + type: number + required: + - code + - link + - max_uses + - uses + title: On Demand Promotion Code + type: object + on-demand-region: + properties: + country_code: + description: The ISO 3166-1 alpha-2 code for this country. + example: US + type: string + country_name: + description: The descriptive name of this country. + example: United States + type: string + uri: + description: The region container's relative URI. + example: /ondemand/pages/61326/regions/US + type: string + required: + - country_code + - country_name + - uri + title: On Demand Region + type: object + on-demand-season: + properties: + description: + description: The description for this season. + example: Season 1 + type: string + metadata: + properties: + connections: + properties: + videos: + description: The Videos connection. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 13 + type: number + uri: + description: The API URI that resolves to the connection ∂data. + example: /ondemand/pages/61326/season/12345/videos + type: string + required: + - options + - total + - uri + type: object + required: + - videos + type: object + required: + - connections + type: object + name: + description: The descriptive name of the season. + example: Season 1 + type: string + position: + description: The position of the season relative to other seasons in the series. + example: 1 + type: number + resource_key: + description: The unique identifier for this On Demand season. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + type: + description: The type of season. + example: main + type: string + uri: + description: The season container's relative URI. + example: /ondemand/pages/61326/seasons/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The creator of this On Demand page. + nullable: true + required: + - description + - metadata + - name + - position + - resource_key + - type + - uri + - user + title: On Demand Season + type: object + on-demand-video: + properties: + buy: + description: Information about purchasing this video. + nullable: true + properties: + active: + description: Whether this On Demand video can be purchased. + example: "true" + type: boolean + price: + description: A map of currency type to price. + type: object + purchased: + description: Whether this On Demand video has been purchased. + example: "true" + type: boolean + required: + - active + - price + type: object + description: + description: Description of the On Demand video. + example: DARBY FOREVER follows the fantasies of Darby, a shopgirl at "Bobbins & Notions". + type: string + duration: + description: The duration of the On Demand video. + example: "1197" + type: string + episode: + description: The episode number of the On Demand video. + example: 1 + type: number + interactions: + description: An object containing information about how the authenticated user can interact with this On Demand page. + properties: + page: + description: Information about how the authenticated user can interact with the connection to the video's On Demand page. + properties: + added: + description: Whether this On Demand page was added. + example: "true" + type: boolean + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The URI to access the On Demand page. + example: /ondemand/pages/61326 + type: string + required: + - added + - options + - uri + type: object + required: + - page + type: object + link: + description: The link to this video on Vimeo. + example: https://vimeo.com/ondemand/darbyforever/12345 + type: string + metadata: + description: Metadata information about this video. + properties: + connections: + properties: + season: + description: Information about this season. + properties: + name: + description: The name of the season on this connection. + example: Season 1 + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/seasons/12345 + type: string + required: + - name + - options + - uri + type: object + required: + - season + type: object + interactions: + properties: + likes: + description: Information about the user's Like interactions with this video. + properties: + added: + description: Whether the user has liked this video. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the user liked this video. + example: 2017-05-12T21:42:42+00:00 + type: string + uri: + description: The URI for the user to like this video. + example: /users/152184/likes/12345 + type: string + required: + - added + - added_time + - uri + type: object + watchlater: + description: Information about the user's Watch Later interactions with this video. + properties: + added: + description: Whether the user has added this video to their Watch Later queue. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the user added this video to their Watch Later queue. + example: 2017-05-12T21:42:42+00:00 + type: string + uri: + description: The URI for the user to add this video to their Watch Later queue. + example: /users/152184/watchlater/12345 + type: string + required: + - added + - added_time + - uri + type: object + required: + - likes + - watchlater + type: object + required: + - connections + - interactions + type: object + name: + description: The title of the On Demand video. + example: Darby Forever + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active picture for this video. + play_progress: + description: The user's most recent play position in seconds for this video. + example: 30 + type: number + position: + description: Describes the manual position of this video relative to the other videos owned by this On Demand page. + example: 1 + type: number + release_date: + description: The time in ISO 8601 format when the On Demand video was created or published. + example: 2017-05-12T21:06:42+00:00 + type: string + release_year: + description: The year that this On Demand video was released. + example: 2016 + nullable: true + type: number + rent: + description: Information about renting this video. + nullable: true + properties: + active: + description: Whether this On Demand video can be rented. + example: "true" + type: boolean + price: + description: A map of currency type to price. + type: object + purchased: + description: Whether this On Demand video has been rented. + example: "true" + type: boolean + required: + - active + - price + type: object + type: + description: | + The type of the On Demand video: + + Option descriptions: + * `extra` - The On Demand video is an extra feature. + * `main` - The On Demand video is a main feature. + * `trailer` - The On Demand video is a trailer. + enum: + - extra + - main + - trailer + example: main + type: string + uri: + description: The video container's relative URI. + example: /ondemand/pages/61326/videos/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the video. + required: + - buy + - interactions + - link + - metadata + - play_progress + - release_year + - rent + - type + - uri + title: On Demand Video + type: object + picture: + properties: + active: + description: Whether this picture is the active picture for its parent resource. + example: "true" + type: boolean + link: + description: The upload URL for the picture. This field appears when you create the picture resource for the first time. + type: string + resource_key: + description: The picture's resource key string. + example: dc724af18fbdd4e59189f5fe768a5f8311527050 + type: string + sizes: + description: An array containing reference information about all available image files. + items: + properties: + height: + description: The height of the image. + example: 720 + nullable: true + type: number + link: + description: The direct link to the image. + example: https://i.vimeocdn.com/video/581495283_1280x720.jpg?r=pad + type: string + link_with_play_button: + description: The direct link to the image with a play button overlay. + example: https://i.vimeocdn.com/filter/overlay?src0=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F581495283_1280x720.jpg&src1=http%3A%2F%2Ff.vimeocdn.com%2Fp%2Fimages%2Fcrawler_play.png + type: string + width: + description: The width of the image. + example: 1280 + type: number + required: + - height + - link + - width + type: object + type: array + type: + description: | + The type of the picture: + + Option descriptions: + * `caution` - An image that is appropriate for all ages. + * `custom` - A custom image for the video. + * `default` - The default image for the video. + enum: + - caution + - custom + - default + example: caution + type: string + uri: + description: The picture's URI. + example: /users/152184/pictures/12345 + type: string + required: + - active + - resource_key + - sizes + - type + - uri + title: Picture + type: object + play: + properties: + progressive: + description: Progressive files. + items: + properties: + created_time: + description: The time in ISO 8601 format when this video file was created. + example: 2017-05-16T17:21:51+00:00 + type: string + fps: + description: The FPS of the video file. + example: 30 + type: number + height: + description: The height in pixels of the video. + example: 720 + nullable: true + type: number + link: + description: The direct link to this video file. + type: string + link_expiration_time: + description: The time in ISO 8601 format when the link to this video file expires. + example: 2017-05-16T17:21:51+00:00 + type: string + log: + description: The URLs for logging events. + type: object + md5: + description: The MD5 hash of the video file. + example: 1bc29b36f623ba82aaf6724fd3b16718 + type: string + size: + description: The file size in bytes of this video. + example: 5000000 + nullable: true + type: number + type: + description: | + The type of the video file: + + Option descriptions: + * `source` - The video is a source file. + * `video/mp4` - The video is in MP4 format. + * `video/webm` - The video is in WebM format. + * `vp6/x-video` - The video is in VP6 format. + enum: + - source + - video/mp4 + - video/webm + - vp6/x-video + example: source + nullable: true + type: string + width: + description: The width in pixels of the video. + example: 1280 + nullable: true + type: number + required: + - created_time + - fps + - height + - link + - link_expiration_time + - md5 + - size + - type + - width + type: object + type: array + status: + description: | + The play status of the video: + + Option descriptions: + * `playable` - The video is playable. + * `purchase_required` - The video must be purchased. + * `restricted` - Playback for the video is restricted. + * `unavailable` - The video is unavailable. + enum: + - playable + - purchase_required + - restricted + - unavailable + example: playable + type: string + required: + - status + title: Play + type: object + portfolio: + properties: + created_time: + description: The time in ISO 8601 format when the portfolio was created. + example: 2017-05-16T19:56:07+00:00 + type: string + description: + description: The portfolio's description. + example: The Vimeo Staff original productions. + nullable: true + type: string + link: + description: The link to the portfolio. + example: https://vimeopro.com/staff/originals + type: string + metadata: + description: Metadata about the album. + properties: + connections: + description: A list of resource URIs related to the album. + properties: + videos: + description: Information about the videos contained within this portfolio. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 18 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/portfolios/12345/videos + type: string + required: + - options + - total + - uri + type: object + required: + - videos + type: object + required: + - connections + type: object + modified_time: + description: The time in ISO 8601 format when the portfolio's data was last modified. + example: 2017-05-17T19:56:07+00:00 + type: string + name: + description: The display name of the portfolio. + example: Vimeo Originals! + type: string + sort: + description: | + The default video sort order for the portfolio: + + Option descriptions: + * `alphabetical` - The default sort order is alphabetical by name. + * `clips` - The default sort order is video creation date. + * `modified` - The default sort order is the order in which the videos were modified. + * `recent` - The default sort order is the order in which the videos were added. + enum: + - alphabetical + - clips + - modified + - recent + example: alphabetical + type: string + uri: + description: The canonical relative URI of the portfolio. + example: /users/152184/portfolios/12345 + type: string + required: + - created_time + - description + - link + - metadata + - modified_time + - name + - sort + - uri + title: Portfolio + type: object + presets: + properties: + metadata: + description: Metadata about the album. + properties: + connections: + description: A list of resource URIs related to the album. + properties: + videos: + description: Information about the videos in this preset. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 13 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/presets/12345/videos + type: string + required: + - options + - total + - uri + type: object + required: + - videos + type: object + required: + - connections + type: object + name: + description: The display name of the presets group. + example: Minimalism + type: string + settings: + description: The contents of the presets group. + properties: + buttons: + properties: + embed: + description: Whether the preset includes Embed button settings. + example: "true" + type: boolean + hd: + description: Whether the preset includes HD button settings. + example: "true" + type: boolean + like: + description: Whether the preset includes Like button settings. + example: "true" + type: boolean + share: + description: Whether the present includes Share button settings. + example: "true" + type: boolean + vote: + description: Whether the preset includes Vote button settings. + example: "true" + type: boolean + watchlater: + description: Whether the preset includes Watch Later button settings. + example: "true" + type: boolean + required: + - embed + - hd + - like + - share + - vote + - watchlater + type: object + logos: + properties: + custom: + description: Whether the preset includes custom logo settings. + example: "true" + type: boolean + sticky_custom: + description: Whether the present includes sticky custom logo settings. + example: "true" + type: boolean + vimeo: + description: Whether the preset includes Vimeo logo settings. + example: "true" + type: boolean + required: + - custom + - sticky_custom + - vimeo + type: object + outro: + properties: + clips: + description: A comma-separated list of video URIs. Present only if the type is `uploaded_clips`. + example: /videos/258684937,/videos/273576296 + nullable: true + type: string + link: + description: The outro link settings. Present only if the type is `link`. + nullable: true + properties: + name: + description: The name of the outro link. + example: Example Outro + type: string + url: + description: The URL of the outro link. + example: https://example.com + type: string + type: object + text: + description: The outro text. Present only if the type is `text`. + example: Lorem ipsum dolor sit amet, consectetur adipiscing elit. + nullable: true + type: string + type: + description: "The preset outro type:" + enum: + - link + - no idea + - text + - uploaded_clips + - uploaded_videos + example: link + type: string + videos: + description: A comma-separated list of video URIs. Present only if type is `no idea`. + example: /videos/258684937,/videos/273576296 + nullable: true + type: string + required: + - type + type: object + required: + - buttons + - logos + - outro + type: object + uri: + description: The canonical relative URI of the presets object. + example: /users/152184/presets/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the preset. + nullable: true + required: + - metadata + - name + - settings + - uri + - user + title: Presets + type: object + project: + properties: + created_time: + description: The time in ISO 8601 format when the project was created. + example: 2017-05-23T14:36:22+00:00 + type: string + metadata: + description: The project's metadata. + properties: + connections: + description: A list of resource URIs related to the project. + properties: + videos: + description: A standard connection object indicating how to get all the videos in this project. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 12 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/projects/12345/videos + type: string + required: + - options + - total + - uri + type: object + required: + - videos + type: object + required: + - connections + type: object + modified_time: + description: The time in ISO 8601 format when the project was last modified. + example: 2017-05-23T14:36:22+00:00 + type: string + name: + description: The name of the folder. + example: Rough cuts + type: string + resource_key: + description: The resource key string of the project. + example: dc724af18fbdd4e59189f5fe768a5f8311527050 + type: string + uri: + description: The URI of the project. + example: /me/projects/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the project. + required: + - created_time + - metadata + - modified_time + - name + - resource_key + - uri + - user + title: Project + type: object + purchase-interaction: + properties: + buy: + description: Information on purchasing this video. + nullable: true + properties: + drm: + description: Whether the On Demand video for purchase has DRM. + example: "true" + type: boolean + type: object + rent: + description: Information on renting this video. + nullable: true + type: object + subscribe: + description: Information on subscribing to this video. + nullable: true + properties: + drm: + description: Whether the On Demand subscription has DRM. + example: "true" + type: boolean + expires_time: + description: The time in ISO 8601 format when the On Demand video will expire. + example: 2018-03-05T21:04:47+00:00 + nullable: true + type: string + link: + description: The URL to purchase this On Demand subscription on Vimeo. + example: https://vimeo.com/ondemand/darbyforever + nullable: true + type: string + purchase_time: + description: The time in ISO 8601 format when the On Demand was purchased. + example: 2018-03-05T21:04:47+00:00 + nullable: true + type: string + stream: + description: | + The user's streaming access to this On Demand subscription: + + Option descriptions: + * `available` - The On Demand subscription is available for streaming. + * `purchased` - The On Demand subscription has been purchased. + * `restricted` - Streaming for the On Demand subscription is restricted. + * `unavailable` - The On Demand subscription is unavailable. + enum: + - available + - purchased + - restricted + - unavailable + example: available + type: string + uri: + description: The On Demand subscription's product URI. + example: /ondemand/pages/61326/products/12345 + nullable: true + type: string + type: object + title: Purchase Interaction + type: object + tag: + properties: + canonical: + description: The normalized canonical tag name. + example: awesome + type: string + metadata: + description: Metadata about the group. + properties: + connections: + description: A collection of information that is connected to this resource. + properties: + videos: + description: Information about the videos related to this tag. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 34371 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /tags/awesome/videos + type: string + required: + - options + - total + - uri + type: object + required: + - videos + type: object + required: + - connections + type: object + name: + description: The tag value. + example: awesome + type: string + resource_key: + description: The tag's resource key string. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + uri: + description: The canonical relative URI of the tag. + example: /videos/258684937/tags/awesome + type: string + required: + - canonical + - metadata + - name + - resource_key + - uri + title: Tag + type: object + text-track: + properties: + active: + description: Whether this text track is active. + example: "true" + type: boolean + hls_link: + description: The read-only URL of the text track file, intended for use with HLS playback. + type: string + hls_link_expires_time: + description: The time in ISO 8601 format when the read-only HLS playback text track file expires. + example: "1494888499" + type: string + language: + description: |- + The language code for this text track. To see a full list, request + `/languages?filter=texttrack`. + example: en-US + nullable: true + type: string + link: + description: The read-only URL of the text track file. You can upload to this link when you create it for the first time. + type: string + link_expires_time: + description: The time in ISO 8601 format when the text track link expires. + example: "1494888499" + type: string + name: + description: The descriptive name of this text track. + example: English Subtitles + nullable: true + type: string + type: + description: | + The type of the text track: + + Option descriptions: + * `captions` - The text track is for captions. + * `subtitles` - The text track is for subtitles. + enum: + - captions + - subtitles + example: captions + nullable: true + type: string + uri: + description: The relative URI of the text track. + example: /videos/258684937/texttracks/12345 + type: string + required: + - active + - hls_link + - hls_link_expires_time + - language + - link + - link_expires_time + - name + - type + - uri + title: Text Track + type: object + upload-attempt: + properties: + clip: + allOf: + - $ref: "#/components/schemas/video" + description: The video to upload. + complete_uri: + description: The completion URI of the upload. + example: /users/152184/uploads/12345?video_file_id=5678&upgrade=true&signature=r394y347ffefeff434 + type: string + form: + description: The HTML upload form. + type: string + ticket_id: + description: The ticket identifier string for the upload. + example: 3da5dac09 + type: string + upload_link: + description: The upload URL. + example: https://123456.cloud.vimeo.com/upload?ticket_id=1234asdf + type: string + uri: + description: The upload URI. + example: /users/152184/uploads/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the uploaded video. + required: + - ticket_id + - upload_link + - uri + - user + title: Upload Attempt + type: object + user: + properties: + account: + description: | + The user's account type: + + Option descriptions: + * `basic` - The user has a Vimeo Basic subscription. + * `business` - The user has a Vimeo Business subscription. + * `live_business` - The user has a Vimeo Business Live subscription. + * `live_premium` - The user has a Vimeo Premium subscription. + * `live_pro` - The user has a Vimeo PRO Live subscription. + * `plus` - The user has a Vimeo Plus subscription. + * `pro` - The user has a Vimeo Pro subscription. + * `pro_unlimited` - The user has a Vimeo PRO Unlimited subscription. + * `producer` - The user has a Vimeo Producer subscription. + enum: + - basic + - business + - live_business + - live_premium + - live_pro + - plus + - pro + - pro_unlimited + - producer + example: basic + type: string + bio: + description: The user's bio. + example: This is where you will find videos and news updates from the staff. + nullable: true + type: string + content_filter: + description: | + The user's content filters: + + Option descriptions: + * `drugs` - Drugs or alcohol use. + * `language` - Profanity or sexually suggestive content. + * `nudity` - Nudity. + * `safe` - Suitable for all audiences. + * `unrated` - No rating. + * `violence` - Violent or graphic content. + enum: + - drugs + - language + - nudity + - safe + - unrated + - violence + example: drugs + items: + type: string + type: array + created_time: + description: The time in ISO 8601 format when the user account was created. + example: 2007-01-18T16:40:11+00:00 + type: string + email: + description: The user's email address. This data requires a bearer token with the `email` scope. + example: user@example.com + type: string + link: + description: The absolute URL of this user's profile page. + example: https://vimeo.com/staff + type: string + location: + description: The user's location. + example: New York City + nullable: true + type: string + metadata: + description: The user's metadata. + properties: + connections: + description: The list of resource URIs related to the user. + properties: + albums: + description: Information about the albums created by this user. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of albums on this connection. + example: 3 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/albums + type: string + required: + - options + - total + - uri + type: object + appearances: + description: Information about the appearances of this user in other videos. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of appearances on this connection. + example: 6 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/appearances + type: string + required: + - options + - total + - uri + type: object + block: + description: Information on the users that the current user has blocked. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + total: + description: The total number of blocked users on this connection. This data requires a bearer token with the `private` scope. + example: 73 + type: number + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /me/block + type: string + required: + - options + - total + - uri + type: object + categories: + description: Information about this user's followed categories. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of categories on this connection. + example: 5 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/categories + type: string + required: + - options + - total + - uri + type: object + channels: + description: Information about this user's subscribed channels. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of channels on this connection. + example: 4 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/channels + type: string + required: + - options + - total + - uri + type: object + feed: + description: Information about this user's feed. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/feed + type: string + required: + - options + - uri + type: object + folders: + description: Information about this user's folders. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of folders on this connection. + example: 9 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /me/folders + type: string + required: + - options + - total + - uri + type: object + followers: + description: Information about the user's followers. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of followers on this connection. + example: 12 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/followers + type: string + required: + - options + - total + - uri + type: object + following: + description: Information about the users that the current user is following. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of users on this connection. + example: 47 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/following + type: string + required: + - options + - total + - uri + type: object + groups: + description: Information about the groups created by this user. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of groups on this connection. + example: 2 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/groups + type: string + required: + - options + - total + - uri + type: object + likes: + description: Information about the videos that this user has liked. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of likes on this connection. + example: 300 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/likes + type: string + required: + - options + - total + - uri + type: object + moderated_channels: + description: Information about the channels that this user moderates. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of channels on this connection. + example: 1 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/channels?filter=moderated + type: string + required: + - options + - total + - uri + type: object + pictures: + description: Information about this user's portraits. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of pictures on this connection. + example: 3 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/pictures + type: string + required: + - options + - total + - uri + type: object + portfolios: + description: Information about this user's portfolios. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of portfolios on this connection. + example: 5 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/portfolios + type: string + required: + - options + - total + - uri + type: object + recommended_channels: + description: A collection of recommended channels for the current user to follow. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + total: + description: The total number of channels on this connection. This data requires a bearer token with the `private` scope. + example: 4 + type: number + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /me/recommendations/channels + type: string + required: + - options + - total + - uri + type: object + recommended_users: + description: A Collection of recommended users for the current user to follow. This data requires a bearer token with the `private` scope. + properties: + options: + description: An array of HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + total: + description: The total number of users on this connection. This data requires a bearer token with the `private` scope. + example: 6 + type: number + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /me/recommendations/users + type: string + required: + - options + - total + - uri + type: object + shared: + description: Information about the videos that have been shared with this user. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 15 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/shared/videos + type: string + required: + - options + - total + - uri + type: object + videos: + description: Information about the videos uploaded by this user. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 36 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/videos + type: string + required: + - options + - total + - uri + type: object + watched_videos: + description: Information about the videos that this user has watched. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 322 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /me/watched/videos + type: string + required: + - options + - total + - uri + type: object + watchlater: + description: Information about the videos that this user wants to watch later. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 14 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/watchlater + type: string + required: + - options + - total + - uri + type: object + required: + - albums + - appearances + - block + - categories + - channels + - feed + - folders + - followers + - following + - groups + - likes + - moderated_channels + - pictures + - portfolios + - recommended_channels + - recommended_users + - shared + - videos + - watched_videos + - watchlater + type: object + interactions: + properties: + add_privacy_user: + properties: + options: + description: An array of the HTTP methods permitted on this URI. This data requires a bearer token with the `private` scope. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. This data requires a bearer token with the `private` scope. + example: /channels/152184/privacy/users + type: string + type: object + block: + description: Information related to the block status of this user. + properties: + added: + description: Whether a user is blocking the current user. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the block occurred, or the null value if no block exists. + example: 2017-05-16T15:05:43+00:00 + nullable: true + type: string + options: + description: An array of the HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The URI to block or unblock the user. + example: /me/block/3766357 + type: string + required: + - added + - added_time + - options + - uri + type: object + follow: + description: Information related to the followed status of this user. + properties: + added: + description: Whether a user is following the current user. + example: "true" + type: boolean + options: + description: An array of the HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The URI to follow the user. + example: /users/152184/following/3766357 + type: string + required: + - added + - options + - uri + type: object + report: + description: Information regarding where and how to report a user. + properties: + options: + description: An array of the HTTP methods permitted on this URI. + items: + type: string + type: array + reason: + description: List of valid reasons for reporting a video. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /users/152184/report + type: string + required: + - options + - reason + - uri + type: object + required: + - block + - follow + - report + type: object + required: + - connections + - interactions + type: object + name: + description: The user's display name. + example: Vimeo Staff + type: string + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active portrait of this user. + preferences: + properties: + videos: + properties: + privacy: + properties: + add: + description: Whether other users can add the user's videos. + example: "true" + type: boolean + comments: + description: | + The user's privacy preference for comments: + + Option descriptions: + * `anybody` - Anyone can comment on the user's videos. + * `contacts` - Only contacts can comment on the user's videos. + * `nobody` - No one can comment on the user's videos. + enum: + - anybody + - contacts + - nobody + example: anybody + type: string + download: + description: Whether other users can download the user's videos. + example: "true" + type: boolean + embed: + description: | + The user's privacy preference for embeds: + + Option descriptions: + * `private` - Only the user can embed their own videos. + * `public` - Anyone can embed the user's videos. + * `whitelist` - Only those on the whitelist can embed the user's videos. + enum: + - private + - public + - whitelist + example: private + type: string + view: + description: | + The user's privacy preference for views: + + Option descriptions: + * `anybody` - Anyone can view the user's videos. + * `contacts` - Only contacts can view the user's videos. + * `disable` - Views are disabled for the user's videos. + * `nobody` - No one except the user can view the user's videos. + * `password` - Only those with the password can view the user's videos. + * `unlisted` - Anybody can view the user's videos if they have a link. + * `users` - Only other Vimeo members can view the user's videos. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + example: anybody + type: string + type: object + type: object + type: object + resource_key: + description: The user's resource key string. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + upload_quota: + description: Appears only when the user has upload access and is looking at their own user record. + properties: + lifetime: + description: Information about the user's lifetime upload usage. + properties: + free: + description: The number of bytes remaining in your lifetime maximum. + example: 5000000 + nullable: true + type: number + max: + description: The total number of bytes that you can upload across the lifetime of your account. + example: 5368709120 + nullable: true + type: number + used: + description: The number of bytes that you've already uploaded against your lifetime limit. + example: 5368704120 + nullable: true + type: number + required: + - free + - max + - used + type: object + periodic: + description: Information about the user's usage for the current period. + properties: + free: + description: The number of bytes remaining in your upload quota for the current period. + example: 5000000 + nullable: true + type: number + max: + description: The total number of bytes that you can upload per period. + example: 5368709120 + nullable: true + type: number + reset_date: + description: The time in ISO 8601 format when your upload quota resets. + example: 2029-03-13T02:35:13-04:00 + nullable: true + type: string + used: + description: The number of bytes that you've already uploaded against your quota in the current period. + example: 5368704120 + nullable: true + type: number + required: + - free + - max + - reset_date + - used + type: object + space: + description: Information about the user's upload space remaining for the current period. + properties: + free: + description: The number of bytes remaining in your upload quota. + example: 5000000 + type: number + max: + description: The maximum number of bytes allotted to your upload quota. + example: 5368709120 + nullable: true + type: number + showing: + description: Whether the values of the upload_quota.space fields are for the lifetime quota or the periodic quota. + enum: + - lifetime + - periodic + example: lifetime + type: string + used: + description: The number of bytes that you've already uploaded against your quota. + example: 5368704120 + type: number + required: + - free + - max + - showing + - used + type: object + required: + - lifetime + - periodic + - space + type: object + uri: + description: The user's canonical relative URI. + example: /users/152184 + type: string + websites: + description: The user's websites. + items: + properties: + description: + description: The website's description. + example: Follow us on Twitter! + nullable: true + type: string + link: + description: The URL of the website. + example: https://twitter.com/vimeo + type: string + name: + description: The name of the website. + example: Twitter + nullable: true + type: string + required: + - description + - link + - name + type: object + type: array + required: + - account + - bio + - created_time + - link + - location + - metadata + - name + - pictures + - resource_key + - upload_quota + - uri + - websites + title: User + type: object + video: + properties: + categories: + description: The categories to which this video belongs. + items: + $ref: "#/components/schemas/category" + type: array + content_rating: + description: The content ratings of this video. + items: + type: string + type: array + context: + description: The context of the video's subscription, if this video is part of a subscription. + properties: + action: + description: | + The contextual action: + + Option descriptions: + * `Added to` - An Added To action. + * `Appearance by` - An Appearance By action. + * `Liked by` - A Liked By action. + * `Uploaded by` - An Unloaded By action. + enum: + - Added to + - Appearance by + - Liked by + - Uploaded by + example: Added to + type: string + resource: + description: "The contextual resource: a user, group, or channel representation, or an object of a tag." + nullable: true + type: object + resource_type: + description: The contextual resource type. + example: clip + type: string + required: + - action + - resource + - resource_type + type: object + created_time: + description: The time in ISO 8601 format when the video was created. + example: 2018-03-05T21:04:47+00:00 + type: string + description: + description: A brief explanation of the video's content. + example: A celebration of 10 years of Staff Picks. + nullable: true + type: string + duration: + description: The video's duration in seconds. + example: 81 + type: number + embed: + allOf: + - $ref: "#/components/schemas/embed-settings" + description: Information about embedding this video. + height: + description: The video's height in pixels. + example: 1080 + type: number + language: + description: The video's primary language. + example: en-US + nullable: true + type: string + last_user_action_event_date: + description: The time in ISO 8601 format when the user last modified the video. + example: 2018-03-21T23:08:22+00:00 + nullable: true + type: string + license: + description: | + The [Creative Commons](http://creativecommons.org/licenses/) license used for the video: + + Option descriptions: + * `by` - Attribution + * `by-nc` - Attribution Non-Commercial + * `by-nc-nd` - Attribution Non-Commercial No Derivatives + * `by-nc-sa` - Attribution Non-Commercial Share Alike + * `by-nd` - Attribution No Derivatives + * `by-sa` - Attribution Share Alike + * `cc0` - Public Domain Dedication + enum: + - by + - by-nc + - by-nc-nd + - by-nc-sa + - by-nd + - by-sa + - cc0 + example: by + type: string + link: + description: The link to the video. + example: https://vimeo.com/258684937 + type: string + metadata: + description: The video's metadata. + properties: + connections: + description: A list of resource URIs related to the video. + properties: + comments: + description: Information about the comments on this video. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of comments on this connection. + example: 14 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/comments + type: string + required: + - options + - total + - uri + type: object + credits: + description: Information about the users credited in this video. + nullable: true + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of users on this connection. + example: 4 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/credits + type: string + type: object + likes: + description: Information about the users who have liked this video. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of likes on this connection. + example: 230 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/likes + type: string + required: + - options + - total + - uri + type: object + ondemand: + description: Information about this video's ondemand data. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + resource_key: + description: The On Demand connection resource key. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326 + type: string + required: + - options + - resource_key + - uri + type: object + pictures: + description: Information about this video's thumbnails. + properties: + options: + description: An array of HTTP methods allowed on this URI. + items: + type: string + type: array + total: + description: Total number of thumbnails on this connection. + example: 1 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/pictures + type: string + required: + - options + - total + - uri + type: object + playback: + description: The DRM playback status connection for this video. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/playback + type: string + required: + - options + - uri + type: object + recommendations: + description: The recommendations for this video. + nullable: true + properties: + options: + description: An array of HTTP methods allowed on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/recommendations + type: string + type: object + related: + description: Related content for this video. + nullable: true + properties: + options: + description: An array of HTTP methods allowed on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937?offset=10 + type: string + type: object + season: + description: Information about the video's season. + properties: + name: + description: The name of this season. + example: Season 1 + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/season/12345 + type: string + required: + - name + - options + - uri + type: object + texttracks: + description: Information about this video's text tracks. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of text tracks on this connection. + example: 2 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/texttracks + type: string + required: + - options + - total + - uri + type: object + trailer: + description: Information about this video's VOD trailer. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + resource_key: + description: The trailer connection resource key. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + uri: + description: The API URI that resolves to the connection data. + example: /ondemand/pages/61326/videos/12345 + type: string + required: + - options + - resource_key + - uri + type: object + users_with_access: + description: Information about the user privacy of this video, if the video privacy is `users`. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of users on this connection. + example: 8 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/privacy/users + type: string + required: + - options + - total + - uri + type: object + versions: + description: Information about the versions of this video. + properties: + current_uri: + description: The URI of the current version of the video. + example: /videos/258684937/versions/12345 + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of versions on this connection. + example: 3 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937/versions + type: string + required: + - options + - total + - uri + type: object + required: + - comments + - credits + - likes + - ondemand + - pictures + - playback + - recommendations + - related + - season + - texttracks + - trailer + - users_with_access + - versions + type: object + interactions: + description: A list of resource URIs related to the video. + properties: + buy: + description: The Buy interaction for a On Demand video. + nullable: true + properties: + currency: + description: The currency code for the current user's region. + example: USD + nullable: true + type: string + display_price: + description: Formatted price to display to buy an On Demand video. + example: "5.99" + nullable: true + type: string + download: + description: | + The user's download access to this On Demand video: + + Option descriptions: + * `available` - The video is available for download. + * `purchased` - The user has purchased the video. + * `restricted` - The user isn't permitted to download the video. + * `unavailable` - The video isn't available for download. + enum: + - available + - purchased + - restricted + - unavailable + example: available + type: string + drm: + description: Whether the video has DRM. + example: "true" + type: boolean + link: + description: The URL to buy the On Demand video on Vimeo. + example: https://vimeo.com/ondemand/darbyforever + nullable: true + type: string + price: + description: The numeric value of the price for buying the On Demand video. + example: 5.99 + nullable: true + type: number + purchase_time: + description: The time in ISO 8601 format when the On Demand video was purchased. + example: 2018-03-05T21:04:47+00:00 + nullable: true + type: string + stream: + description: | + The user's streaming access to this On Demand video: + + Option descriptions: + * `available` - The video is available for streaming. + * `purchased` - The user has purchased the video. + * `restricted` - The user isn't permitted to stream the video. + * `unavailable` - The video isn't available for streaming + enum: + - available + - purchased + - restricted + - unavailable + example: available + type: string + uri: + description: The product URI to purchase the On Demand video. + example: /ondemand/pages/61326/products/12345 + nullable: true + type: string + required: + - currency + - display_price + - download + - drm + - link + - price + - purchase_time + - stream + - uri + type: object + channel: + description: When a video is referenced by a channel URI, if the user is a moderator of the channel, include information about removing the video from the channel. + nullable: true + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + type: string + required: + - options + - uri + type: object + like: + description: Information about whether the authenticated user has liked this video. + properties: + added: + description: Whether the user has liked the video. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the user liked the video. + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + type: string + required: + - added + - added_time + - options + - uri + type: object + rent: + description: The Rent interaction for an On Demand video. + nullable: true + properties: + currency: + description: The currency code for the current user's region. + example: USD + nullable: true + type: string + display_price: + description: Formatted price to display to rent an On Demand video. + example: "5.99" + nullable: true + type: string + drm: + description: Whether the video has DRM. + example: "true" + type: boolean + expires_time: + description: The time in ISO 8601 format when the rental period for the video expires. + example: 2018-03-05T21:04:47+00:00 + nullable: true + type: string + link: + description: The URL to rent the On Demand video on Vimeo. + example: https://vimeo.com/ondemand/darbyforever + nullable: true + type: string + price: + description: The numeric value of the price for buying the On Demand video. + example: 5.99 + nullable: true + type: number + purchase_time: + description: The time in ISO 8601 format when the On Demand video was rented. + example: 2018-09-16T09:02:40+00:00 + nullable: true + type: string + stream: + description: | + The user's streaming access to this On Demand video: + + Option descriptions: + * `available` - The video is available for streaming. + * `purchased` - The user has purchased the video. + * `restricted` - The user isn't permitted to stream the video. + * `unavailable` - The video isn't available for streaming. + enum: + - available + - purchased + - restricted + - unavailable + example: available + type: string + uri: + description: The product URI to rent the On Demand video. + example: /ondemand/pages/61326/products/12345 + nullable: true + type: string + required: + - currency + - display_price + - drm + - expires_time + - link + - price + - purchase_time + - stream + - uri + type: object + report: + description: Information about where and how to report a video. + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + reason: + description: A list of valid reasons for reporting a video. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + type: string + required: + - options + - reason + - uri + type: object + subscribe: + description: Subscription information for an On Demand video. + nullable: true + properties: + drm: + description: Whether the video has DRM. + example: "true" + type: boolean + expires_time: + description: The time in ISO 8601 format when the subscription expires. + example: 2018-03-05T21:04:47+00:00 + type: string + purchase_time: + description: The tine in ISO 8601 format when the subscription was purchased. + example: 2018-03-02T21:04:47+00:00 + type: string + stream: + description: The stream type. + example: purchased + type: string + type: object + watched: + description: Information about removing this video from the user's list of watched videos. + properties: + added: + description: Whether the user has watched the video. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the user watched the video. + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + type: string + required: + - added + - added_time + - options + - uri + type: object + watchlater: + description: Information about whether this video appears on the authenticated user's Watch Later list. + properties: + added: + description: Whether the user has added the video to their Watch later list. + example: "true" + type: boolean + added_time: + description: The time in ISO 8601 format when the user added the video to their Watch Later list. + type: string + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + uri: + description: The API URI that resolves to the connection data. + type: string + required: + - added + - added_time + - options + - uri + type: object + required: + - buy + - channel + - like + - rent + - report + - watched + - watchlater + type: object + required: + - connections + - interactions + type: object + modified_time: + description: The time in ISO 8601 format when the video metadata was last modified. + example: 2018-09-16T09:02:40+00:00 + type: string + name: + description: The video's title. + example: Celebrating 10 Years of Staff Picks + type: string + parent_folder: + allOf: + - $ref: "#/components/schemas/project" + description: Information about the folder that contains this video. + nullable: true + password: + description: The privacy-enabled password to watch this video. Only users can see their own video passwords. This data requires a bearer token with the `private` scope. + example: hunter1 + type: string + pictures: + allOf: + - $ref: "#/components/schemas/picture" + description: The active picture for this video. + privacy: + description: The video's privacy setting. + properties: + add: + description: Whether the video can be added to collections. + example: "true" + type: boolean + comments: + description: | + Who can comment on the video: + + Option descriptions: + * `anybody` - Anyone can comment on the video. + * `contacts` - Only contacts can comment on the video. + * `nobody` - No one can comment on the video. + enum: + - anybody + - contacts + - nobody + example: anybody + type: string + download: + description: The video's download permission setting. + example: "true" + type: boolean + embed: + description: | + The video's embed permission setting: + + Option descriptions: + * `private` - The video is private. + * `public` - Anyone can embed the video. + enum: + - private + - public + example: private + type: string + view: + description: | + The general privacy setting for the video: + + Option descriptions: + * `anybody` - Anyone can view the video. + * `contacts` - Only contacts can view the video. + * `disable` - Hide from vimeo + * `nobody` - No one besides the owner can view the video. + * `password` - Anyone with the video's password can view the video. + * `unlisted` - Not searchable from vimeo.com + * `users` - Only people with a Vimeo account can view the video. + enum: + - anybody + - contacts + - disable + - nobody + - password + - unlisted + - users + example: anybody + type: string + required: + - add + - comments + - download + - embed + - view + type: object + release_time: + description: The time in ISO 8601 format when the video was released. + example: 2018-03-05T21:04:47+00:00 + type: string + resource_key: + description: The resource key string of the video. + example: bac1033deba2310ebba2caec33c23e4beea67aba + type: string + spatial: + description: 360 spatial data. + properties: + director_timeline: + description: 360 director timeline. + items: + properties: + pitch: + description: The director timeline pitch, from -90 (minimum) to 90 (maximum). + example: 70 + type: number + roll: + description: The director timeline roll. + example: 0 + type: number + time_code: + description: The director timeline time code. + example: 300 + type: number + yaw: + description: The director timeline yaw, from 0 (minimum) to 360 (maximum). + example: 125 + type: number + type: object + type: array + field_of_view: + description: The 360 field of view, from 30 (minimum) to 90 (maximum). The default is 50. + example: 50 + nullable: true + type: number + projection: + description: | + The 360 spatial projection: + + Option descriptions: + * `cubical` - The spatial projection is cubical. + * `cylindrical` - The spatial projection is cylindrical. + * `dome` - The spatial projection is dome-shaped. + * `equirectangular` - The spatial projection is equirectangular. + * `pyramid` - The spatial projection is pyramid-shaped. + enum: + - cubical + - cylindrical + - dome + - equirectangular + - pyramid + example: cubical + nullable: true + type: string + stereo_format: + description: | + The 360 stereo format: + + Option descriptions: + * `left-right` - The stereo format is left-right. + * `mono` - The audio is monaural. + * `top-bottom` - The stereo format is top-bottom. + enum: + - left-right + - mono + - top-bottom + example: left-right + nullable: true + type: string + required: + - director_timeline + - field_of_view + - projection + - stereo_format + type: object + stats: + description: A collection of stats associated with this video. + properties: + plays: + description: The current total number of times that the video has been played. + example: 20 + nullable: true + type: number + required: + - plays + type: object + status: + description: | + The status code for the availability of the video. This field is deprecated in favor of `upload` and `transcode`. + + Option descriptions: + * `available` - The video is available. + * `quota_exceeded` - The user's quota is exceeded with this video. + * `total_cap_exceeded` - The user has exceeded their total cap with this video. + * `transcode_starting` - Transcoding is beginning for the video. + * `transcoding` - Transcoding is underway for the video. + * `transcoding_error` - There was an error in transcoding the video. + * `unavailable` - The video is unavailable. + * `uploading` - The video is being uploaded. + * `uploading_error` - There was an error in uploading the video. + enum: + - available + - quota_exceeded + - total_cap_exceeded + - transcode_starting + - transcoding + - transcoding_error + - unavailable + - uploading + - uploading_error + example: available + nullable: true + type: string + tags: + description: An array of all tags assigned to this video. + items: + $ref: "#/components/schemas/tag" + type: array + transcode: + description: The transcode information for a video upload. + nullable: true + properties: + status: + description: Status code for this video's availability. + enum: + - complete + - error + - in_progress + example: complete + type: string + type: object + upload: + description: The upload information for this video. + nullable: true + properties: + approach: + description: The approach for uploading the video. + enum: + - post + - pull + - streaming + - tus + example: post + type: string + complete_uri: + description: The URI for completing the upload. + type: string + form: + description: The HTML form for uploading a video through the post approach. + type: string + link: + description: The link of the video to capture through the pull approach. + type: string + redirect_url: + description: The redirect URL for the upload app. + type: string + size: + description: The file size in bytes of the uploaded video. + example: 60000 + type: number + status: + description: | + The status code for the availability of the uploaded video: + + Option descriptions: + * `complete` - The upload is complete. + * `error` - The upload ended with an error. + * `in_progress` - The upload is underway. + enum: + - complete + - error + - in_progress + example: complete + type: string + upload_link: + description: The link for sending video file data. + type: string + required: + - status + type: object + uri: + description: The video's canonical relative URI. + example: /videos/258684937 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The video owner. + nullable: true + width: + description: The video's width in pixels. + example: 1920 + type: number + required: + - categories + - content_rating + - context + - created_time + - description + - duration + - embed + - height + - language + - license + - link + - metadata + - modified_time + - name + - pictures + - privacy + - release_time + - resource_key + - spatial + - stats + - status + - tags + - transcode + - upload + - uri + - user + - width + title: Video + type: object + video-versions: + properties: + active: + description: Whether this video version is the currently active one. + example: "true" + type: boolean + app: + allOf: + - $ref: "#/components/schemas/api-app" + description: The API app associated with the video version. + created_time: + description: The time in ISO 8601 for when the video version was created. + example: 2018-03-05T21:04:47+00:00 + type: string + duration: + description: The duration of the video version in seconds. + example: 81 + nullable: true + type: number + filename: + description: The file name of the video version. + example: rev2.mp4 + type: string + filesize: + description: The size in byes of the video version file. + example: 4025322521 + nullable: true + type: number + metadata: + description: The video version's metadata. + properties: + connections: + properties: + video: + description: Data from video associated with version + properties: + options: + description: An array of HTTP methods permitted on this URI. + items: + type: string + type: array + total: + description: The total number of videos on this connection. + example: 5 + type: number + uri: + description: The API URI that resolves to the connection data. + example: /videos/258684937 + type: string + required: + - options + - total + - uri + type: object + required: + - video + type: object + required: + - connections + type: object + modified_time: + description: The time in ISO 8601 format when the video version was last modified. + example: 2018-09-16T09:02:40+00:00 + type: string + play: + allOf: + - $ref: "#/components/schemas/play" + description: The Play representation. + upload: + description: The upload information for this version. + nullable: true + properties: + approach: + description: The approach for uploading the video. + enum: + - post + - pull + - streaming + - tus + example: post + type: string + complete_uri: + description: The URI for completing the upload. + type: string + form: + description: The HTML form for uploading a video through the post approach. + type: string + link: + description: The link of the video to capture through the pull approach. + type: string + redirect_url: + description: The redirect URL for the upload app. + type: string + size: + description: The file size in bytes of the uploaded video. + example: 60000 + type: number + status: + description: | + The status code for the availability of the uploaded video: + + Option descriptions: + * `complete` - The upload is complete. + * `error` - The upload ended with an error. + * `in_progress` - The upload is underway. + enum: + - complete + - error + - in_progress + example: complete + type: string + upload_link: + description: The link for sending video file data. + type: string + required: + - status + type: object + upload_date: + description: The time in ISO 8601 format when the video version was uploaded. + example: 2018-09-16T09:02:40+00:00 + nullable: true + type: string + uri: + description: The version's canonical relative URI. + example: /videos/258684937/versions/12345 + type: string + user: + allOf: + - $ref: "#/components/schemas/user" + description: The owner of the video version. + nullable: true + required: + - active + - app + - created_time + - duration + - filename + - filesize + - metadata + - modified_time + - play + - upload + - upload_date + - uri + - user + title: Video Versions + type: object + securitySchemes: + bearer: + bearerFormat: bearer + scheme: bearer + type: http + oauth2: + flows: + authorizationCode: + authorizationUrl: /oauth/authorize + scopes: + create: Create new albums, channels, and so on + delete: Delete videos, albums, channels, and so on + edit: Edit existing videos, albums, channels, and so on + email: Access to email addresses + interact: Interact with Vimeo resources on a member's behalf, such as liking a video or following another member + private: Access private member data + promo_codes: Add, remove, and review Vimeo On Demand promotions + public: Access public member data + purchase: Purchase content + purchased: Access a member's Vimeo On Demand purchase history + stats: Access video stats + upload: Upload videos + video_files: Access video files belonging to members with a PRO subscription or higher + tokenUrl: https://api.vimeo.com/oauth/access_token + clientCredentials: + scopes: + create: Create new albums, channels, and so on + delete: Delete videos, albums, channels, and so on + edit: Edit existing videos, albums, channels, and so on + email: Access to email addresses + interact: Interact with Vimeo resources on a member's behalf, such as liking a video or following another member + private: Access private member data + promo_codes: Add, remove, and review Vimeo On Demand promotions + public: Access public member data + purchase: Purchase content + purchased: Access a member's Vimeo On Demand purchase history + stats: Access video stats + upload: Upload videos + video_files: Access video files belonging to members with a PRO subscription or higher + tokenUrl: https://api.vimeo.com/oauth/access_token + type: oauth2 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/ynab.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/ynab.yaml new file mode 100644 index 000000000..4ed0ab178 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/ynab.yaml @@ -0,0 +1,2712 @@ +openapi: 3.0.1 +info: + x-ballerina-display: + label: YNAB + iconPath: "icon.png" + title: YNAB API Endpoints + description: | + This is a generated connector for [YNAB API v1.0.0](https://api.youneedabudget.com) OpenAPI specification. + YNAB API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. + We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. + API Documentation is at https://api.youneedabudget.com + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Create a [YNAB account](https://app.youneedabudget.com) and obtain tokens by following [this guide](https://api.youneedabudget.com/#quick-start). + version: 1.0.0 +servers: + - url: https://api.youneedabudget.com/v1 +security: + - bearerAuth: [] +tags: + - name: User + - name: Budgets + - name: Accounts + description: The accounts for a budget + - name: Categories + description: The categories for a budget + - name: Payees + description: The payees for a budget + - name: Payee Locations + description: When you enter a transaction and specify a payee on the YNAB mobile + apps, the GPS coordinates for that location are stored, with your permission, + so that the next time you are in the same place (like the Grocery store) we can + pre-populate nearby payees for you! It’s handy and saves you time. This resource + makes these locations available. Locations will not be available for all payees. + - name: Months + description: Each budget contains one or more months, which is where Ready to Assign, + Age of Money and category (budgeted / activity / balances) amounts are available. + - name: Transactions + description: The transactions for a budget + - name: Scheduled Transactions + description: The scheduled transactions for a budget +paths: + /user: + get: + tags: + - User + summary: User info + description: Returns authenticated user information + operationId: getUser + responses: + 200: + description: The user info + content: + application/json: + schema: + $ref: '#/components/schemas/UserResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets: + get: + tags: + - Budgets + summary: List budgets + description: Returns budgets list with summary information + operationId: getBudgets + parameters: + - name: include_accounts + in: query + description: Whether to include the list of budget accounts + schema: + type: boolean + responses: + 200: + description: The list of budgets + content: + application/json: + schema: + $ref: '#/components/schemas/BudgetSummaryResponse' + 404: + description: No budgets were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}: + get: + tags: + - Budgets + summary: Single budget + description: Returns a single budget with all related entities. This resource + is effectively a full budget export. + operationId: getBudgetById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The requested budget + content: + application/json: + schema: + $ref: '#/components/schemas/BudgetDetailResponse' + 404: + description: The specified budget was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/settings: + get: + tags: + - Budgets + summary: Budget Settings + description: Returns settings for a budget + operationId: getBudgetSettingsById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + responses: + 200: + description: The requested budget settings + content: + application/json: + schema: + $ref: '#/components/schemas/BudgetSettingsResponse' + 404: + description: The specified Budget was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/accounts: + get: + tags: + - Accounts + summary: Account list + description: Returns all accounts + operationId: getAccounts + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of requested accounts + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponse' + 404: + description: No accounts were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + post: + tags: + - Accounts + summary: Create a new account + description: Creates a new account + operationId: createAccount + parameters: + - name: budget_id + in: path + description: 'The id of the budget ("last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget)' + required: true + schema: + type: string + requestBody: + description: The account to create. + content: + '*/*': + schema: + $ref: '#/components/schemas/SaveAccountWrapper' + required: true + responses: + 201: + description: The account was successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/AccountResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s). + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-codegen-request-body-name: data + /budgets/{budget_id}/accounts/{account_id}: + get: + tags: + - Accounts + summary: Single account + description: Returns a single account + operationId: getAccountById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: account_id + in: path + description: The id of the account + required: true + schema: + type: string + format: uuid + responses: + 200: + description: The requested account + content: + application/json: + schema: + $ref: '#/components/schemas/AccountResponse' + 404: + description: The requested account was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/categories: + get: + tags: + - Categories + summary: List categories + description: Returns all categories grouped by category group. Amounts (budgeted, + activity, balance, etc.) are specific to the current budget month (UTC). + operationId: getCategories + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The categories grouped by category group + content: + application/json: + schema: + $ref: '#/components/schemas/CategoriesResponse' + 404: + description: No categories were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/categories/{category_id}: + get: + tags: + - Categories + summary: Single category + description: Returns a single category. Amounts (budgeted, activity, balance, + etc.) are specific to the current budget month (UTC). + operationId: getCategoryById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: category_id + in: path + description: The id of the category + required: true + schema: + type: string + responses: + 200: + description: The requested category + content: + application/json: + schema: + $ref: '#/components/schemas/CategoryResponse' + 404: + description: The category not was found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/months/{month}/categories/{category_id}: + get: + tags: + - Categories + summary: Single category for a specific budget month + description: Returns a single category for a specific budget month. Amounts + (budgeted, activity, balance, etc.) are specific to the current budget month + (UTC). + operationId: getMonthCategoryById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: month + in: path + description: The budget month in ISO format (e.g. 2016-12-01) ("current" can + also be used to specify the current calendar month (UTC)) + required: true + schema: + type: string + format: date + - name: category_id + in: path + description: The id of the category + required: true + schema: + type: string + responses: + 200: + description: The requested month category + content: + application/json: + schema: + $ref: '#/components/schemas/CategoryResponse' + 404: + description: The month category was not was found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + patch: + tags: + - Categories + summary: Update a category for a specific month + description: Update a category for a specific month. Only `budgeted` amount + can be updated. + operationId: updateMonthCategory + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: month + in: path + description: The budget month in ISO format (e.g. 2016-12-01) ("current" can + also be used to specify the current calendar month (UTC)) + required: true + schema: + type: string + format: date + - name: category_id + in: path + description: The id of the category + required: true + schema: + type: string + requestBody: + description: The category to update. Only `budgeted` amount can be updated + and any other fields specified will be ignored. + content: + '*/*': + schema: + $ref: '#/components/schemas/SaveMonthCategoryWrapper' + required: true + responses: + 200: + description: The month category was successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/SaveCategoryResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-codegen-request-body-name: data + /budgets/{budget_id}/payees: + get: + tags: + - Payees + summary: List payees + description: Returns all payees + operationId: getPayees + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The requested list of payees + content: + application/json: + schema: + $ref: '#/components/schemas/PayeesResponse' + 404: + description: No payees were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/payees/{payee_id}: + get: + tags: + - Payees + summary: Single payee + description: Returns a single payee + operationId: getPayeeById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: payee_id + in: path + description: The id of the payee + required: true + schema: + type: string + responses: + 200: + description: The requested payee + content: + application/json: + schema: + $ref: '#/components/schemas/PayeeResponse' + 404: + description: The payee was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/payee_locations: + get: + tags: + - Payee Locations + summary: List payee locations + description: Returns all payee locations + operationId: getPayeeLocations + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + responses: + 200: + description: The list of payee locations + content: + application/json: + schema: + $ref: '#/components/schemas/PayeeLocationsResponse' + 404: + description: No payees locations were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/payee_locations/{payee_location_id}: + get: + tags: + - Payee Locations + summary: Single payee location + description: Returns a single payee location + operationId: getPayeeLocationById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: payee_location_id + in: path + description: id of payee location + required: true + schema: + type: string + responses: + 200: + description: The payee location + content: + application/json: + schema: + $ref: '#/components/schemas/PayeeLocationResponse' + 404: + description: The payee location was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/payees/{payee_id}/payee_locations: + get: + tags: + - Payee Locations + summary: List locations for a payee + description: Returns all payee locations for a specified payee + operationId: getPayeeLocationsByPayee + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: payee_id + in: path + description: id of payee + required: true + schema: + type: string + responses: + 200: + description: The list of requested payee locations + content: + application/json: + schema: + $ref: '#/components/schemas/PayeeLocationsResponse' + 404: + description: No payees locations were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/months: + get: + tags: + - Months + summary: List budget months + description: Returns all budget months + operationId: getBudgetMonths + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of budget months + content: + application/json: + schema: + $ref: '#/components/schemas/MonthSummariesResponse' + 404: + description: No budget months were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/months/{month}: + get: + tags: + - Months + summary: Single budget month + description: Returns a single budget month + operationId: getBudgetMonth + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: month + in: path + description: The budget month in ISO format (e.g. 2016-12-01) ("current" can + also be used to specify the current calendar month (UTC)) + required: true + schema: + type: string + format: date + responses: + 200: + description: The budget month detail + content: + application/json: + schema: + $ref: '#/components/schemas/MonthDetailResponse' + 404: + description: The budget month was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/transactions: + get: + tags: + - Transactions + summary: List transactions + description: Returns budget transactions + operationId: getTransactions + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: since_date + in: query + description: If specified, only transactions on or after this date will be + included. The date should be ISO formatted (e.g. 2016-12-30). + schema: + type: string + format: date + - name: type + in: query + description: If specified, only transactions of the specified type will be + included. "uncategorized" and "unapproved" are currently supported. + schema: + type: string + enum: + - uncategorized + - unapproved + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of requested transactions + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionsResponse' + 400: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + 404: + description: No transactions were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + post: + tags: + - Transactions + summary: Create a single transaction or multiple transactions + description: Creates a single transaction or multiple transactions. If you + provide a body containing a `transaction` object, a single transaction will + be created and if you provide a body containing a `transactions` array, multiple + transactions will be created. Scheduled transactions cannot be created on + this endpoint. + operationId: createTransaction + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + requestBody: + description: The transaction or transactions to create. To create a single + transaction you can specify a value for the `transaction` object and to + create multiple transactions you can specify an array of `transactions`. It + is expected that you will only provide a value for one of these objects. + content: + '*/*': + schema: + $ref: '#/components/schemas/SaveTransactionsWrapper' + required: true + responses: + 201: + description: The transaction or transactions were successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/SaveTransactionsResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s). + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + 409: + description: A transaction on the same account with the same `import_id` + already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-codegen-request-body-name: data + patch: + tags: + - Transactions + summary: Update multiple transactions + description: Updates multiple transactions, by `id` or `import_id`. + operationId: updateTransactions + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + requestBody: + description: The transactions to update. Each transaction must have either + an `id` or `import_id` specified. If `id` is specified as null an `import_id` + value can be provided which will allow transaction(s) to be updated by their + `import_id`. If an `id` is specified, it will always be used for lookup. + content: + '*/*': + schema: + $ref: '#/components/schemas/UpdateTransactionsWrapper' + required: true + responses: + 209: + description: The transactions were successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/SaveTransactionsResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s). + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-codegen-request-body-name: data + /budgets/{budget_id}/transactions/import: + post: + tags: + - Transactions + summary: Import transactions + description: Imports available transactions on all linked accounts for the given + budget. Linked accounts allow transactions to be imported directly from a + specified financial institution and this endpoint initiates that import. Sending + a request to this endpoint is the equivalent of clicking "Import" on each + account in the web application or tapping the "New Transactions" banner in + the mobile applications. The response for this endpoint contains the transaction + ids that have been imported. + operationId: importTransactions + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + responses: + 200: + description: The request was successful but there were no transactions to + import + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionsImportResponse' + 201: + description: One or more transactions were imported successfully + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionsImportResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/transactions/{transaction_id}: + get: + tags: + - Transactions + summary: Single transaction + description: Returns a single transaction + operationId: getTransactionById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: transaction_id + in: path + description: The id of the transaction + required: true + schema: + type: string + responses: + 200: + description: The requested transaction + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionResponse' + 404: + description: The transaction was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + put: + tags: + - Transactions + summary: Updates an existing transaction + description: Updates a single transaction + operationId: updateTransaction + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: transaction_id + in: path + description: The id of the transaction + required: true + schema: + type: string + requestBody: + description: The transaction to update + content: + '*/*': + schema: + $ref: '#/components/schemas/SaveTransactionWrapper' + required: true + responses: + 200: + description: The transaction was successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-codegen-request-body-name: data + /budgets/{budget_id}/transactions/bulk: + post: + tags: + - Deprecated + summary: Bulk create transactions + description: Creates multiple transactions. Although this endpoint is still + supported, it is recommended to use 'POST /budgets/{budget_id}/transactions' + to create multiple transactions. + operationId: bulkCreateTransactions + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + requestBody: + description: The list of transactions to create + content: + '*/*': + schema: + $ref: '#/components/schemas/BulkTransactions' + required: true + responses: + 201: + description: The bulk request was processed successfully + content: + application/json: + schema: + $ref: '#/components/schemas/BulkResponse' + 400: + description: The request could not be understood due to malformed syntax + or validation error(s) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-codegen-request-body-name: transactions + /budgets/{budget_id}/accounts/{account_id}/transactions: + get: + tags: + - Transactions + summary: List account transactions + description: Returns all transactions for a specified account + operationId: getTransactionsByAccount + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: account_id + in: path + description: The id of the account + required: true + schema: + type: string + - name: since_date + in: query + description: If specified, only transactions on or after this date will be + included. The date should be ISO formatted (e.g. 2016-12-30). + schema: + type: string + format: date + - name: type + in: query + description: If specified, only transactions of the specified type will be + included. "uncategorized" and "unapproved" are currently supported. + schema: + type: string + enum: + - uncategorized + - unapproved + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of requested transactions + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionsResponse' + 404: + description: No transactions were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/categories/{category_id}/transactions: + get: + tags: + - Transactions + summary: List category transactions + description: Returns all transactions for a specified category + operationId: getTransactionsByCategory + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: category_id + in: path + description: The id of the category + required: true + schema: + type: string + - name: since_date + in: query + description: If specified, only transactions on or after this date will be + included. The date should be ISO formatted (e.g. 2016-12-30). + schema: + type: string + format: date + - name: type + in: query + description: If specified, only transactions of the specified type will be + included. "uncategorized" and "unapproved" are currently supported. + schema: + type: string + enum: + - uncategorized + - unapproved + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of requested transactions + content: + application/json: + schema: + $ref: '#/components/schemas/HybridTransactionsResponse' + 404: + description: No transactions were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/payees/{payee_id}/transactions: + get: + tags: + - Transactions + summary: List payee transactions + description: Returns all transactions for a specified payee + operationId: getTransactionsByPayee + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: payee_id + in: path + description: The id of the payee + required: true + schema: + type: string + - name: since_date + in: query + description: If specified, only transactions on or after this date will be + included. The date should be ISO formatted (e.g. 2016-12-30). + schema: + type: string + format: date + - name: type + in: query + description: If specified, only transactions of the specified type will be + included. "uncategorized" and "unapproved" are currently supported. + schema: + type: string + enum: + - uncategorized + - unapproved + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of requested transactions + content: + application/json: + schema: + $ref: '#/components/schemas/HybridTransactionsResponse' + 404: + description: No transactions were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/scheduled_transactions: + get: + tags: + - Scheduled Transactions + summary: List scheduled transactions + description: Returns all scheduled transactions + operationId: getScheduledTransactions + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: last_knowledge_of_server + in: query + description: The starting server knowledge. If provided, only entities that + have changed since `last_knowledge_of_server` will be included. + schema: + type: integer + format: int64 + responses: + 200: + description: The list of requested scheduled transactions + content: + application/json: + schema: + $ref: '#/components/schemas/ScheduledTransactionsResponse' + 404: + description: No scheduled transactions were found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /budgets/{budget_id}/scheduled_transactions/{scheduled_transaction_id}: + get: + tags: + - Scheduled Transactions + summary: Single scheduled transaction + description: Returns a single scheduled transaction + operationId: getScheduledTransactionById + parameters: + - name: budget_id + in: path + description: 'The id of the budget. "last-used" can be used to specify the + last used budget and "default" can be used if default budget selection is + enabled (see: https://api.youneedabudget.com/#oauth-default-budget).' + required: true + schema: + type: string + - name: scheduled_transaction_id + in: path + description: The id of the scheduled transaction + required: true + schema: + type: string + responses: + 200: + description: The requested Scheduled Transaction + content: + application/json: + schema: + $ref: '#/components/schemas/ScheduledTransactionResponse' + 404: + description: The scheduled transaction was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + default: + description: An error occurred + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + ErrorResponse: + required: + - error + type: object + properties: + error: + $ref: '#/components/schemas/ErrorDetail' + ErrorDetail: + required: + - detail + - id + - name + type: object + properties: + id: + type: string + name: + type: string + detail: + type: string + UserResponse: + required: + - data + type: object + properties: + data: + required: + - user + type: object + properties: + user: + $ref: '#/components/schemas/User' + User: + required: + - id + type: object + properties: + id: + type: string + format: uuid + DateFormat: + required: + - format + type: object + properties: + format: + type: string + description: Date format setting for the budget + description: The date format setting for the budget. In some cases the format + will not be available and will be specified as null. + CurrencyFormat: + required: + - currency_symbol + - decimal_digits + - decimal_separator + - display_symbol + - example_format + - group_separator + - iso_code + - symbol_first + type: object + properties: + iso_code: + type: string + description: ISO code + example_format: + type: string + description: Example format + decimal_digits: + type: integer + format: int32 + description: Decimal digits + decimal_separator: + type: string + description: Decimal separator + symbol_first: + type: boolean + description: Symbol first + group_separator: + type: string + description: Group separator + currency_symbol: + type: string + description: Currency symbol + display_symbol: + type: boolean + description: Display symbol + description: The currency format setting for the budget. In some cases the + format will not be available and will be specified as null. + BudgetSummaryResponse: + required: + - data + type: object + properties: + data: + required: + - budgets + type: object + properties: + budgets: + type: array + items: + $ref: '#/components/schemas/BudgetSummary' + default_budget: + $ref: '#/components/schemas/BudgetSummary' + BudgetSummary: + required: + - id + - name + type: object + nullable: true + properties: + id: + type: string + format: uuid + name: + type: string + last_modified_on: + type: string + description: The last time any changes were made to the budget from either + a web or mobile client + format: date-time + first_month: + type: string + description: The earliest budget month + format: date + last_month: + type: string + description: The latest budget month + format: date + date_format: + $ref: '#/components/schemas/DateFormat' + currency_format: + $ref: '#/components/schemas/CurrencyFormat' + accounts: + type: array + description: The budget accounts (only included if `include_accounts=true` + specified as query parameter) + items: + $ref: '#/components/schemas/Account' + BudgetDetailResponse: + required: + - data + type: object + properties: + data: + required: + - budget + - server_knowledge + type: object + properties: + budget: + $ref: '#/components/schemas/BudgetDetail' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + BudgetDetail: + allOf: + - $ref: '#/components/schemas/BudgetSummary' + - type: object + properties: + accounts: + type: array + items: + $ref: '#/components/schemas/Account' + payees: + type: array + items: + $ref: '#/components/schemas/Payee' + payee_locations: + type: array + items: + $ref: '#/components/schemas/PayeeLocation' + category_groups: + type: array + items: + $ref: '#/components/schemas/CategoryGroup' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + months: + type: array + items: + $ref: '#/components/schemas/MonthDetail' + transactions: + type: array + items: + $ref: '#/components/schemas/TransactionSummary' + subtransactions: + type: array + items: + $ref: '#/components/schemas/SubTransaction' + scheduled_transactions: + type: array + items: + $ref: '#/components/schemas/ScheduledTransactionSummary' + scheduled_subtransactions: + type: array + items: + $ref: '#/components/schemas/ScheduledSubTransaction' + BudgetSettingsResponse: + required: + - data + type: object + properties: + data: + required: + - settings + type: object + properties: + settings: + $ref: '#/components/schemas/BudgetSettings' + BudgetSettings: + required: + - currency_format + - date_format + type: object + properties: + date_format: + $ref: '#/components/schemas/DateFormat' + currency_format: + $ref: '#/components/schemas/CurrencyFormat' + AccountsResponse: + required: + - data + type: object + properties: + data: + required: + - accounts + - server_knowledge + type: object + properties: + accounts: + type: array + items: + $ref: '#/components/schemas/Account' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + AccountResponse: + required: + - data + type: object + properties: + data: + required: + - account + type: object + properties: + account: + $ref: '#/components/schemas/Account' + Account: + required: + - balance + - cleared_balance + - closed + - deleted + - id + - name + - on_budget + - transfer_payee_id + - type + - uncleared_balance + type: object + properties: + id: + type: string + format: uuid + name: + type: string + type: + type: string + description: 'The type of account. Note: payPal, merchantAccount, investmentAccount, + and mortgage types have been deprecated and will be removed in the future.' + enum: + - checking + - savings + - cash + - creditCard + - lineOfCredit + - otherAsset + - otherLiability + - payPal + - merchantAccount + - investmentAccount + - mortgage + on_budget: + type: boolean + description: Whether this account is on budget or not + closed: + type: boolean + description: Whether this account is closed or not + note: + type: string + balance: + type: integer + description: The current balance of the account in milliunits format + format: int64 + cleared_balance: + type: integer + description: The current cleared balance of the account in milliunits format + format: int64 + uncleared_balance: + type: integer + description: The current uncleared balance of the account in milliunits + format + format: int64 + transfer_payee_id: + type: string + description: The payee id which should be used when transferring to this + account + format: uuid + direct_import_linked: + type: boolean + description: Whether or not the account is linked to a financial institution + for automatic transaction import. + direct_import_in_error: + type: boolean + description: If an account linked to a financial institution (direct_import_linked=true) + and the linked connection is not in a healthy state, this will be true. + deleted: + type: boolean + description: Whether or not the account has been deleted. Deleted accounts + will only be included in delta requests. + SaveAccountWrapper: + required: + - account + type: object + properties: + account: + $ref: '#/components/schemas/SaveAccount' + SaveAccount: + required: + - balance + - name + - type + type: object + properties: + name: + type: string + description: The name of the account + type: + type: string + description: The account type + enum: + - checking + - savings + - creditCard + - cash + - lineOfCredit + - otherAsset + - otherLiability + balance: + type: integer + description: The current balance of the account in milliunits format + format: int64 + CategoriesResponse: + required: + - data + type: object + properties: + data: + required: + - category_groups + - server_knowledge + type: object + properties: + category_groups: + type: array + items: + $ref: '#/components/schemas/CategoryGroupWithCategories' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + CategoryResponse: + required: + - data + type: object + properties: + data: + required: + - category + type: object + properties: + category: + $ref: '#/components/schemas/Category' + CategoryGroupWithCategories: + allOf: + - $ref: '#/components/schemas/CategoryGroup' + - required: + - categories + type: object + properties: + categories: + type: array + description: Category group categories. Amounts (budgeted, activity, + balance, etc.) are specific to the current budget month (UTC). + items: + $ref: '#/components/schemas/Category' + CategoryGroup: + required: + - deleted + - hidden + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + hidden: + type: boolean + description: Whether or not the category group is hidden + deleted: + type: boolean + description: Whether or not the category group has been deleted. Deleted + category groups will only be included in delta requests. + Category: + required: + - activity + - balance + - budgeted + - category_group_id + - deleted + - hidden + - id + - name + type: object + properties: + id: + type: string + format: uuid + category_group_id: + type: string + format: uuid + name: + type: string + hidden: + type: boolean + description: Whether or not the category is hidden + original_category_group_id: + type: string + description: If category is hidden this is the id of the category group + it originally belonged to before it was hidden. + format: uuid + note: + type: string + budgeted: + type: integer + description: Budgeted amount in milliunits format + format: int64 + activity: + type: integer + description: Activity amount in milliunits format + format: int64 + balance: + type: integer + description: Balance in milliunits format + format: int64 + goal_type: + type: string + description: The type of goal, if the category has a goal (TB='Target Category + Balance', TBD='Target Category Balance by Date', MF='Monthly Funding', + NEED='Plan Your Spending') + enum: + - TB + - TBD + - MF + - NEED + goal_creation_month: + type: string + description: The month a goal was created + format: date + goal_target: + type: integer + description: The goal target amount in milliunits + format: int64 + goal_target_month: + type: string + description: The original target month for the goal to be completed. Only + some goal types specify this date. + format: date + goal_percentage_complete: + type: integer + description: The percentage completion of the goal + format: int32 + goal_months_to_budget: + type: integer + description: The number of months, including the current month, left in + the current goal period. + format: int32 + goal_under_funded: + type: integer + description: The amount of funding still needed in the current month to + stay on track towards completing the goal within the current goal period. This + amount will generally correspond to the 'Underfunded' amount in the web + and mobile clients except when viewing a category with a Needed for Spending + Goal in a future month. The web and mobile clients will ignore any funding + from a prior goal period when viewing category with a Needed for Spending + Goal in a future month. + format: int64 + goal_overall_funded: + type: integer + description: The total amount funded towards the goal within the current + goal period. + format: int64 + goal_overall_left: + type: integer + description: The amount of funding still needed to complete the goal within + the current goal period. + format: int64 + deleted: + type: boolean + description: Whether or not the category has been deleted. Deleted categories + will only be included in delta requests. + SaveCategoryResponse: + required: + - data + type: object + properties: + data: + required: + - category + - server_knowledge + type: object + properties: + category: + $ref: '#/components/schemas/Category' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + PayeesResponse: + required: + - data + type: object + properties: + data: + required: + - payees + - server_knowledge + type: object + properties: + payees: + type: array + items: + $ref: '#/components/schemas/Payee' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + PayeeResponse: + required: + - data + type: object + properties: + data: + required: + - payee + type: object + properties: + payee: + $ref: '#/components/schemas/Payee' + Payee: + required: + - deleted + - id + - name + type: object + properties: + id: + type: string + format: uuid + name: + type: string + transfer_account_id: + type: string + description: If a transfer payee, the `account_id` to which this payee transfers + to + deleted: + type: boolean + description: Whether or not the payee has been deleted. Deleted payees + will only be included in delta requests. + PayeeLocationsResponse: + required: + - data + type: object + properties: + data: + required: + - payee_locations + type: object + properties: + payee_locations: + type: array + items: + $ref: '#/components/schemas/PayeeLocation' + PayeeLocationResponse: + required: + - data + type: object + properties: + data: + required: + - payee_location + type: object + properties: + payee_location: + $ref: '#/components/schemas/PayeeLocation' + PayeeLocation: + required: + - deleted + - id + - latitude + - longitude + - payee_id + type: object + properties: + id: + type: string + format: uuid + payee_id: + type: string + format: uuid + latitude: + type: string + longitude: + type: string + deleted: + type: boolean + description: Whether or not the payee location has been deleted. Deleted + payee locations will only be included in delta requests. + TransactionsResponse: + required: + - data + type: object + properties: + data: + required: + - server_knowledge + - transactions + type: object + properties: + transactions: + type: array + items: + $ref: '#/components/schemas/TransactionDetail' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + HybridTransactionsResponse: + required: + - data + type: object + properties: + data: + required: + - transactions + type: object + properties: + transactions: + type: array + items: + $ref: '#/components/schemas/HybridTransaction' + SaveTransactionWrapper: + required: + - transaction + type: object + properties: + transaction: + $ref: '#/components/schemas/SaveTransaction' + SaveTransactionsWrapper: + type: object + properties: + transaction: + $ref: '#/components/schemas/SaveTransaction' + transactions: + type: array + items: + $ref: '#/components/schemas/SaveTransaction' + UpdateTransactionsWrapper: + required: + - transactions + type: object + properties: + transactions: + type: array + items: + $ref: '#/components/schemas/UpdateTransaction' + UpdateTransaction: + allOf: + - required: + - id + type: object + properties: + id: + type: string + - $ref: '#/components/schemas/SaveTransaction' + SaveTransaction: + required: + - account_id + - amount + - date + type: object + properties: + account_id: + type: string + format: uuid + date: + type: string + description: The transaction date in ISO format (e.g. 2016-12-01). Future + dates (scheduled transactions) are not permitted. Split transaction dates + cannot be changed and if a different date is supplied it will be ignored. + format: date + amount: + type: integer + description: The transaction amount in milliunits format. Split transaction + amounts cannot be changed and if a different amount is supplied it will + be ignored. + format: int64 + payee_id: + type: string + description: The payee for the transaction. To create a transfer between + two accounts, use the account transfer payee pointing to the target account. Account + transfer payees are specified as `tranfer_payee_id` on the account resource. + format: uuid + payee_name: + maxLength: 50 + type: string + description: The payee name. If a `payee_name` value is provided and `payee_id` + has a null value, the `payee_name` value will be used to resolve the payee + by either (1) a matching payee rename rule (only if `import_id` is also + specified) or (2) a payee with the same name or (3) creation of a new + payee. + category_id: + type: string + description: The category for the transaction. To configure a split transaction, + you can specify null for `category_id` and provide a `subtransactions` + array as part of the transaction object. If an existing transaction is + a split, the `category_id` cannot be changed. Credit Card Payment categories + are not permitted and will be ignored if supplied. + format: uuid + memo: + maxLength: 200 + type: string + cleared: + type: string + description: The cleared status of the transaction + enum: + - cleared + - uncleared + - reconciled + approved: + type: boolean + description: Whether or not the transaction is approved. If not supplied, + transaction will be unapproved by default. + flag_color: + type: string + description: The transaction flag + enum: + - red + - orange + - yellow + - green + - blue + - purple + import_id: + maxLength: 36 + type: string + description: 'If specified, the new transaction will be assigned this `import_id` + and considered "imported". We will also attempt to match this imported + transaction to an existing "user-entered" transation on the same account, + with the same amount, and with a date +/-10 days from the imported transaction + date.

Transactions imported through File Based Import or Direct + Import (not through the API) are assigned an import_id in the format: + ''YNAB:[milliunit_amount]:[iso_date]:[occurrence]''. For example, a transaction + dated 2015-12-30 in the amount of -$294.23 USD would have an import_id + of ''YNAB:-294230:2015-12-30:1''. If a second transaction on the same + account was imported and had the same date and same amount, its import_id + would be ''YNAB:-294230:2015-12-30:2''. Using a consistent format will + prevent duplicates through Direct Import and File Based Import.

If + import_id is omitted or specified as null, the transaction will be treated + as a "user-entered" transaction. As such, it will be eligible to be matched + against transactions later being imported (via DI, FBI, or API).' + subtransactions: + type: array + description: An array of subtransactions to configure a transaction as a + split. Updating `subtransactions` on an existing split transaction is + not supported. + items: + $ref: '#/components/schemas/SaveSubTransaction' + SaveSubTransaction: + required: + - amount + type: object + properties: + amount: + type: integer + description: The subtransaction amount in milliunits format. + format: int64 + payee_id: + type: string + description: The payee for the subtransaction. + format: uuid + payee_name: + maxLength: 50 + type: string + description: The payee name. If a `payee_name` value is provided and `payee_id` + has a null value, the `payee_name` value will be used to resolve the payee + by either (1) a matching payee rename rule (only if import_id is also + specified on parent transaction) or (2) a payee with the same name or + (3) creation of a new payee. + category_id: + type: string + description: The category for the subtransaction. Credit Card Payment categories + are not permitted and will be ignored if supplied. + format: uuid + memo: + maxLength: 200 + type: string + SaveTransactionsResponse: + required: + - data + type: object + properties: + data: + required: + - server_knowledge + - transaction_ids + type: object + properties: + transaction_ids: + type: array + description: The transaction ids that were saved + items: + type: string + transaction: + $ref: '#/components/schemas/TransactionDetail' + transactions: + type: array + description: If multiple transactions were specified, the transactions + that were saved + items: + $ref: '#/components/schemas/TransactionDetail' + duplicate_import_ids: + type: array + description: If multiple transactions were specified, a list of import_ids + that were not created because of an existing `import_id` found on + the same account + items: + type: string + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + TransactionResponse: + required: + - data + type: object + properties: + data: + required: + - transaction + type: object + properties: + transaction: + $ref: '#/components/schemas/TransactionDetail' + TransactionSummary: + required: + - account_id + - amount + - approved + - cleared + - date + - deleted + - id + type: object + properties: + id: + type: string + date: + type: string + description: The transaction date in ISO format (e.g. 2016-12-01) + format: date + amount: + type: integer + description: The transaction amount in milliunits format + format: int64 + memo: + type: string + cleared: + type: string + description: The cleared status of the transaction + enum: + - cleared + - uncleared + - reconciled + approved: + type: boolean + description: Whether or not the transaction is approved + flag_color: + type: string + description: The transaction flag + enum: + - red + - orange + - yellow + - green + - blue + - purple + account_id: + type: string + format: uuid + payee_id: + type: string + format: uuid + category_id: + type: string + format: uuid + transfer_account_id: + type: string + description: If a transfer transaction, the account to which it transfers + format: uuid + transfer_transaction_id: + type: string + description: If a transfer transaction, the id of transaction on the other + side of the transfer + matched_transaction_id: + type: string + description: If transaction is matched, the id of the matched transaction + import_id: + type: string + description: 'If the Transaction was imported, this field is a unique (by + account) import identifier. If this transaction was imported through + File Based Import or Direct Import and not through the API, the import_id + will have the format: ''YNAB:[milliunit_amount]:[iso_date]:[occurrence]''. For + example, a transaction dated 2015-12-30 in the amount of -$294.23 USD + would have an import_id of ''YNAB:-294230:2015-12-30:1''. If a second + transaction on the same account was imported and had the same date and + same amount, its import_id would be ''YNAB:-294230:2015-12-30:2''.' + deleted: + type: boolean + description: Whether or not the transaction has been deleted. Deleted transactions + will only be included in delta requests. + TransactionDetail: + allOf: + - $ref: '#/components/schemas/TransactionSummary' + - required: + - account_name + - subtransactions + type: object + properties: + account_name: + type: string + payee_name: + type: string + category_name: + type: string + subtransactions: + type: array + description: If a split transaction, the subtransactions. + items: + $ref: '#/components/schemas/SubTransaction' + HybridTransaction: + allOf: + - $ref: '#/components/schemas/TransactionSummary' + - required: + - account_name + - type + type: object + properties: + type: + type: string + description: Whether the hybrid transaction represents a regular transaction + or a subtransaction + enum: + - transaction + - subtransaction + parent_transaction_id: + type: string + description: For subtransaction types, this is the id of the parent transaction. For + transaction types, this id will be always be null. + account_name: + type: string + payee_name: + type: string + category_name: + type: string + SaveMonthCategoryWrapper: + required: + - category + type: object + properties: + category: + $ref: '#/components/schemas/SaveMonthCategory' + SaveMonthCategory: + required: + - budgeted + type: object + properties: + budgeted: + type: integer + description: Budgeted amount in milliunits format + format: int64 + TransactionsImportResponse: + required: + - data + type: object + properties: + data: + required: + - transaction_ids + type: object + properties: + transaction_ids: + type: array + description: The list of transaction ids that were imported. + items: + type: string + BulkResponse: + required: + - data + type: object + properties: + data: + required: + - bulk + type: object + properties: + bulk: + required: + - duplicate_import_ids + - transaction_ids + type: object + properties: + transaction_ids: + type: array + description: The list of Transaction ids that were created. + items: + type: string + duplicate_import_ids: + type: array + description: If any Transactions were not created because they had + an `import_id` matching a transaction already on the same account, + the specified import_id(s) will be included in this list. + items: + type: string + BulkTransactions: + required: + - transactions + type: object + properties: + transactions: + type: array + items: + $ref: '#/components/schemas/SaveTransaction' + SubTransaction: + required: + - amount + - deleted + - id + - transaction_id + type: object + properties: + id: + type: string + transaction_id: + type: string + amount: + type: integer + description: The subtransaction amount in milliunits format + format: int64 + memo: + type: string + payee_id: + type: string + format: uuid + payee_name: + type: string + category_id: + type: string + format: uuid + category_name: + type: string + transfer_account_id: + type: string + description: If a transfer, the account_id which the subtransaction transfers + to + format: uuid + transfer_transaction_id: + type: string + description: If a transfer, the id of transaction on the other side of the + transfer + deleted: + type: boolean + description: Whether or not the subtransaction has been deleted. Deleted + subtransactions will only be included in delta requests. + ScheduledTransactionsResponse: + required: + - data + type: object + properties: + data: + required: + - scheduled_transactions + - server_knowledge + type: object + properties: + scheduled_transactions: + type: array + items: + $ref: '#/components/schemas/ScheduledTransactionDetail' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + ScheduledTransactionResponse: + required: + - data + type: object + properties: + data: + required: + - scheduled_transaction + type: object + properties: + scheduled_transaction: + $ref: '#/components/schemas/ScheduledTransactionDetail' + ScheduledTransactionSummary: + required: + - account_id + - amount + - date_first + - date_next + - deleted + - frequency + - id + type: object + properties: + id: + type: string + format: uuid + date_first: + type: string + description: The first date for which the Scheduled Transaction was scheduled. + format: date + date_next: + type: string + description: The next date for which the Scheduled Transaction is scheduled. + format: date + frequency: + type: string + enum: + - never + - daily + - weekly + - everyOtherWeek + - twiceAMonth + - every4Weeks + - monthly + - everyOtherMonth + - every3Months + - every4Months + - twiceAYear + - yearly + - everyOtherYear + amount: + type: integer + description: The scheduled transaction amount in milliunits format + format: int64 + memo: + type: string + flag_color: + type: string + description: The scheduled transaction flag + enum: + - red + - orange + - yellow + - green + - blue + - purple + account_id: + type: string + format: uuid + payee_id: + type: string + format: uuid + category_id: + type: string + format: uuid + transfer_account_id: + type: string + description: If a transfer, the account_id which the scheduled transaction + transfers to + format: uuid + deleted: + type: boolean + description: Whether or not the scheduled transaction has been deleted. Deleted + scheduled transactions will only be included in delta requests. + ScheduledTransactionDetail: + allOf: + - $ref: '#/components/schemas/ScheduledTransactionSummary' + - required: + - account_name + - subtransactions + type: object + properties: + account_name: + type: string + payee_name: + type: string + category_name: + type: string + subtransactions: + type: array + description: If a split scheduled transaction, the subtransactions. + items: + $ref: '#/components/schemas/ScheduledSubTransaction' + ScheduledSubTransaction: + required: + - amount + - deleted + - id + - scheduled_transaction_id + type: object + properties: + id: + type: string + format: uuid + scheduled_transaction_id: + type: string + format: uuid + amount: + type: integer + description: The scheduled subtransaction amount in milliunits format + format: int64 + memo: + type: string + payee_id: + type: string + format: uuid + category_id: + type: string + format: uuid + transfer_account_id: + type: string + description: If a transfer, the account_id which the scheduled subtransaction + transfers to + format: uuid + deleted: + type: boolean + description: Whether or not the scheduled subtransaction has been deleted. Deleted + scheduled subtransactions will only be included in delta requests. + MonthSummariesResponse: + required: + - data + type: object + properties: + data: + required: + - months + - server_knowledge + type: object + properties: + months: + type: array + items: + $ref: '#/components/schemas/MonthSummary' + server_knowledge: + type: integer + description: The knowledge of the server + format: int64 + MonthDetailResponse: + required: + - data + type: object + properties: + data: + required: + - month + type: object + properties: + month: + $ref: '#/components/schemas/MonthDetail' + MonthSummary: + required: + - activity + - budgeted + - deleted + - income + - month + - to_be_budgeted + type: object + properties: + month: + type: string + format: date + note: + type: string + income: + type: integer + description: 'The total amount of transactions categorized to ''Inflow: + Ready to Assign'' in the month' + format: int64 + budgeted: + type: integer + description: The total amount budgeted in the month + format: int64 + activity: + type: integer + description: 'The total amount of transactions in the month, excluding those + categorized to ''Inflow: Ready to Assign''' + format: int64 + to_be_budgeted: + type: integer + description: The available amount for 'Ready to Assign' + format: int64 + age_of_money: + type: integer + description: The Age of Money as of the month + format: int32 + deleted: + type: boolean + description: Whether or not the month has been deleted. Deleted months + will only be included in delta requests. + MonthDetail: + allOf: + - $ref: '#/components/schemas/MonthSummary' + - required: + - categories + type: object + properties: + categories: + type: array + description: The budget month categories. Amounts (budgeted, activity, + balance, etc.) are specific to the {month} parameter specified. + items: + $ref: '#/components/schemas/Category' + securitySchemes: + bearerAuth: + scheme: bearer + type: http diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/zoom.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/zoom.yaml new file mode 100644 index 000000000..0406ad3c1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/ballerinax_connector_tests/zoom.yaml @@ -0,0 +1,4674 @@ +openapi: 3.0.0 +servers: + - url: https://api.zoom.us/v2 +info: + contact: + email: developersupport@zoom.us + name: Zoom Developers + url: https://developer.zoom.us/ + description: > + This is a generated connector for [Zoom API Version 2.0.0](https://marketplace.zoom.us/docs/api-reference/zoom-api) OpenAPI Specification. + + The Zoom API allows developers to access information from Zoom. You can use this API to build private services or public applications on the [Zoom App Marketplace](http://marketplace.zoom.us). To learn how to get your credentials and create private/public applications, read our [Authorization Guide](https://marketplace.zoom.us/docs/guides/authorization/credentials). + + All endpoints are available via `https` and are located at `api.zoom.us/v2/`. For instance you can list all users on an account via `https://api.zoom.us/v2/users/`. + license: + name: MIT for OAS 2.0 + url: https://opensource.org/licenses/MIT + termsOfService: https://zoom.us/docs/en-us/zoom_api_license_and_tou.html + title: Zoom API + version: 2.0.0 + x-ballerina-display: + label: Zoom + iconPath: "icon.png" + x-ballerina-init-description: > + The connector initialization requires setting the API credentials. + + Please create a [Zoom account](https://marketplace.zoom.us/) and obtain tokens following [this guide](https://marketplace.zoom.us/docs/guides/auth/oauth). Configure required scopes when obtaining the tokens. +security: + - OAuth: [] +tags: + - description: Meeting operations + name: Meetings + - description: Meeting operations + name: Webinars +paths: + "/users/{userId}/meetings": + get: + description: >- + List all the meetings that were scheduled for a user (meeting + host). This API only supports scheduled meetings and thus, details on + instant meetings are not returned via this API. + + **Scopes:** `meeting:read:admin` `meeting:read` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + summary: List meetings + operationId: listMeetings + x-ballerina-display: + label: List Meetings + parameters: + - description: The user ID or email address of the user. For user-level apps, pass + `me` as the value for userId. + in: path + name: userId + required: true + schema: + type: string + x-ballerina-display: + label: User Id + - description: "The meeting types. Scheduled, live or upcoming" + in: query + name: type + schema: + default: live + enum: + - scheduled + - live + - upcoming + type: string + x-ballerina-display: + label: Meeting Type + x-enum-descriptions: + - all the scheduled meetings + - all the live meetings + - all the upcoming meetings + - description: "The number of records returned within a single API call." + in: query + name: page_size + schema: + default: 30 + maximum: 300 + type: integer + x-ballerina-display: + label: Page Size + - description: "The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes." + in: query + name: next_page_token + schema: + type: string + x-ballerina-display: + label: Next Page Token + - description: "The page number of the current page in the returned records." + in: query + name: page_number + schema: + type: string + x-ballerina-display: + label: Page Number + responses: + "200": + content: + application/json: + examples: + response: + value: + meetings: + - created_at: 2019-08-16T01:13:12Z + duration: 30 + host_id: abckjdfhsdkjf + id: 11111 + join_url: https://zoom.us/j/11111 + start_time: 2019-08-16T02:00:00Z + timezone: America/Los_Angeles + topic: Zoom Meeting + type: 2 + uuid: mlghmfghlBBB + - agenda: RegistrationDeniedTest + created_at: 2019-08-16T18:30:46Z + duration: 60 + host_id: abckjdfhsdkjf + id: 2222 + join_url: https://zoom.us/j/2222 + start_time: 2019-08-16T19:00:00Z + timezone: America/Los_Angeles + topic: TestMeeting + type: 2 + uuid: J8H8eavweUcd321== + - created_at: 2019-08-16T21:15:56Z + duration: 60 + host_id: abckjdfhsdkjf + id: 33333 + join_url: https://zoom.us/j/33333 + start_time: 2019-08-16T22:00:00Z + timezone: America/Los_Angeles + topic: My Meeting + type: 2 + uuid: SGVTAcfSfCbbbb + - created_at: 2019-08-29T17:32:33Z + duration: 60 + host_id: abckjdfhsdkjf + id: 44444 + join_url: https://zoom.us/j/4444 + start_time: 2019-08-29T18:00:00Z + timezone: America/Los_Angeles + topic: MyTestPollMeeting + type: 2 + uuid: 64123avdfsMVA== + page_count: 1 + page_number: 1 + page_size: 30 + total_records: 4 + schema: + $ref: '#/components/schemas/ListMeetingsResponse' + description: "HTTP Status Code:200. List of meetings returned." + "404": + description: "HTTP Status Code:404 User ID not found. Error Code:1001, User not exist or not belong to this account." + security: + - OAuth: [] + tags: + - Meetings + post: + description: >- + [Create a + meeting](https://support.zoom.us/hc/en-us/articles/201362413-Scheduling-meetings) + for a user. This API has a daily rate limit of 100 requests per day. + Therefore, only 100 **Create a Meeting** API requests are permitted + within a 24 hour window for a user. + + + + + Scopes: `meeting:write:admin` `meeting:write` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + operationId: createMeeting + x-ballerina-display: + label: Create Meeting + parameters: + - description: "The user ID or email address of the user. For user-level apps, pass me as the value for userId." + in: path + name: userId + required: true + schema: + type: string + x-ballerina-display: + label: User Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MeetingDetails' + description: Meeting detailed. + x-ballerina-display: + label: Meeting Details + required: true + x-examples: + application/json: + agenda: string + duration: integer + password: string + recurrence: + end_date_time: string [date-time] + end_times: integer + monthly_day: integer + monthly_week: integer + monthly_week_day: integer + repeat_interval: integer + type: integer + weekly_days: string + schedule_for: string + settings: + alternative_hosts: string + approval_type: integer + audio: string + auto_recording: string + cn_meeting: boolean + enforce_login: boolean + enforce_login_domains: string + global_dial_in_countries: + - string + host_video: boolean + in_meeting: boolean + join_before_host: boolean + mute_upon_entry: boolean + participant_video: boolean + registrants_email_notification: boolean + registration_type: integer + use_pmi: boolean + watermark: boolean + start_time: string [date-time] + timezone: string + topic: string + type: integer + responses: + "201": + content: + application/json: + examples: + response: + value: + created_at: 2019-09-05T16:54:14Z + duration: 60 + host_id: AbcDefGHi + id: 1100000 + join_url: https://zoom.us/j/1100000 + settings: + alternative_hosts: "" + approval_type: 2 + audio: both + auto_recording: local + breakout_room: + enable: false + host_video: false + in_meeting: false + join_before_host: true + mute_upon_entry: false + participant_video: false + registrants_confirmation_email: true + registrants_email_notification: true + rooms: + - name: room1 + participants: + - james.user01@somemail1234.com + - james.user02@somemail1234.com + - name: room2 + participants: + - james.user03@somemail1234.com + use_pmi: false + waiting_room: false + watermark: false + close_registration: false + cn_meeting: false + enforce_login: false + enforce_login_domains: "" + global_dial_in_countries: + - US + global_dial_in_numbers: + - city: New York + country: US + country_name: US + number: +1 1000200200 + type: toll + - city: San Jose + country: US + country_name: US + number: +1 6699006833 + type: toll + - city: San Jose + country: US + country_name: US + number: +1 408000000 + type: toll + start_time: 2019-08-30T22:00:00Z + start_url: https://zoom.us/s/1100000?iIifQ.wfY2ldlb82SWo3TsR77lBiJjR53TNeFUiKbLyCvZZjw + status: waiting + timezone: America/New_York + topic: API Test + type: 2 + uuid: ng1MzyWNQaObxcf3+Gfm6A== + schema: + $ref: '#/components/schemas/CreateMeetingResponse' + description: "HTTP Status Code:201 - Meeting created." + headers: + Content-Location: + description: Location of created Meeting + schema: + type: string + "300": + description: > + **HTTP Status Code:** `300` + + Invalid enforce_login_domains, separate multiple domains by semicolon. + + A maximum of {rateLimitNumber} meetings can be created/updated for a single user in one day. + "404": + description: > + **HTTP Status Code:** `404` **Not Found** + + User not found. + + + **Error Code:** `1001` User {userId} not exist or not belong to this account. + summary: Create a meeting + tags: + - Meetings + "/meetings/{meetingId}/registrants": + get: + description: A host or a user with admin permission can require [registration + for a Zoom meeting + operationId: listMeetingRegistrants + x-ballerina-display: + label: List Meeting Registrants + parameters: + - description: MThe meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: The meeting occurrence ID. + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Occurence Id + - description: The registrant status + in: query + name: status + schema: + default: approved + enum: + - pending + - approved + - denied + type: string + x-ballerina-display: + label: Registrant Status + x-enum-descriptions: + - registrants status is pending + - registrants status is approved + - registrants status is denied + - description: The number of records returned within a single API call. + in: query + name: page_size + schema: + default: 30 + maximum: 300 + type: integer + x-ballerina-display: + label: Page Size + - description: "Deprecated - The page number of the current page in the returned records." + in: query + name: page_number + schema: + default: 1 + type: integer + x-ballerina-display: + label: Page Number + - description: The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes. + in: query + name: next_page_token + schema: + type: string + x-ballerina-display: + label: Next Page Token + responses: + "200": + content: + application/json: + examples: + response: + value: + page_count: 1 + page_number: 1 + page_size: 1 + registrants: + - address: 11111 Awesome St + city: Paris + comments: Love using Zoom APIs + country: France + create_time: 2012-04-14T16:55:30.231Z + custom_questions: + - title: Did you enjoy the registration process? + value: Yes, alot. + - title: Would you like to register for our next meeting? + value: Absolutely. + email: somemeail@emailprovider.com + first_name: Tim + id: zjkfsdfjdfhg + industry: Tech + job_title: Developer + join_url: https://success.zoom.us/j/0000000000000 + last_name: S. + no_of_employees: 1-20 + org: Growth + phone: "00000" + purchasing_time_frame: Within a month + role_in_purchase_process: Not involved + state: Ile-de-France + status: approved + zip: "11000" + total_records: 1 + schema: + $ref: '#/components/schemas/ListMeetingRegistrantsResponse' + description: "HTTP Status Code:200. Successfully listed meeting registrants." + security: + - OAuth: [] + summary: List meeting registrants + tags: + - Meetings + post: + description: >- + Register a participant for a meeting. Note that there is a + maximum limit of 4999 registrants per meeting and users will see an + error if the capacity has reached. + + + **Prerequisite:** + + * Host user type must be "Licensed". + + + **Scopes:** `meeting:write:admin` `meeting:write` + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + operationId: addMeetingRegistrant + x-ballerina-display: + label: Add Meeting Registrant + parameters: + - description: The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: "Occurrence IDs. You can find these with the meeting get API. Multiple values separated by comma." + in: query + name: occurrence_ids + schema: + type: string + required: false + x-ballerina-display: + label: Occurence Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AddMeetingRegistrantRequest' + required: true + description: Meeting Registrant Details + x-examples: + application/json: + address: 123 Main ST + city: San Jose + comments: Excited to host you. + country: US + custom_questions: + - title: Favorite thing about Zoom + value: Meet Happy + email: myemail@mycompany.com + first_name: Mike + industry: Tech + job_title: DA + last_name: Brown + no_of_employees: 1-20 + org: IT + phone: 111-444-4444 + purchasing_time_frame: More Than 6 Months + role_in_purchase_process: Influencer + state: CA + zip: "95550" + responses: + "201": + content: + application/json: + examples: + response: + value: + id: 85746065 + join_url: amet + registrant_id: a + start_time: culpa mollit + topic: reprehenderit ea ut ex Excepteur + schema: + $ref: '#/components/schemas/AddMeetingRegistrantResponse' + description: Meeting registrant's details + security: + - OAuth: [] + summary: Add meeting registrant + tags: + - Meetings + "/meetings/{meetingId}/registrants/questions": + get: + description: >+ + List registration questions that will be displayed to users while + [registering for a + meeting](https://support.zoom.us/hc/en-us/articles/211579443-Registration-for-Meetings).
+ + + **Scopes:** `meeting:read`, `meeting:read:admin`
+ + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + operationId: getMeetingRegistrantsQuestions + x-ballerina-display: + label: List Registrant Questions + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + x-ballerina-display: + label: Meeting Id + schema: + format: int64 + type: integer + responses: + "200": + content: + application/json: + examples: + response: + value: + custom_questions: + - required: false + title: How long have you been working? + type: short + questions: + - field_name: address + required: true + schema: + $ref: '#/components/schemas/RegistrantQuestions' + description: |- + **HTTP Status Code:** `200`. Meeting Registrant Question object returned + "404": + description: |- + **HTTP Status Code:** `404`
+ Meeting not found + security: + - OAuth: [] + summary: "List registration questions " + tags: + - Meetings + patch: + description: >+ + Update registration questions that will be displayed to users while + [registering for a + meeting](https://support.zoom.us/hc/en-us/articles/211579443-Registration-for-Meetings).

+ + **Scopes:** `meeting:write`, `meeting:write:admin`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + + operationId: updateMeetingRegistrantQuestions + x-ballerina-display: + label: Update Registration Questions + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/RegistrantQuestions' + description: Meeting Registrant Questions + required: true + x-examples: + application/json: + custom_questions: + - required: true + title: How long have you been working? + type: short + questions: + - field_name: address + required: true + responses: + "204": + description: |- + **HTTP Status Code:** `204`. Meeting Registrant Questions Updated + "404": + description: |- + **HTTP Status Code:** `404`
+ Meeting not found. + security: + - OAuth: [] + summary: Update registration questions + tags: + - Meetings + "/meetings/{meetingId}/registrants/status": + put: + description: >- + Update a meeting registrant's status by either approving, + cancelling or denying a registrant from joining the meeting.

+ + **Scopes:** `meeting:write:admin` `meeting:write` + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + operationId: updateMeetingRegistrantStatus + x-ballerina-display: + label: Update Meeting Registrant's Status + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meting Id + - description: The meeting occurrence ID. + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Occurrence Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateMeetingRegistrantstatusRequest' + description: Request payload for meeting registrant status update + required: true + x-examples: + application/json: + action: approve + registrants: + - email: someemail@companyname.com + id: "173525362" + - email: anotheremail@companyname.com + id: "156234353456" + responses: + "204": + description: |- + **HTTP Status Code:** `204`. Registrant status updated. + "300": + description: |- + **Error Code:** `300`
+ This meeting has not set registration as required:{meetingId}. + "400": + description: |+ + **HTTP Status Code:** `400`
+ **Error Code:** `1010`
+ User does not belong to this account: {accountId}.
+ **Error Code:** `3000`
+ Cannot access meeting information.
+ **Error Code:** `3003`
+ You're not the meeting host. + + "404": + description: | + **HTTP Status Code:** `404`
+ Meeting or registrant not found. + **Error Code:** `1001`
+ User does not exist: {userId}.
+ security: + - OAuth: [] + summary: Update registrant's status + tags: + - Meetings + "/meetings/{meetingId}/registrants/{registrantId}": + delete: + description: >- + Delete a meeting registrant.

+ + **Scopes**: `meeting:write:admin` `meeting:write`
+
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + operationId: deleteMeetingregistrant + x-ballerina-display: + label: Delete Meeting Registrant + parameters: + - description: The meeting occurence ID. + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: occurence Id + - description: The meeting ID. + in: path + name: meetingId + required: true + schema: + type: integer + x-ballerina-display: + label: Meeting Id + - description: The meeting registrant ID. + in: path + name: registrantId + required: true + schema: + type: string + x-ballerina-display: + label: Registrant Id + responses: + "204": + description: |- + **HTTP status code:** `204` OK + "400": + description: >- + **HTTP status code:** `400`
+ + Bad Request
+ + + **Error code:** `200`
+ + Only available for paid users: {0}.
+ + + **Error code:** `300`
+ + The value that you entered for the Registrant ID field is invalid. Enter a valid value and try again.
+ + + **Error code:** `404`
+ + Registration has not been enabled for this meeting: {0}.
+ + + **Error code:** `1001`
+ + User {userId} does not exist or does not belong to this account.
+ + + **Error code:** `3000`
+ + Cannot access webinar info. ***Note:** Zoom throws this error when the meetingId is a webinarId.*
+ + Registrant {0} was not found. + + + **Error code:** `3001`
+ + Meeting does not exist: {0}. + summary: Delete a meeting registrant + tags: + - Meetings + "/meetings/{meetingId}": + delete: + description: >+ + Delete a meeting. + + **Scopes:** `meeting:write:admin` `meeting:write` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + operationId: deleteMeeting + x-ballerina-display: + label: Delete Meeting + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: The meeting occurrence ID. + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Occurence Id + - description: >- + `true`: Notify host and alternative host about the meeting + cancellation via email. + + `false`: Do not send any email notification. + in: query + name: schedule_for_reminder + schema: + type: boolean + x-ballerina-display: + label: Schedule for Reminder + - description: >- + `true`: Notify registrants about the meeting cancellation via + email. + + + `false`: Do not send any email notification to meeting registrants. + + + The default value of this field is `false`. + in: query + name: cancel_meeting_reminder + schema: + type: string + x-ballerina-display: + label: Meeting Cancellation Reminder + responses: + "204": + description: "**HTTP Status Code**: `204` Meeting deleted." + "400": + description: >+ + **HTTP Status Code**: `400` + + **Error Code**: `1010` + + User does not belong to this account: {accountId}. + + **Error Code**: `3000` Cannot access meeting information.Invalid occurrence_id. + + **Error Code**: `3002` + + Sorry, you cannot delete this meeting since it is in progress.**Error Code**: `3003` You are not the meeting host. + + **Error Code**: `3007` Sorry, you cannot delete this meeting since it has ended.**Error Code**: `3018` + + Not allowed to delete PMI.**Error Code**: `3037` Not allowed to delete PAC. + "404": + description: |- + **HTTP Status Code**: `404` + Meeting not found. + **Error Code**: `1001` + User does not exist: {userId}. + **Error Code**: `3001` + Meeting with this {meetingId} is not found or has expired. + security: + - OAuth: [] + summary: Delete a meeting + tags: + - Meetings + get: + description: >+ + Retrieve the details of a meeting. + + **Scopes:** `meeting:read:admin` `meeting:read` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + operationId: getMeetingById + x-ballerina-display: + label: Get Meeting Details + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: Meeting Occurrence ID. Provide this field to view meeting details + of a particular occurrence of the [recurring + meeting](https://support.zoom.us/hc/en-us/articles/214973206-Scheduling-Recurring-Meetings). + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Occurence Id + - description: "Set the value of this field to `true` if you would like to view + meeting details of all previous occurrences of a [recurring + meeting](https://support.zoom.us/hc/en-us/articles/214973206-Schedu\ + ling-Recurring-Meetings). " + in: query + name: show_previous_occurrences + schema: + type: boolean + x-ballerina-display: + label: Show Previous Occurrences + responses: + "200": + content: + application/json: + examples: + response: + value: + agenda: API overview + created_at: 2019-09-09T15:54:24Z + duration: 60 + host_id: ABcdofjdogh11111 + id: 1234555466 + join_url: https://zoom.us/j/1234555466 + settings: + alternative_hosts: kjxckfjxgfgjdfk@dkjfhdskhf.com + approval_type: 2 + audio: both + auto_recording: local + close_registration: false + cn_meeting: false + enforce_login: false + enforce_login_domains: mycompanydomain.com + global_dial_in_countries: + - US + global_dial_in_numbers: + - city: New York + country: US + country_name: US + number: +1 000011100 + type: toll + - city: San Jose + country: US + country_name: US + number: +1 6699006833 + type: toll + - city: San Jose + country: US + country_name: US + number: +1 221122112211 + type: toll + host_video: false + in_meeting: false + join_before_host: true + mute_upon_entry: false + participant_video: false + registrants_confirmation_email: true + registrants_email_notification: true + use_pmi: false + waiting_room: false + watermark: false + start_time: 2019-08-30T22:00:00Z + start_url: https://zoom.us/1234555466/cdknfdffgggdfg4MDUxNjY0LCJpYXQiOjE1NjgwNDQ0NjQsImFpZCI6IjRBOWR2QkRqVHphd2J0amxoejNQZ1EiLCJjaWQiOiIifQ.Pz_msGuQwtylTtYQ + status: waiting + timezone: America/New_York + topic: My API Test + type: 2 + uuid: iAABBBcccdddd7A== + schema: + $ref: '#/components/schemas/GetMeetingDetailsResponse' + description: "**HTTP Status Code:** `200` Meeting object returned." + "400": + description: >- + **HTTP Status Code:** `400` + + **Error Code:** `1010` + + User not found on this account: {accountId}.**Error Code:** `3000` + + Cannot access webinar info. + "404": + description: |- + **HTTP Status Code:** `404` + Meeting not found. + **Error Code:** `1001` + User not exist: {userId}.**Error Code:** `3001` + Meeting {meetingId} is not found or has expired. + security: + - OAuth: [] + summary: Get a meeting + tags: + - Meetings + patch: + description: >+ + Update the details of a meeting.
This API has a rate limit of + 100 requests per day. Therefore, a meeting can only be updated for a + maximum of 100 times within a 24 hour window.
+ + **Scopes:** `meeting:write:admin` `meeting:write`
+ + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + operationId: updateMeeting + x-ballerina-display: + label: Update Meeting + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: "Meeting occurrence id. Support change of agenda, start_time, + duration, settings: {host_video, participant_video, + join_before_host, mute_upon_entry, waiting_room, watermark, + auto_recording}" + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Occurrence Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateMeetingRequest' + description: Meeting + required: true + x-examples: + application/json: + agenda: My Meeting + duration: 60 + password: abcd + settings: + alternative_hosts: mycohost@someemail.com + approval_type: 0 + global_dial_in_countries: + - city: San Jose + country: US + country_name: US + number: +1 1212121212121212 + type: toll + host_video: false + in_meeting: false + join_before_host: true + mute_upon_entry: false + participant_video: false + registrants_confirmation_email: true + use_pmi: false + waiting_room: false + watermark: false + start_time: 2019-08-30T18:00:00 + timezone: America/New_York + topic: Michael API Test + type: 2 + responses: + "204": + description: "**HTTP Status Code:** `204`. Meeting updated." + "300": + description: > + **Error Code:** `300`
+ + Invalid enforce_login_domains, separate multiple domains by semicolon.
+ + A maximum of {rateLimitNumber} meetings can be created/updated for a single user in one day. + "400": + description: | + **HTTP Status Code:** `400`
+ **Error Code:** `1010`
+ User not found on this account: {accountId}.
+ **Error Code:** `3000`
+ Cannot access meeting information.
+ **Error Code:** `3003`
+ You are not the meeting host. + "404": + description: |- + **HTTP Status Code:** `404`
+ Meeting not found.
+ **Error Code:** `1001`
+ User does not exist: {userId}.
+ **Error Code:** `3001`
+ A meeting with this {meetingId} is not found or has expired. + security: + - OAuth: [] + summary: Update a meeting + tags: + - Meetings + "/meetings/{meetingId}/status": + put: + description: >- + Update the status of a meeting.

+ + **Scopes:** `meeting:write:admin` `meeting:write` + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + operationId: updateMeetingStatus + x-ballerina-display: + label: Update Meeting Status + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + requestBody: + description: Meeting status update details + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateMeetingstatusRequest' + required: true + x-examples: + application/json: + action: end + responses: + "204": + description: |- + **HTTP Status Code:** `204`. Meeting updated. + "400": + description: |- + **HTTP Status Code:** `400`
+ **Error Code:** `1010`
+ User does not belong to this account: {accountId}. + **Error Code:** `3000`
+ Cannot access meeting info. + **Error Code:** `3003`
+ You're not the meeting host. + **Error Code:** `3063`
+ Can not end on-premise user's meeting: {meetingId}. + "404": + description: |+ + **HTTP Status Code:** `404`
+ Meeting not found.
+ **Error Code:** `1001`
+ Meeting host does not exist: {userId}. + + security: + - OAuth: [] + summary: Update meeting status + tags: + - Meetings + "/past_meetings/{meetingId}/instances": + get: + description: >- + Get a list of ended meeting instances

+ + **Scopes:** `meeting:read:admin` `meeting:read`
+ + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + operationId: listPastMeetings + x-ballerina-display: + label: List Past Meetings + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ListPastMeetingsResponse' + description: |- + **HTTP Status Code:** `200`. List of ended meeting instances returned. + "404": + description: |- + **HTTP Status Code:** `404`
+ Meeting not found. + security: + - OAuth: [] + summary: List ended meeting instances + tags: + - Meetings + "/past_meetings/{meetingId}/polls": + get: + description: >- + [Polls](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings) + allow the meeting host to survey attendees. Use this API to list poll + results of a meeting.

+ + + **Scopes**: `meeting:read:admin`, `meeting:read`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium`
+ **Prerequisites**:
+ + * Host user type must be **Pro**. + + * Meeting must be a scheduled meeting. Instant meetings do not have polling features enabled. + operationId: listPastMeetingPolls + x-ballerina-display: + label: List Meeting Polls + parameters: + - description: >- + The meeting ID or the meeting UUID. If a meeting ID is provided in + the request instead of a UUID, the response will be for the latest + meeting instance. + + + If a UUID starts with "/" or contains "//" (example: "/ajXp112QmuoKj4854875==\"), you must **double encode** the UUID before making an API request. + in: path + name: meetingId + required: true + schema: + type: string + x-ballerina-display: + label: Meeting Id + responses: + "200": + content: + application/json: + examples: + response: + value: + id: 123456 + questions: + - email: myemail@jksdlfkjdf.djfk + name: Sam S + question_details: + - answer: I am wonderful. + question: How are you? + start_time: 2019-02-01T12:34:12.660Z + title: Learn something new + uuid: gsdjfhsdfkhjdsf + schema: + $ref: '#/components/schemas/ListPastMeetingPollsResponse' + description: |- + **HTTP Status Code:** `200` **OK**. Polls returned successfully. + security: + - OAuth: [] + summary: List past meeting's poll results + tags: + - Meetings + parameters: + - in: path + name: meetingId + required: true + schema: + type: string + "/past_meetings/{meetingUUID}": + get: + description: >- + Get details on a past meeting.

+ + **Scopes:** `meeting:read:admin` `meeting:read` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + > **Note**: Please double encode your UUID when using this API if the UUID begins with a '/'or contains '//' in it. + operationId: getPastMeetingDetails + x-ballerina-display: + label: Get Past Meeting Details + parameters: + - description: The meeting UUID. Each meeting instance will generate its own + Meeting UUID (i.e., after a meeting ends, a new UUID will be + generated for the next instance of the meeting). Please double + encode your UUID when using it for other API calls if the UUID + begins with a '/'or contains '//' in it. + in: path + name: meetingUUID + required: true + schema: + type: string + x-ballerina-display: + label: Meeting UUID + responses: + "200": + content: + application/json: + examples: + response: + value: + duration: integer + end_time: string [date-time] + host_id: integer + id: integer + participants_count: integer + start_time: string [date-time] + topic: string + total_minutes: integer + type: integer + user_email: string + user_name: string + uuid: string [uuid] + schema: + $ref: '#/components/schemas/PastMeetingDetailsResponse' + description: |- + **HTTP Status Code:** `200`. Meeting details returned. + "400": + description: | + **HTTP Status Code:** `400`
+ Meeting not found

+ **Error Code:** `1010`
+ User not exist: {userId}

+ User {userId} not exist or not belong to this account.

+ **Error Code:** `300`
+ Cannot access meeting info.

+ **Error Code:** `200`
+ Only available for paid account: {accountId} + "404": + description: | + **HTTP Status Code:** `404`
+ Meeting not found

+ **Error Code:** `3001`
+ This meeting is not available or ID is not valid.
+ Meeting ID is invalid or not end. + security: + - OAuth: [] + summary: Get past meeting details + tags: + - Meetings + "/past_meetings/{meetingUUID}/participants": + get: + description: > + Retrieve information on participants from a past meeting.

+ + **Scopes:** `meeting:read:admin` `meeting:read` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + **Prerequisites:**
+ + * Paid account on a Pro or higher plan. + + +

**Note**: Please double encode your UUID when using this API if the UUID begins with a '/'or contains '//' in it. + operationId: listPastMeetingParticipants + x-ballerina-display: + label: List Past Meeting Participants + parameters: + - description: The meeting UUID. Each meeting instance will generate its own + Meeting UUID (i.e., after a meeting ends, a new UUID will be + generated for the next instance of the meeting). Please double + encode your UUID when using it for other API calls if the UUID + begins with a '/'or contains '//' in it. + in: path + name: meetingUUID + required: true + schema: + type: string + x-ballerina-display: + label: Meeting UUID + - description: The number of records returned within a single API call. + in: query + name: page_size + schema: + default: 30 + maximum: 300 + type: integer + x-ballerina-display: + label: Page Size + - description: The next page token is used to paginate through large result sets. + A next page token will be returned whenever the set of available + results exceeds the current page size. The expiration period for + this token is 15 minutes. + in: query + name: next_page_token + schema: + type: string + x-ballerina-display: + label: Next Page Token + responses: + "200": + content: + application/json: + examples: + response: + value: + next_page_token: aliqua + page_count: 1 + page_size: 30 + participants: + - id: 8b29rgg4bb + name: Ram Shekhar + user_email: ram.shekhar.123@fkdngfjg.fdghdfgj + total_records: 1 + schema: + $ref: '#/components/schemas/ListPastMeetingParticipantsResponse' + description: |- + **HTTP Status Code:** `200`. Meeting participants' report returned. + "400": + description: |+ + **HTTP Status Code:** `400`
+ **Error Code:** `1010`
+ User {userId} not exist or not belong to this account.

+ **Error Code:** `300`
+ Cannot access meeting information.

+ **Error Code:** `200`
+ Only available for paid account: {accountId} + + "404": + description: |- + **HTTP Status Code:** `404`
+ Meeting not found
+ **Error Code:** `1001`
+ User {userId} not exist or not belong to this account.
+ User not exist: {userId}

+ **Error Code:** `3001`
+ This meeting is not available or ID is not valid.
+ Meeting ID is invalid or not end. + security: + - OAuth: [] + summary: List past meeting participants + tags: + - Meetings + "/meetings/{meetingId}/polls": + get: + description: >- + Polls allow the meeting host to survey attendees. Use this API to + list + [polls](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings) + of a meeting.

+ + + **Scopes**: `meeting:read:admin` `meeting:read`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light`
+ **Prerequisites**:
+ + * Host user type must be **Pro** or higher plan. + + * Meeting must be a scheduled meeting. Instant meetings do not have polling features enabled. + operationId: getMeetingPolls + x-ballerina-display: + label: Get Meeting Polls + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + responses: + "200": + content: + application/json: + examples: + response: + value: + polls: + - id: YB33NcABCdg_g1AAAxTQ + questions: + - answers: + - Extremely useful + - Somewhat useful + - Not useful at all + name: How useful was this meeting? + type: multiple + status: notstart + title: Meeting Usefulness + total_records: 1 + schema: + $ref: '#/components/schemas/MeetingPollsResponse' + description: |- + **HTTP Status Code:**. List polls of a Meeting returned + "404": + description: |- + **Error Code:** `404` + Meeting Poll not found + security: + - OAuth: [] + summary: List meeting polls + tags: + - Meetings + post: + description: >- + Polls allow the meeting host to survey attendees. Use this API to + create a + [poll](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings) + for a meeting.

+ + + **Scopes**: `meeting:write:admin` `meeting:write`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light`
+ **Prerequisites**:
+ + * Host user type must be **Pro** or higher plan. + + * Polling feature must be enabled in the host's account. + + * Meeting must be a scheduled meeting. Instant meetings do not have polling features enabled. + operationId: createMeetingPoll + x-ballerina-display: + label: Create Meeting Poll + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateMeetingPollRequest' + description: Meeting poll object + required: true + x-examples: + application/json: + questions: + - answers: + - Extremely useful + - Somewhat useful + - Not useful at all + name: How useful was this meeting? + type: multiple + title: Meeting Usefulness + responses: + "201": + content: + application/json: + examples: + response: + value: + id: abcdaaaeefffhhh + questions: + - answers: + - Extremely useful + - Somewhat useful + - Not useful at all + name: How useful was this meeting? + type: multiple + status: notstart + title: Meeting Usefulness + schema: + $ref: '#/components/schemas/CreateMeetingPollResponse' + description: |- + **HTTP Status Code:** `201`. Meeting Poll Created + headers: + Content-Location: + description: Location of created Meeting Poll + schema: + type: string + "404": + description: |- + **Error Code:** `404`
+ Meeting not found + security: + - OAuth: [] + summary: Create a meeting poll + tags: + - Meetings + "/meetings/{meetingId}/polls/{pollId}": + delete: + description: >- + Polls allow the meeting host to survey attendees. Use this API to + delete a meeting + [poll](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings).
+ + **Scopes**: `meeting:write:admin` `meeting:write`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light`
+ **Prerequisites**:
+ + * Host user type must be **Pro**. + + * Polling feature should be enabled in the host's account. + + * Meeting must be a scheduled meeting. Instant meetings do not have polling features enabled. + operationId: deleteMeetingPoll + x-ballerina-display: + label: Delete Meeting Poll + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: The poll ID + in: path + name: pollId + required: true + schema: + type: string + x-ballerina-display: + label: Poll Id + responses: + "204": + description: |- + **HTTP Status Code:** `204`. Meeting Poll deleted + "404": + description: |- + **Error Code:** `404` + Meeting Poll not found + security: + - OAuth: [] + summary: Delete a meeting poll + tags: + - Meetings + get: + description: >+ + Polls allow the meeting host to survey attendees. Use this API to + get information about a specific meeting + [poll](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings).

+ + **Scopes**: `meeting:read:admin` `meeting:read`
+ + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + + operationId: getMeetingPoll + x-ballerina-display: + label: Get Meeting Poll + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: The poll ID + in: path + name: pollId + required: true + schema: + type: string + x-ballerina-display: + label: Poll Id + responses: + "200": + content: + application/json: + examples: + response: + value: + id: abcdaaaeefffhhh + questions: + - answers: + - Extremely useful + - Somewhat useful + - Not useful at all + name: How useful was this meeting? + type: multiple + status: notstart + title: Meeting Usefulness + schema: + $ref: '#/components/schemas/GetMeetingPollResponse' + description: |- + **HTTP Status Code:** `200`. Meeting Poll object returned + "404": + description: |- + **Error Code:** `404`
+ Meeting Poll not found. + security: + - OAuth: [] + summary: Get a meeting poll + tags: + - Meetings + put: + description: >+ + Polls allow the meeting host to survey attendees. Use this API to + update information of a specific meeting + [poll](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings)

+ + **Scopes**: `meeting:write:admin` `meeting:write` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + operationId: updateMeetingPoll + x-ballerina-display: + label: Update Meeting Poll + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + - description: The poll ID + in: path + name: pollId + required: true + schema: + type: string + x-ballerina-display: + label: Poll Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateMeetingPollRequest' + description: Meeting Poll + required: true + x-examples: + application/json: + questions: + - answers: + - Definitely + - Probably + - Not going to use it again + name: Would you like to use our service again? + type: multiple + title: Meeting Usefulness + responses: + "204": + description: |- + **HTTP Status Code:** `204`. Meeting Poll Updated + "404": + description: |- + **Error Code:** `404`
+ Meeting Poll not found + security: + - OAuth: [] + summary: Update a meeting poll + tags: + - Meetings + "/meetings/{meetingId}/batch_polls": + post: + description: >- + Polls allow the meeting host to survey attendees. Use this API to + create batch + [polls](https://support.zoom.us/hc/en-us/articles/213756303-Polling-for-Meetings) + for a meeting.

+ + + **Scopes**: `meeting:write:admin` `meeting:write`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light`
+ **Prerequisites**:
+ + * Host user type must be **Pro** or higher plan. + + * Polling feature must be enabled in the host's account. + + * Meeting must be a scheduled meeting. Instant meetings do not have polling features enabled. + operationId: createBatchPolls + x-ballerina-display: + label: Create Batch Polls + parameters: + - in: path + name: meetingId + required: true + schema: + type: string + description: Meeting Id + x-ballerina-display: + label: Meeting Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateBatchPollsRequest' + description: Batch Meeting poll object + x-examples: + application/json: + polls: + - questions: + - answers: + - answer 1 + - answer 2 + name: Question Name + type: multiple + - answers: + - answer 1 + - answer 2 + name: Question Name 2 + type: single + title: Meeting Usefulness + responses: + "201": + content: + application/json: + examples: + response: + value: + polls: + - id: ex eiusmod + questions: + - answers: + - est officia + - dolor amet consectetur ad + - irure consectetur enim commodo + name: in mollit cillum adipisicing ullamco + type: consectetur magna et + - answers: + - ut ut + - non pariatur dolore eiusmod consectetur + - pariatur deserunt in dolore et + - deserunt exercitation incididunt nostrud dolore + - dolor sit in laboris eiusmod + name: non proident dolor eiusmod consectetur + type: "et deserunt nisi " + - answers: + - dolor mollit + - dolore Lorem voluptate + name: minim + type: velit labore + status: Excepteur Lorem dolor exercitation + title: in dolore culpa ad qui + - id: mollit do + questions: + - answers: + - "culpa " + - aliquip dolore + name: exercitation consectetur officia do + type: id ex consequat culpa + - answers: + - ullamco consequat ut id esse + - veniam eiusmod anim laborum + name: proident ad + type: Lorem nostrud nulla + - answers: + - nostrud voluptate eu velit + - non labore dolor ad eiusmod + - vo + name: sint cillum ut + type: in enim + - answers: + - sunt voluptate + - reprehenderit ea + - sunt aute + - elit + name: eu ullamco + type: anim dolor sunt + - answers: + - nulla Duis + name: sit enim consequat cupidatat + type: cillum adipisicing + status: deserunt id occaecat nisi qui + title: est incididunt in dolore tempor + - id: "qui " + questions: + - answers: + - laboris laborum + - nostrud sit dolore veniam + - sunt commodo amet dolor ex + name: ullamco et pariatur + type: proident + - answers: + - anim magna ut Lorem + name: adipisicing dolor culpa commodo + type: aliquip veniam + - answers: + - "sunt dolor Excepteur amet " + - qui pariatur esse id fugiat + - aliquip + name: laborum nisi + type: in Duis qui Excepteur aute + status: ut Ut esse + title: ullamco dolore + schema: + $ref: '#/components/schemas/CreateBatchPollsResponse' + description: "**HTTP Status Code:** `201`. Meeting Poll Created" + "400": + description: |- + **HTTP Status Code:** `404` **Not Found**
+ **Error Code:** `300`
+ Invalid Meeting ID. + **Error Code:** `300`
+ Meeting id does not exist. + **Error Code:** `3000`
+ Cannot access meeting information. + **Error Code:** `3001`
+ Meeting does not exist: {meetingId}.
+ **Error Code:** `4400`
+ Polling has not been enabled for this meeting: {meetingId}. + **Error Code:** `4400`
+ You can add a maximum of 25 polls. + summary: Perform batch poll creation + tags: + - Meetings + "/meetings/{meetingId}/invitation": + get: + description: >+ + Retrieve the meeting invite note that was sent for a specific + meeting.

+ + **Scopes:** `meeting:read:admin` `meeting:read`
+ + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + operationId: getMeetingInvitation + x-ballerina-display: + label: Get Meeting Invitation + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + responses: + "200": + content: + application/json: + examples: + response: + value: + invitation: "Shrijana G is inviting you to a scheduled Zoom meeting.\r + + \r + + Topic: MyTestMeeting\r + + Time: Jul 31, 2019 04:00 PM Pacific + Time (US and Canada)\r + + \r + + Join Zoom Meeting\r + + https://zoom.us/j/000000\r + + \r + + One tap mobile\r + + +000000" + schema: + $ref: '#/components/schemas/GetMeetingInvitationResponse' + description: |- + **HTTP Status Code:** `200`
+ Meeting invitation returned. + security: + - OAuth: [] + summary: Get meeting invitation + tags: + - Meetings + "/meetings/{meetingId}/livestream": + get: + description: >+ + Zoom allows users to [live stream a + meeting](https://support.zoom.us/hc/en-us/articles/115001777826-Live-Streaming-Meetings-or-Webinars-Using-a-Custom-Service) + to a custom platform. Use this API to get a meeting's live stream + configuration details such as Stream URL, Stream Key and Page + URL.

+ + **Prerequisites:**
+ + * Meeting host must be a licensed user with a Pro or higher plan.
+ + * Live streaming details must have been [configured](https://support.zoom.us/hc/en-us/articles/115001777826-Live-Streaming-Meetings-or-Webinars-Using-a-Custom-Service#h_01589a6f-a40a-4e18-a448-cb746e52ebc5) for the meeting.

+ + **Scopes:** `meeting:read:admin` `meeting:read`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + + + operationId: getLiveStreamDetails + x-ballerina-display: + label: Get Live Stream Details + parameters: + - description: Unique identifier of the meeting. + in: path + name: meetingId + required: true + schema: + type: string + x-ballerina-display: + label: Meeting Id + responses: + "200": + content: + application/json: + examples: + response: + value: + page_url: https://somecompany.com/livestream/123 + stream_key: Contact It@somecompany.com + stream_url: https://somecompany.com/livestream + schema: + $ref: '#/components/schemas/GetLiveStreamDetailsResponse' + description: |+ + **HTTP Status Code:** `200` **OK**. Live Stream details returned. + + "400": + description: |+ + **HTTP Status Code:** `400` **Bad Request**
+ **Error Code:** `300`
+ Missing meetingId
+ Invalid meetingId

+ **Error Code:** `1010`
+ User does not belong to this account: {accountId} + + + "404": + description: |+ + **HTTP Status Code:** `404` **Not Found**
+ **Error Code:** `1001`
+ User {userId} does not exist. + + summary: Get live stream details + tags: + - Meetings + patch: + description: >+ + Zoom allows users to [live stream a + meeting](https://support.zoom.us/hc/en-us/articles/115001777826-Live-Streaming-Meetings-or-Webinars-Using-a-Custom-Service) + to a custom platform. Use this API to update a meeting's live stream + information.

+ + **Prerequisites:**
+ + * Meeting host must have a Pro license.
+ + **Scopes:** `meeting:write:admin` `meeting:write`
+ **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` + + + operationId: updateMeetingLiveStream + x-ballerina-display: + label: Update Meeting Live Stream + parameters: + - description: >- + The meeting ID in **long** format. The data type of this field is + "long"(represented as int64 in JSON). + + + While storing it in your database, store it as a **long** data type and **not as an integer**, as the Meeting IDs can be longer than 10 digits. + in: path + name: meetingId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Meeting Id + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateMeetingLiveStreamDetailsRequest' + description: Meeting + required: true + x-examples: + application/json: + page_url: mycompany.com/livestream/123 + stream_key: Contact it@mycompany.com + stream_url: mycompany.com/livestream + responses: + "204": + description: |- + **HTTP Status Code:** `204`. Meeting live stream updated. + "300": + description: "**Error Code:** `300`
Missing meetingId
Invalid meetingId." + "400": + description: |- + **HTTP Status Code:** `400`
**Error Code:** `1010`
+ User does not belong to this account: {accountId}.
+ **Error Code:** `3000` Cannot access webinar info. + "404": + description: > + **HTTP Status Code:** `404`
**Error Code:** `1001`
User + {userId} does not exist. + security: + - OAuth: [] + summary: Update a live stream + tags: + - Meetings + "/webinars/{webinarId}/registrants": + get: + description: >+ + Zoom users with a [Webinar Plan](https://zoom.us/webinar) have + access to creating and managing Webinars. Webinar allows a host to + broadcast a Zoom meeting to up to 10,000 attendees. Scheduling a + [Webinar with + registration](https://support.zoom.us/hc/en-us/articles/204619915-Scheduling-a-Webinar-with-Registration) + requires your registrants to complete a brief form before receiving the + link to join the Webinar. + + Use this API to list all the users that have registered for a webinar. + + **Prerequisites:** + + * Pro or higher plan with a Webinar Add-on. + + **Scopes:** `webinar:read:admin` `webinar:read` + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + + operationId: listWebinarRegistrants + x-ballerina-display: + label: List Webinar Meeting Registrants + parameters: + - description: 'The webinar ID in "**long**" format(represented as int64 data type + in JSON). ' + in: path + name: webinarId + required: true + schema: + format: int64 + type: integer + x-ballerina-display: + label: Webinar Id + - description: The meeting occurrence ID. + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Meeting Occurence Id + - description: "The registrant status: `pending` - Registrant's status is pending. `approved` - Registrant's status is approved.`denied` - Registrant's status is denied." + in: query + name: status + schema: + default: approved + enum: + - pending + - approved + - denied + type: string + x-ballerina-display: + label: Status + x-enum-descriptions: + - registrants status is pending + - registrants status is approved + - registrants status is denied + - description: The tracking source ID for the registrants. Useful if you share the + webinar registration page in multiple locations. See [Creating + source tracking links for webinar + registration](https://support.zoom.us/hc/en-us/articles/360000315683-Creating-source-tracking-links-for-webinar-registration) + for details. + in: query + name: tracking_source_id + schema: + type: string + x-ballerina-display: + label: Tracking Source Id + - description: The number of records returned within a single API call. + in: query + name: page_size + schema: + default: 30 + maximum: 300 + type: integer + x-ballerina-display: + label: Page Size + - description: The page number of the current page in the returned records. + in: query + name: page_number + schema: + default: 1 + type: integer + x-ballerina-display: + label: Page Number + - description: The next page token is used to paginate through large result sets. + A next page token will be returned whenever the set of available + results exceeds the current page size. The expiration period for + this token is 15 minutes. + in: query + name: next_page_token + schema: + type: string + x-ballerina-display: + label: Next Page Token + responses: + "200": + content: + application/json: + examples: + response: + value: + page_count: "1" + page_number: "1" + page_size: "30" + registrants: + - address: dsfhkdjsfh st + city: jackson heights + comments: Looking forward to the Webinar + country: US + create_time: 2019-02-26T23:01:16.899Z + custom_questions: + - title: What do you hope to learn from this Webinar? + value: Look forward to learning how you come up with new recipes and what other + services you offer. + email: sjfkghdsg@someemail.dfgjd + first_name: Jill + id: "24000002122" + industry: Food + job_title: Chef + join_url: https://zoom.us/webinar/mywebinarissocooldighdghodghodg + last_name: Chill + no_of_employees: "10" + org: Cooking Org + phone: "00000000" + purchasing_time_frame: 1-3 months + role_in_purchase_process: Influencer + state: NY + status: approved + zip: "11371" + total_records: "1" + schema: + $ref: '#/components/schemas/ListWebinarRegistrantsResponse' + description: "HTTP Status Code: `200` Webinar plan subscription is missing. Enable webinar for this user once the subscription is added." + "300": + description: "**HTTP Status Code:** `300` Invalid webinar ID." + "400": + description: |- + **HTTP Status Code:** `400` + Bad request + **Error Code:** `1010` + User does not belong to this account:{accountId}. + "404": + description: |- + **HTTP Status Code:** `404` + Webinar not found. + **Error Code:** `1001` + User {userId} does not exist or does not belong to this account. + **Error Code:** `3001` + Webinar {webinarId} not found or has expired. + security: + - OAuth: [] + summary: List webinar registrants + tags: + - Webinars + parameters: + - in: path + name: webinarId + required: true + schema: + type: string + x-ballerina-display: + label: Webinar Id + "/past_webinars/{webinarId}/participants": + get: + description: >+ + Use this API to list all the participants who attended a webinar + hosted in the past. + + + **Prerequisites:** + + * Pro or higher plan with a Webinar Add-on. + + **Scopes:** `webinar:read:admin` `webinar:read` + + + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + + + + operationId: listWebinarParticipants + x-ballerina-display: + label: List Webinar Participants + parameters: + - description: Unique identifier of the webinar. You can retrieve the value of + this field by calling the [list + webinars](https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinars) + API. + in: path + name: webinarId + required: true + schema: + type: string + x-ballerina-display: + label: Webinar Id + - description: The number of records returned within a single API call. + in: query + name: page_size + schema: + default: 30 + maximum: 300 + type: integer + x-ballerina-display: + label: Page Size + - description: The next page token is used to paginate through large result sets. + A next page token will be returned whenever the set of available + results exceeds the current page size. The expiration period for + this token is 15 minutes. + in: query + name: next_page_token + schema: + type: string + x-ballerina-display: + label: Next Page Token + responses: + "200": + content: + application/json: + examples: + response: + value: + next_page_token: mdnf23qbsf4wr + page_count: 1 + page_size: 1 + participants: + - id: sdjhf3ui + name: Matt + user_email: matt@123.jhdyuerys + total_records: 1 + schema: + $ref: '#/components/schemas/ListWebinarParticipantsResponse' + description: "Webinar participants' details" + "400": + description: | + **HTTP Status Code:** `400` **Bad request** + + **Error Code:** `200` + No permission. + Only available for paid account: {accountId}. + **Error Code:** `300` + The next page token is invalid or expired. + "404": + description: |- + **HTTP Status Code:** `404` + **Error Code:**`3001` + Webinar does not exist. + summary: List webinar participants + tags: + - Webinars + parameters: + - in: path + name: webinarId + required: true + schema: + type: string + x-ballerina-display: + label: Webinar Id + "/past_webinars/{WebinarUUID}/absentees": + get: + description: >- + List absentees of a webinar. + + **Scopes:** `webinar:read:admin` `webinar:read` + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Heavy` + operationId: listWebinarAbsentees + x-ballerina-display: + label: List Webinar Absentees + parameters: + - description: The meeting occurrence ID. + in: query + name: occurrence_id + schema: + type: string + x-ballerina-display: + label: Occurence Id + - description: The number of records returned within a single API call. + in: query + name: page_size + schema: + default: 30 + maximum: 300 + type: integer + x-ballerina-display: + label: Page Size + - description: The next page token is used to paginate through large result sets. + A next page token will be returned whenever the set of available + results exceeds the current page size. The expiration period for + this token is 15 minutes. + in: query + name: next_page_token + schema: + type: string + x-ballerina-display: + label: Next Page Token + - description: The Webinar UUID. Each Webinar instance will generate its own + Webinar UUID (i.e., after a Webinar ends, a new UUID will be + generated for the next instance of the Webinar). Please double + encode your UUID when using it for API calls if the UUID begins with + a '/' or contains '//' in it. + in: path + name: WebinarUUID + required: true + schema: + type: string + x-ballerina-display: + label: Webinar UUID + responses: + "200": + content: + application/json: + examples: + response: + value: + page_count: 1 + page_number: 1 + page_size: 30 + registrants: + - address: dsfhkdjsfh st + city: jackson heights + comments: Looking forward to the Webinar + country: USA + create_time: 2019-02-26T23:01:16.899Z + custom_questions: + - title: What do you hope to learn from this Webinar? + value: Look forward to learning how you come up with new recipes and what other + services you offer. + email: sjfkghdsg@someemail.dfgjd + first_name: Jill + id: "24000002122" + industry: Food + job_title: Chef + join_url: https://zoom.us/webinar/mywebinarissocooldighdghodghodg + last_name: Chill + no_of_employees: "10" + org: Cooking Org + phone: "00000000" + purchasing_time_frame: 1-3 months + role_in_purchase_process: Influencer + state: NY + status: approved + zip: "11371" + total_records: 1 + schema: + $ref: '#/components/schemas/ListWebinarAbsentees' + description: >- + **HTTP Status Code:** `200` + + Success. **Error Code:** `200` + + Webinar plan subscription is missing. Enable webinar for this user once the subscription is added:{userId}. + "300": + description: "**Error Code:** `300` Invalid webinar UUID." + "400": + description: >- + **HTTP Status Code:** `400` + + **Error Code:** `300` + + The request could not be completed because you have provided an invalid occurence ID: {occurenceId} + + **Error Code:** `1010` + + User does not belong to this account:{accountId}. + + **Error Code:** `3000` + + This Webinar has not registration required: {webinarUUID} + "404": + description: |+ + **HTTP Status Code:** `404` + **Error Code:** `1001` + User {userId} does not exist or does not belong to this account. + **Error Code:** `3001` Meeting ID is invalid or not end. + + security: + - OAuth: [] + summary: List webinar absentees + tags: + - Webinars + "/users/{userId}/meeting_templates": + get: + description: > + Use this API to list [meeting + templates](https://support.zoom.us/hc/en-us/articles/360036559151-Meeting-templates) + that are available to be used by a user. + + + **Scope:** `meeting:read` or `meeting:read:admin` + + **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` + operationId: listMeetingTemplates + x-ballerina-display: + label: List Meeting Templates + parameters: + - description: Unique identifier of the user. Retrieve the value of this field by + calling the [List + users](https://marketplace.zoom.us/docs/api-reference/zoom-api/users/users) + API. + in: path + name: userId + required: true + schema: + type: string + x-ballerina-display: + label: User Id + responses: + "200": + content: + application/json: + examples: + response: + value: + templates: + - id: AdxbhxCzKgSiWAw + name: My meeting template + type: 1 + - id: eYshgdftw4-5_MUSQ + name: Zoom meeting template for daily sync + type: 2 + total_records: 2 + schema: + $ref: '#/components/schemas/ListMeetingTemplatesResponse' + description: "**HTTP Status Code:** `200` **OK**" + "404": + description: |- + **HTTP Status Code:** `404` **Not Found**
+ **Error Code:** `1001`
User not exist: {userId}.
+ User {userId} does not exist or does not belong to this account. + summary: List meeting templates + tags: + - Meetings + parameters: + - in: path + name: userId + required: true + schema: + type: string +components: + schemas: + ListWebinarAbsentees: + allOf: + - $ref: '#/components/schemas/PaginationObject' + - $ref: '#/components/schemas/RegistrantsList' + description: List of users. + title: Registration List + type: object + ListWebinarRegistrantsResponse: + allOf: + - $ref: '#/components/schemas/PaginationObject' + - $ref: '#/components/schemas/RegistrantsList' + description: List of users. + title: Registration List + type: object + ListPastMeetingParticipantsResponse: + allOf: + - $ref: '#/components/schemas/PaginationObject' + - $ref: '#/components/schemas/MeetingPartcipantsList' + description: List of participants + GetMeetingDetailsResponse: + allOf: + - $ref: '#/components/schemas/MeetingFullMetadata' + - $ref: '#/components/schemas/RequestedMeetingDetails' + description: Details of the meeting. + ListMeetingRegistrantsResponse: + allOf: + - $ref: '#/components/schemas/PaginationObject' + - $ref: '#/components/schemas/RegistrantsList' + description: List of users. + title: Registration List + CreateMeetingResponse: + allOf: + - $ref: '#/components/schemas/MeetingMetadata' + - $ref: '#/components/schemas/RequestedMeetingDetails' + description: Details of the created meeting. + ListMeetingsResponse: + allOf: + - $ref: '#/components/schemas/PaginationObject' + - $ref: '#/components/schemas/MeetingList' + description: List of meetings + title: Group List + ListMeetingTemplatesResponse: + properties: + templates: + items: + $ref: '#/components/schemas/TemplateDetails' + type: array + total_records: + description: Total records found for this request. + type: integer + type: object + ListWebinarParticipantsResponse: + properties: + next_page_token: + description: The next page token is used to paginate through large result sets. + A next page token will be returned whenever the set of + available results exceeds the current page size. The + expiration period for this token is 15 minutes. + type: string + page_count: + description: The number of pages returned for this request. + type: integer + page_size: + default: 30 + description: The total number of records returned from a single API call. + maximum: 300 + type: integer + participants: + description: ParticipantsDetails + items: + $ref: '#/components/schemas/PartcipantDetails' + type: array + total_records: + description: The total number of records available across all pages. + type: integer + type: object + UpdateMeetingLiveStreamDetailsRequest: + description: Meeting live stream. + properties: + page_url: + description: The livestream page URL. + format: uri + maxLength: 1024 + type: string + stream_key: + description: Stream name and key. + maxLength: 512 + type: string + stream_url: + description: Streaming URL. + maxLength: 1024 + type: string + required: + - stream_url + - stream_key + type: object + GetLiveStreamDetailsResponse: + properties: + page_url: + description: Live streaming page URL. This is the URL using which anyone can + view the live stream of the meeting. + type: string + stream_key: + description: Stream Key. + type: string + stream_url: + description: Stream URL. + type: string + type: object + GetMeetingInvitationResponse: + description: Meeting invitation details. + properties: + invitation: + description: Meeting invitation. + type: string + title: Meeting Invitation + type: object + CreateBatchPollsResponse: + properties: + polls: + items: + $ref: '#/components/schemas/AddPollQuestionsResponse' + type: array + type: object + CreateBatchPollsRequest: + properties: + questions: + items: + $ref: '#/components/schemas/PollQuestions' + type: array + title: + description: Meeting Poll Title. + type: string + type: object + UpdateMeetingPollRequest: + description: Poll + properties: + questions: + description: Array of Polls + items: + $ref: '#/components/schemas/PollQuestions' + type: array + title: + description: Title for the poll. + type: string + title: Poll + type: object + GetMeetingPollResponse: + properties: + id: + description: Meeting Poll ID + type: string + status: + description: Status of the Meeting Poll:
`notstart` - Poll not + started
`started` - Poll started
`ended` - Poll + ended
`sharing` - Sharing poll results + enum: + - notstart + - started + - ended + - sharing + type: string + x-enum-descriptions: + - Poll not start + - Poll started + - Poll ended + - Poll is sharing + questions: + description: Array of Polls + items: + $ref: '#/components/schemas/PollQuestions' + type: array + title: + description: Title for the poll. + type: string + title: Poll + type: object + CreateMeetingPollResponse: + properties: + id: + description: Meeting Poll ID + type: string + status: + description: Status of the Meeting Poll:
`notstart` - Poll not + started
`started` - Poll started
`ended` - Poll + ended
`sharing` - Sharing poll results + enum: + - notstart + - started + - ended + - sharing + type: string + x-enum-descriptions: + - Poll not start + - Poll started + - Poll ended + - Poll is sharing + questions: + description: Array of Polls + items: + $ref: '#/components/schemas/PollQuestions' + type: array + title: + description: Title for the poll. + type: string + title: Poll + type: object + CreateMeetingPollRequest: + description: Poll + properties: + questions: + description: Array of Polls + items: + $ref: '#/components/schemas/PollQuestions' + type: array + title: + description: Title for the poll. + type: string + title: Poll + type: object + MeetingPollsResponse: + properties: + polls: + description: Array of Polls + items: + $ref: '#/components/schemas/PollDetails' + type: array + total_records: + description: The number of all records available across pages + type: integer + description: Poll List + title: Poll List + type: object + PastMeetingDetailsResponse: + properties: + duration: + description: Meeting duration. + type: integer + end_time: + description: Meeting end time (GMT). + format: date-time + type: string + host_id: + description: Host ID. + type: string + id: + description: '[Meeting + ID](https://support.zoom.us/hc/en-us/articles/201362373-What-is-a-Meeting-ID-): + Unique identifier of the meeting in "**long**" + format(represented as int64 data type in JSON), also known + as the meeting number.' + format: int64 + type: integer + participants_count: + description: Number of meeting participants. + type: integer + start_time: + description: Meeting start time (GMT). + format: date-time + type: string + topic: + description: Meeting topic. + type: string + total_minutes: + description: Sum of meeting minutes from all participants in the meeting. + type: integer + type: + description: Meeting type. + type: integer + user_email: + description: User email. + type: string + user_name: + description: User display name. + type: string + uuid: + description: Meeting UUID. + format: uuid + type: string + type: object + ListPastMeetingPollsResponse: + properties: + id: + description: '[Meeting + ID](https://support.zoom.us/hc/en-us/articles/201362373-What-is-a-Meeting-ID-): + Unique identifier of the meeting in "**long**" + format(represented as int64 data type in JSON), also known + as the meeting number.' + format: int64 + type: integer + questions: + items: + $ref: '#/components/schemas/UserSubmittedAnswers' + type: array + start_time: + description: The start time of the meeting. + format: date-time + type: string + uuid: + description: Meeting UUID. + type: string + type: object + ListPastMeetingsResponse: + properties: + meetings: + description: List of ended meeting instances. + items: + $ref: '#/components/schemas/EndedMeetingDetails' + type: array + description: List of Meetings + title: Meeting instances + type: object + UpdateMeetingstatusRequest: + properties: + action: + description: > + `end` - End a meeting.
+ + `recover` - [Recover](https://support.zoom.us/hc/en-us/articles/360038297111-Recover-a-deleted-meeting) a deleted meeting. + enum: + - end + - recover + type: string + type: object + UpdateMeetingRequest: + properties: + schedule_for: + description: Email or userId if you want to schedule meeting for another user. + type: string + agenda: + description: Meeting description. + maxLength: 2000 + type: string + duration: + description: Meeting duration (minutes). Used for scheduled meetings only. + type: integer + password: + description: >- + Meeting passcode. Passcode may only contain the following + characters: [a-z A-Z 0-9 @ - _ *] and can have a + maximum of 10 characters. + + + **Note:** If the account owner or the admin has configured [minimum passcode requirement settings](https://support.zoom.us/hc/en-us/articles/360033559832-Meeting-and-webinar-passwords#h_a427384b-e383-4f80-864d-794bf0a37604), the passcode value provided here must meet those requirements.

If the requirements are enabled, you can view those requirements by calling either the [Get User Settings API](https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usersettings) or the [Get Account Settings](https://marketplace.zoom.us/docs/api-reference/zoom-api/accounts/accountsettings) API. + maxLength: 10 + type: string + recurrence: + $ref: '#/components/schemas/ReccurenceDetails' + settings: + $ref: '#/components/schemas/MeetingSettings' + start_time: + description: Meeting start time. When using a format like + "yyyy-MM-dd'T'HH:mm:ss'Z'", always use GMT time. + When using a format like "yyyy-MM-dd'T'HH:mm:ss", + you should use local time and specify the time + zone. Only used for scheduled meetings and recurring + meetings with a fixed time. + format: date-time + type: string + template_id: + description: >- + Unique identifier of the meeting template. + + + Use this field if you would like to [schedule the meeting from a meeting template](https://support.zoom.us/hc/en-us/articles/360036559151-Meeting-templates#h_86f06cff-0852-4998-81c5-c83663c176fb). You can retrieve the value of this field by calling the [List meeting templates]() API. + type: string + timezone: + description: Time zone to format start_time. For example, "America/Los_Angeles". + For scheduled meetings only. Please reference our + [time zone](#timezones) list for supported time + zones and their formats. + type: string + topic: + description: Meeting topic. + type: string + tracking_fields: + description: Tracking fields + items: + $ref: '#/components/schemas/TrackingFields' + type: array + type: + default: 2 + description: Meeting Types:
`1` - Instant meeting.
`2` - Scheduled + meeting.
`3` - Recurring meeting with no fixed + time.
`8` - Recurring meeting with a fixed time. + enum: + - 1 + - 2 + - 3 + - 8 + type: integer + x-enum-descriptions: + - Instant Meeting + - Scheduled Meeting + - Recurring Meeting with no fixed time + - Recurring Meeting with fixed time + type: object + UpdateMeetingRegistrantstatusRequest: + properties: + action: + description: Registrant Status:
`approve` - Approve registrant.
`cancel` - + Cancel previously approved registrant's + registration.
`deny` - Deny registrant. + enum: + - approve + - cancel + - deny + type: string + x-enum-descriptions: + - Approve registrant + - Cancel previously approved registrant + - Deny registrant + registrants: + description: List of registrants. + items: + $ref: "#/components/schemas/RegistriantDetails" + maximum: 30 + type: array + required: + - action + type: object + description: Meeting registrant status update details + AddMeetingRegistrantResponse: + properties: + id: + description: '[Meeting + ID](https://support.zoom.us/hc/en-us/articles/201362373-What-is-a-Meeting-ID-): + Unique identifier of the meeting in "**long**" + format(represented as int64 data type in JSON), also known + as the meeting number.' + format: int64 + type: integer + join_url: + description: >- + Unique URL for this registrant to join the meeting. This URL should + only be shared with the registrant for whom the API + request was made. + + If the meeting was [created](https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate) with manual approval type (`approval_type`: 1), the join URL will not be returned in the response. + type: string + registrant_id: + description: Unique identifier of the registrant. + type: string + start_time: + description: The start time for the meeting. + type: string + topic: + description: Topic of the meeting. + type: string + type: object + AddMeetingRegistrantRequest: + description: Registrant base object + x-ballerina-display: + label: Registrant Details + properties: + language: + description: "Registrant's language preference for confirmation emails. The value can be one of the following: `en-US`,`de-DE`,`es-ES`,`fr-FR`,`jp-JP`,`pt-PT`,`ru-RU`,`zh-CN`, `zh-TW`, `ko-KO`, `it-IT`, `vi-VN`." + type: string + x-ballerina-display: + label: Language + auto_approve: + type: boolean + x-ballerina-display: + label: Enable Auto Approve + address: + description: Registrant's address. + type: string + x-ballerina-display: + label: Registrant's Address + city: + description: Registrant's city. + type: string + x-ballerina-display: + label: Registrant's City + comments: + description: A field that allows registrants to provide any questions or + comments that they might have. + type: string + x-ballerina-display: + label: Comments + country: + description: Registrant's country. The value of this field must be in two-letter + abbreviated form and must match the ID field provided in + the + [Countries](https://marketplace.zoom.us/docs/api-reference/other-references/abbreviation-lists#countries) + table. + type: string + x-ballerina-display: + label: Registrant's Country + custom_questions: + description: Custom questions. + x-ballerina-display: + label: Custom Questions + items: + $ref: '#/components/schemas/RegistrantCustomQuestion' + type: array + email: + description: A valid email address of the registrant. + maxLength: 128 + type: string + x-ballerina-display: + label: Email + first_name: + description: Registrant's first name. + maxLength: 64 + type: string + x-ballerina-display: + label: First Name + industry: + description: Registrant's Industry. + type: string + x-ballerina-display: + label: Industry + job_title: + description: Registrant's job title. + type: string + x-ballerina-display: + label: Job Title + last_name: + description: Registrant's last name. + maxLength: 64 + type: string + x-ballerina-display: + label: Last Name + no_of_employees: + description: "Number of Employees: `1-20`, `21-50`, `51-100`, `101-500`, `500-1,000`, `1,001-5,000`, `5,001-10,000`, `More than 10,000`" + type: string + x-ballerina-display: + label: No of Employees + org: + description: Registrant's Organization. + type: string + x-ballerina-display: + label: Registrant's Organization. + phone: + description: Registrant's Phone number. + type: string + x-ballerina-display: + label: Registrant's Phone Number + purchasing_time_frame: + description: >- + This field can be included to gauge interest of webinar attendees + towards buying your product or service. + + + Purchasing Time Frame:`Within a month``1-3 months``4-6 months``More than 6 months``No timeframe` + type: string + x-ballerina-display: + label: Purchasing Time Frame + role_in_purchase_process: + description: "Role in Purchase Process: `Decision Maker`, `Evaluator/Recommender`, `Influencer`, `Not involved` " + type: string + x-ballerina-display: + label: Role in Purchase Process + state: + description: Registrant's State/Province. + type: string + x-ballerina-display: + label: Registrant's State/Province + zip: + description: Registrant's Zip/Postal Code. + type: string + x-ballerina-display: + label: Registrant's Zip/Postal Code + required: + - email + - first_name + type: object + TemplateDetails: + description: Template details + properties: + id: + description: Unique identifier of the template. + type: string + name: + description: Name of the template. + type: string + type: + description: >- + Type of the template. The value of this field can be one of the + following:
+ + `1`: meeting template
+ + `2`: admin meeting template + type: integer + type: object + PollDetails: + allOf: + - properties: + id: + description: ID of Poll + type: string + status: + description: Status of Poll:
`notstart` - Poll not started
`started` - + Poll started
`ended` - Poll + ended
`sharing` - Sharing poll results + enum: + - notstart + - started + - ended + - sharing + type: string + x-enum-descriptions: + - Poll not start + - Poll started + - Poll ended + - Poll is sharing + - description: Poll + properties: + questions: + description: Array of Polls + items: + $ref: '#/components/schemas/PollQuestions' + type: array + title: + description: Title for the poll. + type: string + title: Poll + type: object + UserSubmittedAnswers: + description: Answers submitted by users + properties: + email: + description: Email address of the user who submitted answers to the poll. + type: string + name: + description: Name of the user who submitted answers to the poll. If "anonymous" + option is enabled for a poll, the participant's + polling information will be kept anonymous and the + value of `name` field will be "Anonymous Attendee". + type: string + question_details: + items: + $ref: '#/components/schemas/PollQuestionAnswer' + type: array + type: object + PollQuestionAnswer: + description: Answers submitted for poll questions + properties: + answer: + description: Answer submitted by the user. + type: string + date_time: + description: Date and time at which the answer to the poll was submitted. + format: date-time + type: string + polling_id: + description: Unique identifier of the poll. + type: string + question: + description: Question asked during the poll. + type: string + type: object + EndedMeetingDetails: + properties: + start_time: + description: Start time + format: date-time + type: string + uuid: + description: >+ + Meeting UUID. Unique meeting ID. Each meeting instance will + generate its own Meeting UUID (i.e., after a + meeting ends, a new UUID will be generated + for the next instance of the meeting). + Please double encode your UUID when using it + for API calls if the UUID begins with a + '/'or contains '//' in it. + + type: string + description: Ended meeting details + RegistriantDetails: + properties: + email: + type: string + description: Registrant email + id: + type: string + description: Registrant Id + type: object + description: Registrant's details + CustomQuestions: + properties: + answers: + description: Answer choices for the question. Can not be used for `short` + question type as this type of question requires + registrants to type out the answer. + items: + type: string + type: array + required: + description: Indicates whether or not the custom question is required to be + answered by participants or not. + type: boolean + title: + description: Title of the custom question. + type: string + type: + description: Type of the question being asked. + enum: + - short + - single + type: string + x-enum-descriptions: + - Short Answer + - Single Answer + type: object + CustomRegistrantQuestions: + properties: + field_name: + description: Field name of the question. + enum: + - address + - city + - country + - zip + - state + - phone + - industry + - org + - job_title + - purchasing_time_frame + - role_in_purchase_process + - no_of_employees + - comments + type: string + x-enum-descriptions: + - Address + - City + - Country/Region + - Zip/Postal Code + - State/Province + - Phone + - Industry + - Organization + - Job Title + - Purchasing Time Frame + - Role in Purchase Process + - Number of Employees + - Questions & Comments + required: + description: Indicates whether or not the displayed fields are required to be + filled out by registrants. + type: boolean + type: object + RegistrantQuestions: + description: Meeting Registrant Questions + properties: + custom_questions: + description: Array of Registrant Custom Questions + items: + $ref: '#/components/schemas/CustomQuestions' + type: array + questions: + description: Array of Registrant Questions + items: + $ref: '#/components/schemas/CustomRegistrantQuestions' + type: array + title: Meeting Registrant Questions + type: object + AddPollQuestionsResponse: + description: Response received from adding poll quetions + properties: + id: + description: Meeting Poll ID + type: string + questions: + items: + $ref: '#/components/schemas/PollQuestions' + type: array + status: + description: Status of the Meeting Poll:
`notstart` - Poll not + started
`started` - Poll started
`ended` - + Poll ended
`sharing` - Sharing poll results + enum: + - notstart + - started + - ended + - sharing + type: string + x-enum-descriptions: + - Poll not start + - Poll started + - Poll ended + - Poll is sharing + title: + description: Title for the Poll + type: string + type: object + PollQuestions: + description: Poll questions + properties: + answers: + description: Possible answers for the question. + items: + type: string + type: array + name: + description: Name of the question. + type: string + type: + description: Question type:
`single` - Single choice
`mutliple` - Multiple + choice + enum: + - single + - multiple + type: string + type: object + TrackingFields: + properties: + field: + description: Tracking fields type + type: string + value: + description: Tracking fields value + type: string + type: object + MeetingTrackingDetails: + properties: + field: + description: Label of the tracking field. + type: string + x-ballerina-display: + label: Label + value: + description: Tracking fields value + type: string + x-ballerina-display: + label: Value + required: + - field + type: object + MeetingDetails: + description: Base object for meeting + x-ballerina-display: + label: Meeting Details + properties: + agenda: + description: Meeting description. + maxLength: 2000 + type: string + x-ballerina-display: + label: Description + duration: + description: "Meeting duration (minutes). Used for scheduled meetings only." + type: integer + x-ballerina-display: + label: Duration + password: + description: "Passcode to join the meeting." + maxLength: 10 + type: string + x-ballerina-display: + label: Password + recurrence: + $ref: '#/components/schemas/ReccurenceDetails' + schedule_for: + description: "If you would like to schedule this meeting for someone else in your account, provide the Zoom user id or email address of the user here." + type: string + x-ballerina-display: + label: Scheduled For + settings: + $ref: '#/components/schemas/MeetingSettingsInRequest' + start_time: + description: "Meeting start time. We support two formats for `start_time` - local time and GMT.To set time as GMT the format should be `yyyy-MM-dd`T`HH:mm:ssZ`. To set time using a specific timezone, use `yyyy-MM-dd`T`HH:mm:ss` format and specify the timezone id in the `timezone` field OR leave it blank and the timezone set on your Zoom account will be used. You can also set the time as UTC as the timezone field" + type: string + format: date-time + x-ballerina-display: + label: Meeting Start Time + template_id: + description: "Unique identifier of the admin meeting template. To create admin meeting templates, contact the Zoom support team." + type: string + x-ballerina-display: + label: Template Id + timezone: + description: Time zone to format start_time. For example, "America/Los_Angeles". + For scheduled meetings only. Please reference our [time + zone](https://marketplace.zoom.us/docs/api-reference/other-references/abbreviation-lists#timezones) + list for supported time zones and their formats. + type: string + x-ballerina-display: + label: Timezone + topic: + description: Meeting topic. + type: string + x-ballerina-display: + label: Meeting Topic + tracking_fields: + description: Tracking fields + x-ballerina-display: + label: Tracking Fields + items: + $ref: '#/components/schemas/MeetingTrackingDetails' + type: array + type: + default: 2 + description: "Meeting Type: 1 - Instant meeting. 2 - Scheduled meeting. 3 - Recurring meeting with no fixed time. 8 - Recurring meeting with fixed time." + enum: + - 1 + - 2 + - 3 + - 8 + type: integer + x-ballerina-display: + label: Meeting Type + x-enum-descriptions: + - Instant Meeting + - Scheduled Meeting + - Recurring Meeting with no fixed time + - Recurring Meeting with fixed time + type: object + MeetingFullMetadata: + properties: + assistant_id: + description: Unique identifier of the scheduler who scheduled this meeting on + behalf of the host. This field is only returned if you + used "schedule_for" option in the [Create a Meeting + API + request](https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate). + type: string + host_email: + description: Email address of the meeting host. + format: email + type: string + host_id: + description: ID of the user who is set as host of meeting. + type: string + id: + description: '[Meeting + ID](https://support.zoom.us/hc/en-us/articles/201362373-What-is-a-Meeting-ID-): + Unique identifier of the meeting in "**long**" + format(represented as int64 data type in JSON), also + known as the meeting number.' + format: int64 + type: integer + uuid: + description: > + Unique meeting ID. Each meeting instance will generate its own + Meeting UUID (i.e., after a meeting ends, a new UUID + will be generated for the next instance of the + meeting). You can retrieve a list of UUIDs from past + meeting instances using [this + API](https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/pastmeetings) + . Please double encode your UUID when using it for API + calls if the UUID begins with a '/'or contains '//' in + it. + type: string + type: object + description: Detailed Meeting Metadata + ApprovalAndDenialInfo: + description: "Approve or block users from specific regions/countries from joining this meeting." + x-ballerina-display: + label: Approval or Denial Info + properties: + approved_list: + description: "List of countries/regions from where participants can join this meeting. " + items: + type: string + type: array + x-ballerina-display: + label: Approved Regions List + denied_list: + description: "List of countries/regions from where participants can not join this meeting. " + items: + type: string + type: array + x-ballerina-display: + label: Denied Regions List + enable: + description: "`true`: Setting enabled to either allow users or block users from specific regions to join your meetings. `false`: Setting disabled." + type: boolean + x-ballerina-display: + label: Enable + method: + description: "Specify whether to allow users from specific regions to join thismeeting; or block users from specific regions from oining this meeting. Values: approve or deny" + enum: + - approve + - deny + type: string + x-ballerina-display: + label: Method + type: object + BreakoutRoomSettings: + description: "Setting to pre-assign breakout rooms" + x-ballerina-display: + label: Breakout Room Settings + properties: + enable: + description: "Set the value of this field to `true` if you would like to enable the pre-assigned breakout rooms. " + type: boolean + x-ballerina-display: + label: Enable Pre-Assigned Breakout Rooms + rooms: + description: Create room(s). + x-ballerina-display: + label: Breakout Room Details + items: + $ref: '#/components/schemas/BreakoutRoomsDetails' + type: array + type: object + BreakoutRoomsDetails: + properties: + name: + description: Name of the breakout room. + type: string + x-ballerina-display: + label: Name + participants: + description: "Email addresses of the participants who are to be assigned to the breakout room." + items: + type: string + x-ballerina-display: + label: Participant List + type: array + type: object + LanguageInterpretationDetails: + description: "Language interpretation for meetings. " + x-ballerina-display: + label: Language Interpretation + properties: + enable: + description: "Indicate whether or not you would like to enable language interpretation or this meeting." + type: boolean + x-ballerina-display: + label: Enable + interpreters: + description: Information associated with the interpreter. + x-ballerina-display: + label: interpreter Information + items: + $ref: '#/components/schemas/InterpreterDetails' + type: array + type: object + InterpreterDetails: + properties: + email: + description: Email address of the interpreter. + format: email + type: string + x-ballerina-display: + label: Email + languages: + description: "Languages for interpretation. The string must contain two separated by a comma. For example, if the language is to be interpreted from English to Chinese, the value of this field should be US,CN." + type: string + x-ballerina-display: + label: Languages + type: object + MeetingSettingsInRequest: + description: Meeting settings + x-ballerina-display: + label: Meeting Settings + properties: + additional_data_center_regions: + description: "Enable additional data center regions for this meeting. Provide the value in the form of array of country code(s) for the countries which are available as data center regions" + items: + type: string + type: array + x-ballerina-display: + label: Additiona Data Center Regions + allow_multiple_devices: + description: "If set to `true`, attendees will be allowed to join a meeting from multiple devices." + type: boolean + x-ballerina-display: + label: Allow Multiple Devices + alternative_hosts: + description: "Alternative host's emails or IDs: multiple values separated by a comma." + type: string + x-ballerina-display: + label: Allternative Hosts + alternative_hosts_email_notification: + default: true + description: "Flag to determine whether to send email notifications to alternative hosts, default value is true." + type: boolean + x-ballerina-display: + label: Enable Email Notifications for Alternative Hosts + approval_type: + default: 2 + description: "The default value is `2`. To enable registration required, set the approval type to `0` or `1`. `0` - Automatically approve. `1` - Manually approve. `2` - No registration required." + enum: + - 0 + - 1 + - 2 + type: integer + x-ballerina-display: + label: Approval Type + x-enum-descriptions: + - Automatically Approve + - Manually Approve + - No Registration Required + approved_or_denied_countries_or_regions: + $ref: '#/components/schemas/ApprovalAndDenialInfo' + audio: + default: both + description: "Determine how participants can join the audio portion of the meeting. both : Both Telephony and VoIP, telephony :Telephony only, voip:VoIP only." + enum: + - both + - telephony + - voip + type: string + x-enum-descriptions: + - Both Telephony and VoIP + - Telephony only + - VoIP only + x-ballerina-display: + label: Audio Type + authentication_domains: + description: "Meeting authentication domains. This option, allows you to specify the rule so that Zoom users, whose email address contains a certain domain, can join the meeting." + type: string + x-ballerina-display: + label: Authentication Domains + authentication_option: + description: "Specify the authentication type for users to join a meeting with `meeting_authentication` setting set to `true`. " + type: string + x-ballerina-display: + label: Authentication Option + auto_recording: + default: none + description: "Automatic recording: local - Record on local.cloud - Record on cloud.none - Disabled." + enum: + - local + - cloud + - none + type: string + x-enum-descriptions: + - Record to local device + - Record to cloud + - No Recording + x-ballerina-display: + label: Auto Recording + breakout_room: + $ref: '#/components/schemas/BreakoutRoomSettings' + close_registration: + default: false + description: Close registration after event date + type: boolean + x-ballerina-display: + label: Close Registration + cn_meeting: + default: false + description: Host meeting in China. + type: boolean + x-ballerina-display: + label: Host Meeting in China + contact_email: + description: Contact email for registration + type: string + x-ballerina-display: + label: Contact Email + contact_name: + description: Contact name for registration + type: string + x-ballerina-display: + label: Contact Name + encryption_type: + description: "Choose between enhanced encryption and end-to-end encryption. Values: enhanced_encryption, e2ee" + enum: + - enhanced_encryption + - e2ee + type: string + x-ballerina-display: + label: Encryption Type + global_dial_in_countries: + description: List of global dial-in countries + items: + type: string + type: array + x-ballerina-display: + label: Global Dial-In Countries + host_video: + description: Start video when the host joins the meeting. + type: boolean + x-ballerina-display: + label: Enable Host Video + in_meeting: + default: false + description: Host meeting in India. + type: boolean + x-ballerina-display: + label: Host Meeting in India + jbh_time: + description: " If the value of join_before_host field is set to true, this field can be used to indicate time limits within which a participant may join a meeting before a host. The value of this field can be one of the following: 0: Allow participant to join anytime. 5: Allow participant to join 5 minutes before meeting start time. 10: Allow participant to join 10 minutes before meeting start time." + enum: + - 0 + - 5 + - 10 + type: integer + x-ballerina-display: + label: Join Before Host Time + join_before_host: + default: false + description: "Allow participants to join the meeting before the host starts the meeting. This field can only used for scheduled or recurring meetings." + type: boolean + x-ballerina-display: + label: Enable Join Before Host + language_interpretation: + $ref: '#/components/schemas/LanguageInterpretationDetails' + meeting_authentication: + description: "Only authenticated users can join meeting if the value of this field is set to `true`." + type: boolean + x-ballerina-display: + label: Meeting Authentication + mute_upon_entry: + default: false + description: Mute participants upon entry. + type: boolean + x-ballerina-display: + label: Enable Mute Upon Entry + participant_video: + description: Start video when participants join the meeting. + type: boolean + x-ballerina-display: + label: Start Participant Video On Entry + registrants_email_notification: + description: "Send email notifications to registrants about approval, cancellation, denial of the registration. The value of this field must be set to true in order to use the `registrants_confirmation_email` field." + type: boolean + x-ballerina-display: + label: Enable Email Notifications for Registrants + registration_type: + default: 1 + description: "Registration type. Used for recurring meeting with fixed time only. `1` - Attendees register once and can attend any of the occurrences. `2` - Attendees need to register for each occurrence to attend. `3` - occurrences to attend." + enum: + - 1 + - 2 + - 3 + type: integer + x-ballerina-display: + label: Registration Type + x-enum-descriptions: + - Attendees register once and can attend any of the + occurrences + - Attendees need to register for each occurrence to + attend + - Attendees register once and can choose one or more + occurrences to attend + show_share_button: + description: "If set to `true`, the registration page for the meeting will + include social share buttons. " + type: boolean + x-ballerina-display: + label: Enable Social Share + use_pmi: + default: false + description: Use Personal Meeting ID instead of an automatically generated + meeting ID. It can only be used for scheduled meetings, + instant meetings and recurring meetings with no fixed + time. + type: boolean + x-ballerina-display: + label: User Personal Meeting Id + waiting_room: + description: Enable waiting room. Note that if the value of this field is set to + `true`, it will override and disable the + `join_before_host` setting. + type: boolean + x-ballerina-display: + label: Enable Waiting Room + watermark: + default: false + description: Add watermark when viewing a shared screen. + type: boolean + x-ballerina-display: + label: Enable Watermark + type: object + RegistrantsList: + description: Meeting Registrnats's Details + properties: + registrants: + description: List of registrant objects. + items: + $ref: '#/components/schemas/RegistrantDetails' + type: array + RegistrantCustomQuestion: + description: Custom Question. + properties: + title: + type: string + description: Question title + value: + type: string + description: Question value + type: object + RegistrantDetails: + allOf: + - properties: + id: + description: Registrant ID. + type: string + type: object + - description: Registrant base object + properties: + address: + description: Registrant's address. + type: string + city: + description: Registrant's city. + type: string + comments: + description: A field that allows registrants to provide any questions or + comments that they might have. + type: string + country: + description: Registrant's country. + type: string + custom_questions: + description: Custom questions. + items: + $ref: '#/components/schemas/RegistrantCustomQuestion' + type: array + email: + description: A valid email address of the registrant. + maxLength: 128 + type: string + first_name: + description: Registrant's first name. + maxLength: 64 + type: string + industry: + description: Registrant's Industry. + type: string + job_title: + description: Registrant's job title. + type: string + last_name: + description: Registrant's last name. + maxLength: 64 + type: string + no_of_employees: + description: "Number of Employees: `1-20`, `21-50`, `51-100`, `101-500`, `500-1,000`, `1,001-5,000`, `5,001-10,000`, `More than 10,000`" + type: string + org: + description: Registrant's Organization. + type: string + phone: + description: Registrant's Phone number. + type: string + purchasing_time_frame: + description: >- + This field can be included to gauge interest of webinar attendees + towards buying your product or + service. + + + Purchasing Time Frame:`Within a month``1-3 months``4-6 months``More than 6 months``No timeframe` + type: string + role_in_purchase_process: + description: "Role in Purchase Process: `Decision Maker`, `Evaluator/Recommender`, `Influencer`, `Not involved` " + type: string + state: + description: Registrant's State/Province. + type: string + zip: + description: Registrant's Zip/Postal Code. + type: string + required: + - email + - first_name + type: object + - properties: + create_time: + description: The time at which the registrant registered. + format: date-time + type: string + join_url: + description: The URL using which an approved registrant can join the webinar. + format: string + type: string + status: + description: "The status of the registrant's registration. `approved`: User + has been successfully approved for the + webinar. `pending`: The + registration is still pending. + `denied`: User has been denied from + joining the webinar." + type: string + type: object + PaginationObject: + description: Pagination Object + properties: + next_page_token: + description: The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes. + type: string + page_count: + description: The number of pages returned for the request made. + type: integer + page_number: + default: 1 + description: This field has been deprecated. + type: integer + page_size: + default: 30 + description: The number of records returned with a single API call. + maximum: 300 + type: integer + total_records: + description: The total number of all the records available across pages. + type: integer + type: object + ApprovedOrDeniedCountriesDetails: + description: > + Approve or block users from specific regions/countries from joining + this meeting. + properties: + approved_list: + description: "List of countries/regions from where participants can join this + meeting. " + items: + type: string + type: array + denied_list: + description: "List of countries/regions from where participants can not join + this meeting. " + items: + type: string + type: array + enable: + description: >- + `true`: Setting enabled to either allow users or block users from + specific regions to join your meetings. + + + `false`: Setting disabled. + type: boolean + method: + description: >- + Specify whether to allow users from specific regions to join this + meeting; or block users from specific regions + from joining this meeting. + + `approve`: Allow users from specific regions/countries to join this meeting. If this setting is selected, the approved regions/countries must be included in the `approved_list`. + + `deny`: Block users from specific regions/countries from joining this meeting. If this setting is selected, the approved regions/countries must be included in the `denied_list` + enum: + - approve + - deny + type: string + type: object + ParticipantDetails: + properties: + email: + description: Email address of the participant. + format: email + type: string + name: + description: Name of the participant. + type: string + type: object + CustomKeys: + properties: + key: + description: Custom key associated with the user. + maxLength: 64 + type: string + value: + description: Value of the custom key associated with the user. + maxLength: 256 + type: string + type: object + GlobalDialInNumbersDetails: + properties: + city: + description: City of the number, if any. For example, Chicago. + type: string + country: + description: Country code. For example, BR. + type: string + country_name: + description: Full name of country. For example, Brazil. + type: string + number: + description: Phone number. For example, +1 2332357613. + type: string + type: + description: "Type of number. " + enum: + - toll + - tollfree + type: string + type: object + MeetingSettings: + description: Meeting settings + properties: + allow_multiple_devices: + description: Allow attendees to join the meeting from multiple devices. This + setting only works for meetings that require + [registration](https://support.zoom.us/hc/en-us/articles/211579443-Setting-up-registration-for-a-meeting). + type: boolean + alternative_hosts: + description: "Alternative host's emails or IDs: multiple values are separated by + a semicolon." + type: string + alternative_hosts_email_notification: + default: true + description: Flag to determine whether to send email notifications to + alternative hosts, default value is true. + type: boolean + approval_type: + default: 2 + description: "The default value is `2`. To enable registration required, set the approval type to `0` or `1`. `0` - Automatically approve. `1` - Manually approve. `2` - No registration required." + enum: + - 0 + - 1 + - 2 + type: integer + x-enum-descriptions: + - Automatically Approve + - Manually Approve + - No Registration Required + approved_or_denied_countries_or_regions: + $ref: '#/components/schemas/ApprovedOrDeniedCountriesDetails' + audio: + default: both + description: "Determine how participants can join the audio portion of the meeting. both : Both Telephony and VoIP, telephony :Telephony only, voip:VoIP only." + enum: + - both + - telephony + - voip + type: string + x-enum-descriptions: + - Both Telephony and VoIP + - Telephony only + - VoIP only + authentication_domains: + description: If user has configured ["Sign Into Zoom with Specified + Domains"](https://support.zoom.us/hc/en-us/articles/360037117472-Authentication-Profiles-for-Meetings-and-Webinars#h_5c0df2e1-cfd2-469f-bb4a-c77d7c0cca6f) + option, this will list the domains that are + authenticated. + type: string + authentication_exception: + description: The participants added here will receive unique meeting invite + links and bypass authentication. + items: + $ref: '#/components/schemas/ParticipantDetails' + type: array + authentication_name: + description: Authentication name set in the [authentication + profile](https://support.zoom.us/hc/en-us/articles/360037117472-Authentication-Profiles-for-Meetings-and-Webinars#h_5c0df2e1-cfd2-469f-bb4a-c77d7c0cca6f). + type: string + authentication_option: + description: "Specify the authentication type for users to join a meeting with `meeting_authentication` setting set to `true`. " + type: string + auto_recording: + default: none + description: "Automatic recording: `local` - Record on local. `cloud` - Record on cloud. `none` - Disabled." + enum: + - local + - cloud + - none + type: string + x-enum-descriptions: + - Record to local device + - Record to cloud + - No Recording + breakout_room: + $ref: '#/components/schemas/BreakoutRoomSettings' + close_registration: + default: false + description: Close registration after event date + type: boolean + cn_meeting: + default: false + description: Host meeting in China. + type: boolean + contact_email: + description: Contact email for registration + type: string + contact_name: + description: Contact name for registration + type: string + custom_keys: + description: Custom keys and values assigned to the meeting. + items: + $ref: '#/components/schemas/CustomKeys' + maxItems: 10 + type: array + encryption_type: + description: >- + Choose between enhanced encryption and [end-to-end + encryption](https://support.zoom.us/hc/en-us/articles/360048660871) + when starting or a meeting. When using end-to-end + encryption, several features (e.g. cloud + recording, phone/SIP/H.323 dial-in) will be + **automatically disabled**. The value of + this field can be one of the following: + + `enhanced_encryption`: Enhanced encryption. Encryption is stored in the cloud if you enable this option. + + + `e2ee`: [End-to-end encryption](https://support.zoom.us/hc/en-us/articles/360048660871). The encryption key is stored in your local device and can not be obtained by anyone else. Enabling this setting also **disables** the following features: join before host, cloud recording, streaming, live transcription, breakout rooms, polling, 1:1 private chat, and meeting reactions. + enum: + - enhanced_encryption + - e2ee + type: string + enforce_login: + description: >- + Only signed in users can join this meeting. + + + **This field is deprecated and will not be supported in the future.** As an alternative, use the "meeting_authentication", "authentication_option" and "authentication_domains" fields to understand the [authentication configurations](https://support.zoom.us/hc/en-us/articles/360037117472-Authentication-Profiles-for-Meetings-and-Webinars) set for the meeting. + type: boolean + enforce_login_domains: + description: >- + Only signed in users with specified domains can join meetings. + + + **This field is deprecated and will not be supported in the future.** As an alternative, use the "meeting_authentication", "authentication_option" and "authentication_domains" fields to understand the [authentication configurations](https://support.zoom.us/hc/en-us/articles/360037117472-Authentication-Profiles-for-Meetings-and-Webinars) set for the meeting. + type: string + global_dial_in_countries: + description: List of global dial-in countries + items: + type: string + type: array + global_dial_in_numbers: + description: Global Dial-in Countries/Regions + items: + $ref: '#/components/schemas/GlobalDialInNumbersDetails' + type: array + host_video: + description: Start video when the host joins the meeting. + type: boolean + in_meeting: + default: false + description: Host meeting in India. + type: boolean + jbh_time: + description: >- + If the value of "join_before_host" field is set to true, this field + can be used to indicate time limits within which a + participant may join a meeting before a host. The + value of this field can be one of the following: + + + * `0`: Allow participant to join anytime. + + * `5`: Allow participant to join 5 minutes before meeting start time. + * `10`: Allow participant to join 10 minutes before meeting start time. + enum: + - 0 + - 5 + - 10 + type: integer + join_before_host: + default: false + description: Allow participants to join the meeting before the host starts the + meeting. Only used for scheduled or recurring + meetings. + type: boolean + language_interpretation: + $ref: '#/components/schemas/LanguageInterpretationDetails' + meeting_authentication: + description: "`true` - Only authenticated users can join meetings." + type: boolean + mute_upon_entry: + default: false + description: Mute participants upon entry. + type: boolean + participant_video: + description: Start video when participants join the meeting. + type: boolean + registrants_confirmation_email: + description: Send confirmation email to registrants upon successful + registration. + type: boolean + registrants_email_notification: + description: Send email notifications to registrants about approval, + cancellation, denial of the registration. The + value of this field must be set to true in order + to use the `registrants_confirmation_email` field. + type: boolean + registration_type: + default: 1 + description: "Registration type. Used for recurring meeting with fixed time only. `1` - Attendees register once and can attend any of the occurrences. `2` - Attendees need to register for each occurrence to attend. `3` - occurrences to attend." + enum: + - 1 + - 2 + - 3 + type: integer + x-enum-descriptions: + - Attendees register once and can attend any of + the occurrences + - Attendees need to register for each occurrence + to attend + - Attendees register once and can choose one or + more occurrences to attend + show_share_button: + description: >- + Show social share buttons on the meeting registration page. + + This setting only works for meetings that require [registration](https://support.zoom.us/hc/en-us/articles/211579443-Setting-up-registration-for-a-meeting). + type: boolean + use_pmi: + default: false + description: Use a personal meeting ID. Only used for scheduled meetings and + recurring meetings with no fixed time. + type: boolean + waiting_room: + default: false + description: Enable waiting room + type: boolean + watermark: + default: false + description: Add watermark when viewing a shared screen. + type: boolean + type: object + ReccurenceDetails: + description: "Recurrence related meeting informations" + properties: + end_date_time: + description: Select the final date on which the meeting will recur before it is + canceled. Should be in UTC time, such as + 2017-11-25T12:00:00Z. (Cannot be used with + "end_times".) + format: date-time + type: string + end_times: + default: 1 + description: Select how many times the meeting should recur before it is + canceled. (Cannot be used with "end_date_time".) + maximum: 365 + type: integer + monthly_day: + default: 1 + description: >- + Use this field **only if you're scheduling a recurring meeting of + type** `3` to state which day in a month, the + meeting should recur. The value range is from 1 to + 31. + + + For instance, if you would like the meeting to recur on 23rd of each month, provide `23` as the value of this field and `1` as the value of the `repeat_interval` field. Instead, if you would like the meeting to recur every three months, on 23rd of the month, change the value of the `repeat_interval` field to `3`. + type: integer + monthly_week: + description: Use this field **only if you're scheduling a recurring meeting of + type** `3` to state the week of the month when the + meeting should recur. If you use this field, **you + must also use the `monthly_week_day` field to + state the day of the week when the meeting should + recur.** `-1` - Last week of the month.`1` + - First week of the month.`2` - Second week of + the month.`3` - Third week of the + month.`4` - Fourth week of the month. + enum: + - -1 + - 1 + - 2 + - 3 + - 4 + type: integer + x-enum-descriptions: + - Last week + - First week + - Second week + - Third week + - Fourth week + monthly_week_day: + description: >- + Use this field **only if you're scheduling a recurring meeting of + type** `3` to state a specific day in a week when + the monthly meeting should recur. To use this + field, you must also use the `monthly_week` + field. + + + `1` - Sunday.`2` - Monday.`3` - Tuesday.`4` - Wednesday.`5` - Thursday.`6` - Friday.`7` - Saturday. + enum: + - 1 + - 2 + - 3 + - 4 + - 5 + - 6 + - 7 + type: integer + x-enum-descriptions: + - Sunday + - Monday + - Tuesday + - Wednesday + - Thursday + - Friday + - Saturday + repeat_interval: + description: >+ + Define the interval at which the meeting should recur. For + instance, if you would like to schedule a meeting + that recurs every two months, you must set the + value of this field as `2` and the value of the + `type` parameter as `3`. + + + For a daily meeting, the maximum interval you can set is `90` days. For a weekly meeting the maximum interval that you can set is of `12` weeks. For a monthly meeting, there is a maximum of `3` months. + + type: integer + type: + description: Recurrence meeting types:`1` - Daily.`2` - Weekly.`3` - + Monthly. + enum: + - 1 + - 2 + - 3 + type: integer + x-enum-descriptions: + - Daily + - Weekly + - Monthly + weekly_days: + default: "1" + description: >- + This field is required **if you're scheduling a recurring meeting + of type** `2` to state which day(s) of the week + the meeting should repeat. The value for + this field could be a number between `1` to `7` in + string format. For instance, if the meeting should + recur on Sunday, provide `"1"` as the value of + this field. **Note:** If you would like + the meeting to occur on multiple days of a week, + you should provide comma separated values for this + field. For instance, if the meeting should recur + on Sundays and Tuesdays provide `"1,3"` as the + value of this field. + + `1` - Sunday. `2` - Monday.`3` - Tuesday.`4` - Wednesday.`5` - Thursday.`6` - Friday.`7` - Saturday. + enum: + - "1" + - "2" + - "3" + - "4" + - "5" + - "6" + - "7" + type: string + required: + - type + type: object + MeetingOccurenceDetails: + description: Occurence object. This object is only returned for Recurring Webinars. + properties: + duration: + description: Duration. + type: integer + occurrence_id: + description: "Occurrence ID: Unique Identifier that identifies an occurrence of + a recurring webinar. [Recurring + webinars](https://support.zoom.us/hc/en-us/arti\ + cles/216354763-How-to-Schedule-A-Recurring-Webi\ + nar) can have a maximum of 50 occurrences." + type: string + start_time: + description: Start time. + format: date-time + type: string + status: + description: Occurrence status. + type: string + type: object + RequestedMeetingTrackingDetails: + properties: + field: + description: Label of the tracking field. + type: string + value: + description: Value for the field. + type: string + visible: + description: >- + Indicates whether the [tracking + field](https://support.zoom.us/hc/en-us/articles/115000293426-Scheduling-Tracking-Fields) + is visible in the meeting scheduling options in + the Zoom Web Portal or not. + + + `true`: Tracking field is visible. + + + `false`: Tracking field is not visible to the users in the meeting options in the Zoom Web Portal but the field was used while scheduling this meeting via API. An invisible tracking field can be used by users while scheduling meetings via API only. + type: boolean + type: object + RequestedMeetingDetails: + description: Meeting object + properties: + agenda: + description: Agenda + type: string + created_at: + description: The date and time at which this meeting was created. + format: date-time + type: string + duration: + description: Meeting duration. + type: integer + h323_password: + description: H.323/SIP room system password + type: string + join_url: + description: URL for participants to join the meeting. This URL should only be + shared with users that you would like to invite for + the meeting. + type: string + occurrences: + description: Array of occurrence objects. + items: + $ref: '#/components/schemas/MeetingOccurenceDetails' + type: array + password: + description: >+ + Meeting password. Password may only contain the following + characters: `[a-z A-Z 0-9 @ - _ * !]` + + + If "Require a password when scheduling new meetings" setting has been **enabled** **and** [locked](https://support.zoom.us/hc/en-us/articles/115005269866-Using-Tiered-Settings#locked) for the user, the password field will be autogenerated in the response even if it is not provided in the API request. + + + type: string + pmi: + description: Personal Meeting Id. Only used for scheduled meetings and recurring + meetings with no fixed time. + format: int64 + type: integer + recurrence: + $ref: '#/components/schemas/ReccurenceDetails' + settings: + $ref: '#/components/schemas/MeetingSettings' + start_time: + description: 'Meeting start date-time in UTC/GMT. Example: + "2020-03-31T12:02:00Z"' + format: date-time + type: string + start_url: + description: URL to start the meeting. This URL should only be used by the host + of the meeting and **should not be shared with anyone + other than the host** of the meeting as anyone with + this URL will be able to login to the Zoom Client as + the host of the meeting. + type: string + timezone: + description: Timezone to format start_time + type: string + topic: + description: Meeting topic + maxLength: 200 + type: string + tracking_fields: + description: Tracking fields + items: + $ref: '#/components/schemas/RequestedMeetingTrackingDetails' + type: array + type: + default: 2 + description: Meeting Type + enum: + - 1 + - 2 + - 3 + - 8 + type: integer + x-enum-descriptions: + - Instant Meeting + - Scheduled Meeting + - Recurring Meeting with no fixed time + - Recurring Meeting with fixed time + type: object + MeetingMetadata: + description: Meeting Metadata + properties: + assistant_id: + description: Unique identifier of the scheduler who scheduled this meeting on + behalf of the host. This field is only returned if you + used "schedule_for" option in the [Create a Meeting + API + request](https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate). + type: string + host_email: + description: Email address of the meeting host. + format: email + type: string + id: + description: '[Meeting + ID](https://support.zoom.us/hc/en-us/articles/201362373-What-is-a-Meeting-ID-): + Unique identifier of the meeting in "**long**" + format(represented as int64 data type in JSON), also + known as the meeting number.' + format: int64 + type: integer + registration_url: + description: URL using which registrants can register for a meeting. This field + is only returned for meetings that have enabled + registration. + type: string + type: object + required: + - id + MeetingObject: + properties: + agenda: + description: Meeting description. The length of agenda gets truncated to 250 + characters when you list all meetings for a user. To + view the complete agenda of a meeting, retrieve + details for a single meeting + [here](https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meeting). + type: string + created_at: + description: "Time of creation. " + format: date-time + type: string + duration: + description: Meeting duration. + type: integer + host_id: + description: ID of the user who is set as the host of the meeting. + type: string + id: + description: Meeting ID - also known as the meeting number in double (int64) + format. + format: int64 + type: integer + join_url: + description: Join URL. + type: string + start_time: + description: Meeting start time. + format: date-time + type: string + timezone: + description: "Timezone to format the meeting start time. " + type: string + topic: + description: Meeting topic. + type: string + type: + description: "Meeting Type: 1 - Instant meeting. 2 - Scheduled meeting. 3 - Recurring meeting with no fixed time. 8 - Recurring meeting with fixed time." + enum: + - 1 + - 2 + - 3 + - 8 + type: integer + x-enum-descriptions: + - Instant Meeting + - Scheduled Meeting + - Recurring Meeting with no fixed time + - Recurring Meeting with fixed time + uuid: + description: Unique Meeting ID. Each meeting instance will generate its own + Meeting UUID. + type: string + type: object + MeetingList: + description: List of meetings + title: Group List + type: object + properties: + meetings: + description: List of Meeting objects. + items: + $ref: '#/components/schemas/MeetingObject' + type: array + MeetingPartcipantsList: + description: List of meeting participants + properties: + participants: + description: Array of meeting participant objects. + items: + $ref : '#/components/schemas/PartcipantDetails' + type: array + type: object + PartcipantDetails: + description: Participant's details + properties: + id: + description: Universally unique identifier of the Participant. It is the same as + the User ID of the participant if the + participant joins the meeting by logging into + Zoom. If the participant joins the meeting + without logging in, the value of this field will + be blank. + format: uuid + type: string + name: + description: Participant display name. + type: string + user_email: + description: Email address of the user. This field will be returned if the user + logged into Zoom to join the meeting. + type: string + type: object + securitySchemes: + OAuth: + flows: + authorizationCode: + authorizationUrl: https://zoom.us/oauth/authorize + scopes: {} + tokenUrl: https://zoom.us/oauth/token + type: oauth2 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/complex_oneOf_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/complex_oneOf_schema.yaml new file mode 100644 index 000000000..9ff6d7e17 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/complex_oneOf_schema.yaml @@ -0,0 +1,76 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of pets +components: + schemas: + Address: + oneOf: + - properties: + streetNo: + type: string + houseNo: + type: string + - properties: + streatName: + type: string + country: + type: string + - properties: + zipCode: + type: integer + - $ref: '#/components/schemas/CountryDetails' + CountryDetails: + properties: + iso_code: + type: string + name: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/duplicated_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/duplicated_response.yaml new file mode 100644 index 000000000..4ea9bfbe5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/duplicated_response.yaml @@ -0,0 +1,39 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: https://petstore/v1 + description: The production API server +paths: + /pets: + get: + summary: Get a pet + operationId: getPet + description: "Get pet details" + responses: + '200': + description: The status information is returned for the requested file upload. + content: + application/json: + schema: + $ref: '#/components/schemas/PetDetails' + '202': + description: The status information is returned for the requested file upload. + content: + application/json: + schema: + $ref: '#/components/schemas/PetDetails' + '204': + description: The status information cannot be retrieved for the specified request ID. + content: {} +components: + schemas: + PetDetails: + properties: + name: + type: string + age: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/head_operation.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/head_operation.yaml new file mode 100644 index 000000000..a57d6e5ca --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/head_operation.yaml @@ -0,0 +1,220 @@ +openapi: 3.0.1 +info: + title: Azure Data Lake Storage + description: Azure Data Lake Storage provides storage for Hadoop and other big data + workloads. + version: 1.0.0 +servers: + - url: https://azure.local/ +paths: + /{filesystem}: + head: + tags: + - Filesystem Operations + summary: Get Filesystem Properties. + description: All system and user-defined filesystem properties are specified + in the response headers. + operationId: Filesystem_GetProperties + parameters: + - name: filesystem + in: path + description: The filesystem identifier. + required: true + schema: + maxLength: 63 + minLength: 3 + pattern: ^[$a-z0-9](?!.*--)[-a-z0-9]{1,61}[a-z0-9]$ + type: string + - name: resource + in: query + description: The value must be "filesystem" for all filesystem operations. + required: true + schema: + type: string + enum: + - filesystem + x-ms-enum: + modelAsString: false + name: FilesystemResourceType + x-ms-enum: + modelAsString: false + name: FilesystemResourceType + - name: x-ms-client-request-id + in: header + description: A UUID recorded in the analytics logs for troubleshooting and + correlation. + schema: + pattern: ^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$ + type: string + x-ms-client-request-id: true + x-ms-client-request-id: true + - name: timeout + in: query + description: An optional operation timeout value in seconds. + schema: + minimum: 1 + type: integer + format: int32 + - name: x-ms-date + in: header + description: Specifies the Coordinated Universal Time (UTC) for the request. This + is required when using shared key authorization. + schema: + type: string + - name: x-ms-version + in: header + description: Specifies the version of the REST protocol used for processing + the request. This is required when using shared key authorization. + schema: + type: string + x-ms-parameter-location: client + x-ms-parameter-location: client + responses: + 200: + description: Ok + headers: + x-ms-namespace-enabled: + description: 'A bool string indicates whether the namespace feature + is enabled. If "true", the namespace is enabled for the filesystem. ' + schema: + type: string + x-ms-version: + description: The version of the REST protocol used to process the request. + schema: + type: string + ETag: + description: An HTTP entity tag associated with the filesystem. Changes + to filesystem properties affect the entity tag, but operations on + files and directories do not. + schema: + type: string + Last-Modified: + description: The data and time the filesystem was last modified. Changes + to filesystem properties update the last modified time, but operations + on files and directories do not. + schema: + type: string + x-ms-properties: + description: The user-defined properties associated with the filesystem. A + comma-separated list of name and value pairs in the format "n1=v1, + n2=v2, ...", where each value is a base64 encoded string. Note that + the string may only contain ASCII characters in the ISO-8859-1 character + set. + schema: + type: string + x-ms-request-id: + description: A server-generated UUID recorded in the analytics logs + for troubleshooting and correlation. + schema: + pattern: ^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$ + type: string + Date: + description: A UTC date/time value generated by the service that indicates + the time at which the response was initiated. + schema: + type: string + content: {} + default: + description: "Default Response" + headers: + x-ms-version: + description: The version of the REST protocol used to process the request. + schema: + type: string + x-ms-request-id: + description: A server-generated UUID recorded in the analytics logs + for troubleshooting and correlation. + schema: + pattern: ^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$ + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/DataLakeStorageError' +components: + schemas: + DataLakeStorageError: + type: object + properties: + error: + type: object + properties: + code: + type: string + description: The service error code. + message: + type: string + description: The service error message. + description: The service error response object. + Path: + type: object + properties: + contentLength: + type: integer + format: int64 + eTag: + type: string + group: + type: string + isDirectory: + type: boolean + default: false + lastModified: + type: string + name: + type: string + owner: + type: string + permissions: + type: string + responses: + ErrorResponse: + description: "Error Response" + headers: + x-ms-version: + description: The version of the REST protocol used to process the request. + schema: + type: string + x-ms-request-id: + description: A server-generated UUID recorded in the analytics logs for + troubleshooting and correlation. + schema: + pattern: ^[{(]?[0-9a-f]{8}[-]?([0-9a-f]{4}[-]?){3}[0-9a-f]{12}[)}]?$ + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/DataLakeStorageError' + parameters: + Version: + name: x-ms-version + in: header + description: Specifies the version of the REST protocol used for processing + the request. This is required when using shared key authorization. + schema: + type: string + x-ms-parameter-location: client + x-ms-parameter-location: client + accountName: + name: accountName + in: path + description: The Azure Storage account name. + required: true + schema: + type: string + x-ms-parameter-location: client + x-ms-skip-url-encoding: true + x-ms-parameter-location: client + x-ms-skip-url-encoding: true + dnsSuffix: + name: dnsSuffix + in: path + description: The DNS suffix for the Azure Data Lake Storage endpoint. + required: true + schema: + type: string + default: dfs.core.windows.net + x-ms-parameter-location: client + x-ms-skip-url-encoding: true + x-ms-parameter-location: client + x-ms-skip-url-encoding: true diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/header_parameter.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/header_parameter.yaml new file mode 100644 index 000000000..4966db141 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/header_parameter.yaml @@ -0,0 +1,73 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - in: header + description: Tests header 01 + name: X-Request-ID + schema: + type: string + format: uuid + required: true + - in: header + description: Tests header 02 + name: X-Request-Client + schema: + type: array + items: + type: string + format: uuid + required: true + responses: + '200': + description: Expected response to a valid request + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + security: + - X-API-KEY: [] +components: + schemas: + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string + securitySchemes: + X-API-KEY: + type: apiKey + in: header + name: X-API-KEY + description: Go to http://petstore.com and get the api key \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/json_payload.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/json_payload.yaml new file mode 100644 index 000000000..cc6493c3d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/json_payload.yaml @@ -0,0 +1,34 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + content: + application/json: + schema: {} + required: true + responses: + '201': + description: Null response diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/openapi_display_annotation.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/openapi_display_annotation.yaml new file mode 100644 index 000000000..a381b541f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/openapi_display_annotation.yaml @@ -0,0 +1,336 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + x-ballerina-display: + label: "Current Weather Details" + iconPath: "Path" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + x-ballerina-display: + label: "Current weather" + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API DocCommentsGenerator + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + x-ballerina-display: + label: "City name" + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + description: name + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + description: coord + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + description: weather + type: object + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + description: tests + type: object + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + description: wind + title: Wind + type: object + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + description: cloud + title: Clouds + type: object + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + description: rain + title: Rain + type: object + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + description: snow + type: object + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + description: sys + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. If you don't have an OpenWeatherMap API key, use `fd4698c940c6d1da602a70ac34f0b147`. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/operation_delete.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/operation_delete.yaml new file mode 100644 index 000000000..361630618 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/operation_delete.yaml @@ -0,0 +1,96 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets/{petId}: + delete: + summary: Delete pet + operationId: deletePetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + "204": + description: |- + **HTTP status code:** `204` OK + /action: + x-MULTI: + operationId: getAction + responses: + '200': + description: Successful + examples: + application/json: Ok + x-METHODS: + - HEAD + - OPTIONS + - PATCH + - DELETE + - POST + - PUT + - GET +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_get.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_get.yaml new file mode 100644 index 000000000..112e798f0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_get.yaml @@ -0,0 +1,141 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://localhost:9090/petstore/v1 +paths: + /pet: + get: + description: Simple get function + operationId: getSimple + responses: + '200': + description: Expected response to a valid request + /pets/{petId}: + get: + summary: Get funtion with path parameters + operationId: getPetId + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + /pets/{petId}/Image/{imageId}: + get: + summary: Multiple path parameters + operationId: getMultiplePath + tags: + - pets + parameters: + - name: petId + in: path + description: ID of pet to delete + required: true + schema: + type: integer + - name: imageId + in: path + description: ID of pet to delete + required: true + schema: + type: string + responses: + '200': + description: An paged array of pets + /pets: + get: + summary: Query parameters + operationId: getQueryParams + tags: + - pets + parameters: + - name: offset + in: query + description: ID of pet to delete + required: true + schema: + type: integer + responses: + '200': + description: An paged array of pets + /users: + get: + summary: Query parameters optional + operationId: getQueryParamsOptional + tags: + - pets + parameters: + - name: offset + in: query + description: offset count + required: false + schema: + type: array + items: + type: string + responses: + '200': + description: An paged array of user + + /image: + get: + summary: Multiple path parameters + operationId: getImage + parameters: + - name: tag + in: query + description: ID of pet to delete + required: false + schema: + type: string + - name: limit + in: query + description: ID of pet to delete + required: false + schema: + type: integer + responses: + '200': + description: An paged array of pets + /header: + get: + operationId: getPets + parameters: + - in: header + name: XClient + description: Header + schema: + type: string + format: uuid + required: true + responses: + '200': + description: An paged array of pets +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_post.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_post.yaml new file mode 100644 index 000000000..cb15e84c5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_post.yaml @@ -0,0 +1,85 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://localhost:9090/petstore/v1 +paths: + /pet: + post: + description: Simple post function + operationId: postSimple + responses: + '200': + description: Expected response to a valid request + requestBody: + description: test + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + /pets/{petId}: + post: + summary: Get funtion with path parameters + operationId: getPetId + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + requestBody: + description: test + content: + text/plain: + schema: + type: string + + /pets/{petId}/Image/{imageId}: + get: + summary: Multiple path parameters + operationId: getMultiplePath + tags: + - pets + parameters: + - name: petId + in: path + description: ID of pet to delete + required: true + schema: + type: integer + - name: imageId + in: path + description: ID of pet to delete + required: true + schema: + type: string + responses: + '200': + description: An paged array of pets +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_server_with_base_path.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_server_with_base_path.yaml new file mode 100644 index 000000000..3967ee8ca --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_server_with_base_path.yaml @@ -0,0 +1,130 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag +security: +- petstore_auth: + - write:pets + - read:pets +- user_auth: + - read:user + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_server_without_base_path.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_server_without_base_path.yaml new file mode 100644 index 000000000..10e3a021b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_server_without_base_path.yaml @@ -0,0 +1,152 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag +security: +- petstore_auth: + - write:pets + - read:pets +- user_auth: + - read:user + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /action: + x-MULTI: + operationId: getAction + responses: + '200': + description: Successful + examples: + application/json: Ok + x-METHODS: + - HEAD + - OPTIONS + - PATCH + - DELETE + - POST + - PUT + - GET +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_with_oneOf_response.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_with_oneOf_response.yaml new file mode 100644 index 000000000..c2db5993e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/petstore_with_oneOf_response.yaml @@ -0,0 +1,71 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://localhost:9090/petstore/v1 +paths: + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: getPet + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/Pet' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Cat' + +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Dog: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + bark: + type: boolean + Cat: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + hunt: + type: boolean diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/request_body_ref.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/request_body_ref.yaml new file mode 100644 index 000000000..8de6c204f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/request_body_ref.yaml @@ -0,0 +1,113 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + description: "Request to add a pet" + $ref: "#/components/requestBodies/CreatedPet" + responses: + '200': + description: Successful operation + /my/pets: + post: + summary: Create a pet + operationId: createMyPet + tags: + - pets + requestBody: + description: "Request to add a pet" + $ref: "#/components/requestBodies/CreatedPetRef" + responses: + '200': + description: Successful operation + +components: + requestBodies: + CreatedPet: + description: Return from creating a pet + content: + application/json: + schema: + type: object + properties: + petId: + type: string + createdDate: + type: string + CreatedPetRef: + description: "Return from creating a pet" + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/response_nested_array.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/response_nested_array.yaml new file mode 100644 index 000000000..2fcc5d202 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/response_nested_array.yaml @@ -0,0 +1,57 @@ +openapi: 3.0.0 +servers: + - url: https://api.nytimes.com/svc/suggest/v1 +info: + description: With the TimesTags API, you can mine the riches of the New York Times tag set. The TimesTags service matches your query to the controlled vocabularies that fuel NYTimes.com metadata. You supply a string of characters, and the service returns a ranked list of suggested terms. + termsOfService: http://developer.nytimes.com/tou + title: TimesTags API + version: 1.0.0 +security: + - apikey: [] +paths: + /timestags: + get: + operationId: getTimesTags + parameters: + - description: Your search query + in: query + name: query + required: true + schema: + type: string + - description: Add filters + in: query + name: filter + required: false + schema: + enum: + - Des + - Geo + - Org + - Per + type: string + - description: Sets the maximum number of results + in: query + name: max + required: false + schema: + default: 10 + type: integer + responses: + "200": + content: + application/json: + schema: + items: + items: + type: string + type: array + type: array + description: An array of tags +components: + securitySchemes: + apikey: + in: query + name: api-key + type: apiKey + description: Log in to https://api.nytimes.com/svc/suggest/v1 and get the api key diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/xml_payload.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/xml_payload.yaml new file mode 100644 index 000000000..0d2f400ad --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/xml_payload.yaml @@ -0,0 +1,35 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + content: + application/xml: + schema: {} + description: Pet data + required: true + responses: + '201': + description: Null response diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/xml_payload_with_ref.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/xml_payload_with_ref.yaml new file mode 100644 index 000000000..d4fe39e00 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/client/diagnostic_files/xml_payload_with_ref.yaml @@ -0,0 +1,52 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + post: + summary: Create a pet + operationId: createPet + tags: + - pets + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet data + required: true + responses: + '201': + description: Null response +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOfWithEmptyObject.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOfWithEmptyObject.yaml new file mode 100644 index 000000000..9cc1c3e88 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOfWithEmptyObject.yaml @@ -0,0 +1,70 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - type: object + required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOfWithNoType.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOfWithNoType.yaml new file mode 100644 index 000000000..6420f5892 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOfWithNoType.yaml @@ -0,0 +1,76 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - properties: + pure: + type: boolean + - required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + properties: + timing: + type: boolean + + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOf_with_cyclic.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOf_with_cyclic.yaml new file mode 100644 index 000000000..9f27a7a8c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOf_with_cyclic.yaml @@ -0,0 +1,75 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - type: object + required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + properties: + time: + allOf: + - $ref: "#/components/schemas/UnSubscribe" + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOf_with_one_ref.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOf_with_one_ref.yaml new file mode 100644 index 000000000..7795c0268 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/allOf_with_one_ref.yaml @@ -0,0 +1,75 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - type: object + required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + properties: + time: + allOf: + - $ref: "#/components/schemas/Time" + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/nested_allOf_with_allOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/nested_allOf_with_allOf.yaml new file mode 100644 index 000000000..d8aeecbd7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/nested_allOf_with_allOf.yaml @@ -0,0 +1,83 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - allOf: + - properties: + streetNo: + type: string + houseNo: + type: string + - properties: + streatName: + type: string + country: + type: string + - required: + - event + properties: + zipCode: + type: integer + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + properties: + timing: + type: boolean + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/nested_allOf_with_oneOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/nested_allOf_with_oneOf.yaml new file mode 100644 index 000000000..9244a56a5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/nested_allOf_with_oneOf.yaml @@ -0,0 +1,83 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - oneOf: + - properties: + streetNo: + type: string + houseNo: + type: string + - properties: + streatName: + type: string + country: + type: string + - required: + - event + properties: + zipCode: + type: integer + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + properties: + timing: + type: booleanZ + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/oneAllOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/oneAllOf.yaml new file mode 100644 index 000000000..bc4e52598 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/oneAllOf.yaml @@ -0,0 +1,74 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - type: object + required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - type: object + properties: + timing: + type: boolean + + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/twoAllOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/twoAllOf.yaml new file mode 100644 index 000000000..fc5eb0acc --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AllOf/twoAllOf.yaml @@ -0,0 +1,75 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - type: object + required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + allOf: + - $ref: "#/components/schemas/Time" + - $ref: '#/components/schemas/Activity' + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + Activity: + properties: + uuid: + type: string + description: Unique identifier for the activity + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AnyOf/oneAnyOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AnyOf/oneAnyOf.yaml new file mode 100644 index 000000000..1cb75b2ec --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/AnyOf/oneAnyOf.yaml @@ -0,0 +1,70 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + allOf: + - type: object + required: + - event + properties: + timing: + type: boolean + event: + type: string + UnSubscribe: + anyOf: + - $ref: '#/components/schemas/Time' + + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_exceed_max_item.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_exceed_max_item.yaml new file mode 100644 index 000000000..658a7b9f0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_exceed_max_item.yaml @@ -0,0 +1,66 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Request: + type: array + maxItems: 2147483638 + items: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_exceed_max_item_02.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_exceed_max_item_02.yaml new file mode 100644 index 000000000..f2c6938f9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_exceed_max_item_02.yaml @@ -0,0 +1,65 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + tag: + type: array + maxItems: 2147483640 + items: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_max_item.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_max_item.yaml new file mode 100644 index 000000000..a38b66e7d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_max_item.yaml @@ -0,0 +1,69 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + tag: + type: array + maxItems: 7 + items: + type: integer + event: + type: string + activity: + $ref: '#/components/schemas/Activity' + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Activity: + type: array + maxItems: 7 + items: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_no_item_type.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_no_item_type.yaml new file mode 100644 index 000000000..563c68126 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_no_item_type.yaml @@ -0,0 +1,65 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + activity: + $ref: '#/components/schemas/Activity' + event: + type: string + tag: + type: array + items: { } + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Activity: + type: array + items: { } + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_allOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_allOf.yaml new file mode 100644 index 000000000..99eb986fa --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_allOf.yaml @@ -0,0 +1,87 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + data: + type: array + items: + title: activityResponseObject + allOf: + - $ref: "#/components/schemas/ActivityResponseObject" + - $ref: "#/components/schemas/EmployeeDetails" + event: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + ActivityResponseObject: + properties: + due_date: + description: 'Due date of the Activity. Format: YYYY-MM-DD' + type: string + format: date + due_time: + description: 'Due time of the Activity in UTC. Format: HH:MM' + type: string + duration: + description: 'Duration of the Activity. Format: HH:MM' + type: string + deal_id: + description: The ID of the Deal this Activity is associated with + type: integer + EmployeeDetails: + properties: + employee_id: + description: 'Employee ID' + type: string + employee_name: + description: 'Employee Name' + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_oneOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_oneOf.yaml new file mode 100644 index 000000000..3626af960 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_oneOf.yaml @@ -0,0 +1,87 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + data: + type: array + items: + title: activityResponseObject + oneOf: + - $ref: "#/components/schemas/ActivityResponseObject" + - $ref: "#/components/schemas/EmployeeDetails" + event: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + ActivityResponseObject: + properties: + due_date: + description: 'Due date of the Activity. Format: YYYY-MM-DD' + type: string + format: date + due_time: + description: 'Due time of the Activity in UTC. Format: HH:MM' + type: string + duration: + description: 'Duration of the Activity. Format: HH:MM' + type: string + deal_id: + description: The ID of the Deal this Activity is associated with + type: integer + EmployeeDetails: + properties: + employee_id: + description: 'Employee ID' + type: string + employee_name: + description: 'Employee Name' + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_oneOf_complex.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_oneOf_complex.yaml new file mode 100644 index 000000000..512b7af41 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/array_with_oneOf_complex.yaml @@ -0,0 +1,100 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + data: + type: array + items: + oneOf: + - type: array + items: + $ref: "#/components/schemas/EmployeeDetails" + nullable: true + - $ref: "#/components/schemas/ActivityResponseObject" + event: + type: string + request: + $ref: "#/components/schemas/Request" + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + ActivityResponseObject: + properties: + due_date: + description: 'Due date of the Activity. Format: YYYY-MM-DD' + type: string + format: date + due_time: + description: 'Due time of the Activity in UTC. Format: HH:MM' + type: string + duration: + description: 'Duration of the Activity. Format: HH:MM' + type: string + deal_id: + description: The ID of the Deal this Activity is associated with + type: integer + EmployeeDetails: + properties: + employee_id: + description: 'Employee ID' + type: string + employee_name: + description: 'Employee Name' + type: string + Request: + type: array + items: + oneOf: + - type: array + items: + $ref: "#/components/schemas/EmployeeDetails" + nullable: true + - $ref: "#/components/schemas/ActivityResponseObject" + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/nestedArray.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/nestedArray.yaml new file mode 100644 index 000000000..3b0a6b909 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/nestedArray.yaml @@ -0,0 +1,67 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + tag: + type: array + items: + type: array + items: + type: array + items: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/oneArray.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/oneArray.yaml new file mode 100644 index 000000000..9090840c5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/oneArray.yaml @@ -0,0 +1,63 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + tag: + type: array + items: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/refArray.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/refArray.yaml new file mode 100644 index 000000000..0019539c5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/refArray.yaml @@ -0,0 +1,78 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + code: + type: array + description: Code array + items: + $ref: "#/components/schemas/Activity" + codePen: + type: boolean + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Activity: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/schemaArray.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/schemaArray.yaml new file mode 100644 index 000000000..758ea2844 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Array/schemaArray.yaml @@ -0,0 +1,72 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + code: + type: array + description: Code array + items: + $ref: "#/components/schemas/Activity" + codePen: + type: boolean + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Activity: + type: array + items: + $ref: "#/components/schemas/Request" + Request: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/basic_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/basic_auth.yaml new file mode 100644 index 000000000..7eae32993 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/basic_auth.yaml @@ -0,0 +1,417 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + description: Account Id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - basicAuth: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + basicAuth: + type: http + scheme: basic \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/bearer_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/bearer_auth.yaml new file mode 100644 index 000000000..072eb3984 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/bearer_auth.yaml @@ -0,0 +1,419 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + description: Account Id + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - bearerAuth: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + bearerAuth: + type: http + scheme: bearer + links: {} + callbacks: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/combination_of_apikey_and_http_oauth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/combination_of_apikey_and_http_oauth.yaml new file mode 100644 index 000000000..676946c7d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/combination_of_apikey_and_http_oauth.yaml @@ -0,0 +1,161 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets/management: + get: + operationId: getPetInfo + summary: Info for a specific pet + tags: + - pets + parameters: + - name: petId + in: query + required: true + description: The id of the pet to retrieve + schema: + type: string + - name: headerX + in: header + required: true + description: Header X + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + security: + - api_key: [] + - api_key_2: [] + delete: + operationId: deletePetInfo + summary: Delete a pet + tags: + - pets + parameters: + - name: petId + in: query + required: true + description: The id of the pet to delete + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + security: + - api_key: [] + - api_key_2: [] + post: + operationId: votePet + summary: Vote for a pet + tags: + - pets + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + security: + - api_key: [] + - api_key_2: [] + /pets/management2: + delete: + operationId: deletePetInfo2 + summary: Delete a pet 2 + tags: + - pets + parameters: + - name: petId + in: header + required: true + description: The id of the pet to delete + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + security: + - api_key: [] + - api_key_2: [] +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + securitySchemes: + api_key: + in: header + name: api-key + description: Represents API Key `api-key` + type: apiKey + api_key_2: + in: query + name: api-key-2 + description: Represents API Key `api-key-2` + type: apiKey + oauth2: + flows: + authorizationCode: + authorizationUrl: https://dev.to/oauth/authorize + refreshUrl: https://dev.to/oauth/token + scopes: {} + tokenUrl: https://dev.to/oauth/token + clientCredentials: + refreshUrl: https://dev.to/oauth/token + scopes: {} + tokenUrl: https://dev.to/oauth/token + type: oauth2 diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/header_api_key.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/header_api_key.yaml new file mode 100644 index 000000000..10fdd0bda --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/header_api_key.yaml @@ -0,0 +1,330 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - API-X-KEY: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API Documentation + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + description: Name + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + description: Geo location + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + description: Weather + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + description: Main weather data + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + description: wind related data + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + description: Cloud related data + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + description: Rain related data + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + description: Snow related data + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + description: System data + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + API-X-KEY: + type: apiKey + description: API key to authorize requests. If you don't have an OpenWeatherMap API key, use `fd4698c940c6d1da602a70ac34f0b147`. + name: API-X-KEY + in: header diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/multiple_api_keys.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/multiple_api_keys.yaml new file mode 100644 index 000000000..80b72c5c4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/multiple_api_keys.yaml @@ -0,0 +1,335 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API Documentation + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + description: Name + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + description: Geo location + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + description: Weather + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + description: Main weather data + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + description: wind related data + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + description: Cloud related data + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + description: Rain related data + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + description: Snow related data + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + description: System data + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. If you don't have an OpenWeatherMap API key, use `fd4698c940c6d1da602a70ac34f0b147`. + name: appid + in: query + API-X-Key: + type: apiKey + description: API key to authorize requests. If you don't have an OpenWeatherMap API key, use `fd4698c940c6d1da602a70ac34f0b147`. + name: API-X-Key + in: header diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/multiple_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/multiple_auth.yaml new file mode 100644 index 000000000..d3516eaf7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/multiple_auth.yaml @@ -0,0 +1,423 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + description: Account Id + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - bearerAuth: [] + - basicAuth: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + bearerAuth: + type: http + scheme: bearer + basicAuth: + type: http + scheme: basic + links: {} + callbacks: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/no_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/no_auth.yaml new file mode 100644 index 000000000..20267e31d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/no_auth.yaml @@ -0,0 +1,166 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag +security: + - petstore_auth: + - write:pets + - read:pets + - user_auth: + - read:user + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + operationId: createPet + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /action: + x-MULTI: + operationId: getAction + responses: + '200': + description: Successful + examples: + application/json: Ok + x-METHODS: + - HEAD + - OPTIONS + - PATCH + - DELETE + - POST + - PUT + - GET +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_authorization_code.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_authorization_code.yaml new file mode 100644 index 000000000..befba8ab9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_authorization_code.yaml @@ -0,0 +1,422 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + description: Account Id + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2AuthCode: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2AuthCode: + type: oauth2 + description: For more information, see https://api.slack.com/docs/oauth + flows: + authorizationCode: + authorizationUrl: https://login.salesforce.com/services/oauth2/autherize + tokenUrl: https://login.salesforce.com/services/oauth2/token + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_client_credential.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_client_credential.yaml new file mode 100644 index 000000000..b9fd317ff --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_client_credential.yaml @@ -0,0 +1,421 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + description: Account Id + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2ClientCredentials: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2ClientCredentials: + type: oauth2 + description: See salesforce.help.com + flows: + clientCredentials: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_implicit.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_implicit.yaml new file mode 100644 index 000000000..46f668d65 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_implicit.yaml @@ -0,0 +1,421 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + description: Account Id + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2Implicit: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2Implicit: + type: oauth2 + description: See salesforce.help.com + flows: + implicit: + authorizationUrl: https://test.salesforce.com/services/oauth2/authorize + scopes: {} diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_multipleflows.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_multipleflows.yaml new file mode 100644 index 000000000..bbc764087 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_multipleflows.yaml @@ -0,0 +1,426 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + in: path + description: Account Id + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oauth_2_0: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oauth_2_0: + type: oauth2 + description: Authentication based on OAuth 2.0. + flows: + authorizationCode: + authorizationUrl: /oauth/authorize + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} + password: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_password.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_password.yaml new file mode 100644 index 000000000..2f38a31df --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/oauth2_password.yaml @@ -0,0 +1,421 @@ +openapi: 3.0.0 +info: + title: Salesforce REST APIs + version: 0.1-oas3 +servers: + - url: https://{domain}/services/data + variables: + domain: + default: domain +tags: + - name: Account + description: Represents an individual account, which is an organization or person involved with your business (such as customers, competitors, and partners). +paths: + /{version}/sobjects/Account/{id}: + get: + tags: + - Account + summary: Get account information + operationId: getAccountById + parameters: + - name: id + description: Account Id + in: path + required: true + style: simple + explode: false + schema: + type: string + - name: version + in: path + description: version + required: true + style: simple + explode: false + schema: + type: string + default: v48.0 + enum: + - v47.0 + - v48.0 + responses: + "200": + description: "Status Okay" + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Account_inner' + "400": + description: The request couldn’t be understood, usually because the JSON or XML body contains an error. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + "401": + description: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode' + security: + - oAuth2Password: [] +components: + schemas: + attributes: + required: + - type + - url + type: object + properties: + type: + type: string + description: the type of object. + example: Account + url: + type: string + description: The relative path of the object. + example: /services/data/v46.0/sobjects/Account/0010E00000Up3QGQAZ + address: + type: object + properties: + city: + type: string + example: Uden + country: + type: string + example: Netherlands + countryCode: + type: string + example: NL + geocodeAccuracy: + type: string + latitude: + type: string + longtitude: + type: string + postalCode: + type: string + example: 5405 BW + state: + type: string + stateCode: + type: string + street: + type: string + example: Jagersveld 15 + MessagewithErrorCode: + type: array + items: + $ref: '#/components/schemas/MessagewithErrorCode_inner' + Account_inner: + required: + - Attributes + - Id + - Name + type: object + properties: + Attributes: + $ref: '#/components/schemas/attributes' + Id: + type: string + description: The Salesforce ID of the account + example: 0010E00000Up3QGQAZ + IsDeleted: + type: boolean + description: Indicates whether the object has been moved to the Recycle Bin (true) or not (false). + example: false + MasterRecordId: + type: string + description: If this object was deleted as the result of a merge, this field contains the ID of the record that was kept. If this object was deleted for any other reason, or has not been deleted, the value is null. + Name: + type: string + description: 'Name of the account. Maximum size is 255 characters. If the account has a record type of Person Account: This value is the concatenation of the FirstName, MiddleName, LastName, and Suffix of the associated person contact. You can''t modify this value.' + example: Klaas Vaak + LastName: + type: string + description: Last name of the account. + example: Vaak + FirstName: + type: string + description: First name of the account + example: Klaas + Salutation: + type: string + description: Honorific added to the name for use in letters, etc. + example: Mr. + MiddleName: + type: string + description: Middle name of the account. + Suffix: + type: string + description: Name suffix of the person for a person account. Maximum size is 40 characters. + Type: + type: string + description: Type of account, for example, Customer, Competitor, or Partner. + example: Customer + RecordTypeId: + type: string + description: Classification of the type of account. The record type influences the business process, picklist values and page layouts. The id references the record type which can correspond to business account or person account. + example: 0121i000000Y4jLAAS + ParentId: + type: string + description: ID of the parent object, if any. + BillingStreet: + type: string + description: Street address for the billing address of this account. + example: Jagersveld 15 + BillingCity: + type: string + description: City for the billing address of this account. + example: Uden + BillingState: + type: string + description: State for the billing address of this account. + BillingPostalCode: + type: string + description: Postal code for the billing address of this account. + example: 5405 BW + BillingCountry: + type: string + description: Country for the billing address of this account. + example: the Netherlands + BillingStateCode: + type: string + description: Code of the state for the billing address of this account. + BillingCountryCode: + type: string + description: Country code for the billing address of this account. + example: NL + BillingLatitude: + type: string + description: 'Used with BillingLongitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + BillingLongitude: + type: string + description: 'Used with BillingLatitude to specify the precise geolocation of a billing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + BillingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the billing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + BillingAddress: + $ref: '#/components/schemas/address' + ShippingStreet: + type: string + description: 'The street address of the shipping address for this account. ' + example: Jagersveld 15 + ShippingCity: + type: string + description: 'City of the shipping address for this account. ' + example: Uden + ShippingState: + type: string + description: 'State of the shipping address for this account. ' + ShippingPostalCode: + type: string + description: 'Postal code of the shipping address for this account. ' + example: 5405 BW + ShippingCountry: + type: string + description: 'Country of the shipping address for this account. ' + example: the Netherlands + ShippingStateCode: + type: string + description: 'Code of the state of the shipping address for this account. ' + ShippingCountryCode: + type: string + description: 'Country code of the shipping address for this account. ' + example: NL + ShippingLatitude: + type: string + description: 'Used with ShippingLongitude to specify the precise geolocation of a shipping address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + ShippingLongitude: + type: string + description: 'Used with ShippingLatitude to specify the precise geolocation of an address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + ShippingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the shipping address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + ShippingAddress: + $ref: '#/components/schemas/address' + Phone: + type: string + description: 'Phone number of the account. ' + example: "623456789" + Website: + type: string + description: The website of this account. Maximum of 255 characters. + example: https://www.swisssense.nl + PhotoUrl: + type: string + description: Path to be combined with the URL of a Salesforce instance (for example, https://yourInstance.salesforce.com/) to generate a URL to request the social network profile image associated with the account. Generated URL returns an HTTP redirect (code 302) to the social network profile image for the account. Blank if Social Accounts and Contacts isn't enabled for the organization or if Social Accounts and Contacts is disabled for the requesting user. + example: /services/images/photo/0010E00000XDEnHQAX + Industry: + type: string + description: An industry associated with this account. Maximum size is 40 characters. + NumberOfEmployees: + type: integer + description: Number of employees working at the company represented by this account. Maximum size is eight digits. + Description: + type: string + description: Text description of the account. + example: Sample Description + OwnerId: + type: string + description: 'The ID of the user who currently owns this account. ' + example: 0051i000000kb4lAAA + CreatedDate: + type: string + description: 'Date and time when this record was created. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + CreatedById: + type: string + description: 'ID of the User who created this record. ' + example: 0051i000000kb4lAAA + LastModifiedDate: + type: string + description: 'Date and time when a user last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastModifiedById: + type: string + description: 'ID of the User who last updated this record. ' + example: 0051i000000kb4lAAA + SystemModstamp: + type: string + description: 'Date and time when a user or automated process (such as a trigger) last modified this record. ' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastActivityDate: + type: string + description: 'Value is one of the following, whichever is the most recent: Due date of the most recent event logged against the record. Due date of the most recently closed task associated with the record.' + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastViewedDate: + type: string + description: The timestamp for when the current user last viewed this record or list view. If this value is null, this record or list view might only have been referenced (LastReferencedDate) and not viewed. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + LastReferencedDate: + type: string + description: The timestamp for when the current user last viewed a record related to this record or list view. + format: rfc2822 + example: 2019-09-04T13:49:25.000+0000 + PersonContactId: + type: string + description: The ID for the contact associated with this person account. + example: 0030E00000UkUPpQAN + IsPersonAccount: + type: boolean + description: Indicates whether this account has a record type of Person Account (true) or not (false). + example: true + PersonMailingStreet: + type: string + description: 'The mailing street address for this person account. ' + example: Jagersveld 15 + PersonMailingCity: + type: string + description: 'The city mailing address for this person account. ' + example: Uden + PersonMailingState: + type: string + description: 'The state of the mailing address for this person account. ' + PersonMailingPostalCode: + type: string + description: 'The postal code of the mailing address for this person account. ' + example: 5405 BW + PersonMailingCountry: + type: string + description: 'The country of the mailing address for this person account. ' + example: the Netherlands + PersonMailingStateCode: + type: string + description: 'The state code of the mailing address for this person account. ' + PersonMailingCountryCode: + type: string + description: 'The country code of the mailing address for this person account. ' + example: NL + PersonMailingLatitude: + type: string + description: 'Used with PersonMailingLongitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –90 and 90 with up to 15 decimal places. ' + PersonMailingLongitude: + type: string + description: 'Used with PersonMailingLatitude to specify the precise geolocation of a person account’s mailing address. Acceptable values are numbers between –180 and 180 with up to 15 decimal places. ' + PersonMailingGeocodeAccuracy: + type: string + description: Accuracy level of the geocode for the person’s mailing address. See Compound Field Considerations and Limitations for details on geolocation compound fields. + PersonMailingAddress: + $ref: '#/components/schemas/address' + PersonMobilePhone: + type: string + description: 'The mobile phone number for this person account. ' + example: "623456789" + PersonEmail: + type: string + description: 'Email address for this person account. ' + PersonTitle: + type: string + description: 'The person account’s title. ' + PersonDepartment: + type: string + description: The department. Maximum size is 80 characters. + PersonBirthdate: + type: string + description: The birth date of the person account. + format: date + example: 1923-09-26 + PersonLastCURequestDate: + type: string + description: The last date that this person account was requested. + format: rfc2822 + PersonLastCUUpdateDate: + type: string + description: The last date a person account was updated. + format: rfc2822 + PersonEmailBouncedReason: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the reason the bounce occurred + PersonEmailBouncedDate: + type: string + description: If bounce management is activated and an email sent to the person account bounces, the date and time the bounce occurred. + format: rfc2822 + PersonIndividualId: + type: string + description: ID of the data privacy record associated with this person’s account. This field is available if you enabled Data Protection and Privacy in Setup. + Jigsaw: + type: string + description: References the ID of a company in Data.com. If an account has a value in this field, it means that the account was imported from Data.com. If the field value is null, the account was not imported from Data.com. Maximum size is 20 characters. Available in API version 22.0 and later. Label is Data.com Key.The Jigsaw field is exposed in the API to support troubleshooting for import errors and reimporting of corrected data. Do not modify the value in the Jigsaw field. + JigsawCompanyId: + type: string + AccountSource: + type: string + description: The source of the account record. For example, Advertisement, Data.com, or Trade Show. The source is selected from a picklist of available values, which are set by an administrator. Each picklist value can have up to 40 characters. + SicDesc: + type: string + description: A brief description of an organization’s line of business, based on its SIC code. Maximum length is 80 characters. + MessagewithErrorCode_inner: + required: + - errorCode + - message + type: object + properties: + message: + type: string + errorCode: + type: string + responses: {} + parameters: {} + examples: {} + requestBodies: {} + headers: {} + securitySchemes: + oAuth2Password: + type: oauth2 + description: Authentication based on OAuth 2.0. + flows: + password: + tokenUrl: https://test.salesforce.com/services/oauth2/token + scopes: {} \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/query_api_key.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/query_api_key.yaml new file mode 100644 index 000000000..e6cee51ea --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Auth/query_api_key.yaml @@ -0,0 +1,330 @@ +openapi: "3.0.1" + +info: + title: "OpenWeatherMap API" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API.

**Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results." + version: "2.5.2" + termsOfService: "https://openweathermap.org/terms" + contact: + name: "OpenWeatherMap API" + url: "https://openweathermap.org/api" + email: "some_email@gmail.com" + license: + name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)" + url: "https://openweathermap.org/price" + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /weather: + get: + tags: + - Current Weather Data + summary: "Call current weather data for one location" + description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations." + operationId: CurrentWeatherData + parameters: + - $ref: '#/components/parameters/q' + - $ref: '#/components/parameters/id' + - $ref: '#/components/parameters/lat' + - $ref: '#/components/parameters/lon' + - $ref: '#/components/parameters/zip' + - $ref: '#/components/parameters/units' + - $ref: '#/components/parameters/lang' + - $ref: '#/components/parameters/mode' + + responses: + 200: + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/200' + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + +externalDocs: + description: API Documentation + url: https://openweathermap.org/api + +components: + + parameters: + q: + name: q + in: query + description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by comma; use ISO 3166 country codes." + schema: + type: string + id: + name: id + in: query + description: "**City ID**. *Example: `2172797`*. You can call by city ID. API responds with exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs. it's treated as 3 API calls.*" + schema: + type: string + + lat: + name: lat + in: query + description: "**Latitude**. *Example: 35*. The latitude cordinate of the location of your interest. Must use with `lon`." + schema: + type: string + + lon: + name: lon + in: query + description: "**Longitude**. *Example: 139*. Longitude cordinate of the location of your interest. Must use with `lat`." + schema: + type: string + + zip: + name: zip + in: query + description: "**Zip code**. Search by zip code. *Example: 95050,us*. Please note if country is not specified then the search works for USA as a default." + schema: + type: string + + units: + name: units + in: query + description: '**Units**. *Example: imperial*. Possible values: `standard`, `metric`, and `imperial`. When you do not use units parameter, format is `standard` by default.' + schema: + type: string + enum: [standard, metric, imperial] + default: "imperial" + + lang: + name: lang + in: query + description: '**Language**. *Example: en*. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - `ar`, Bulgarian - `bg`, Catalan - `ca`, Czech - `cz`, German - `de`, Greek - `el`, English - `en`, Persian (Farsi) - `fa`, Finnish - `fi`, French - `fr`, Galician - `gl`, Croatian - `hr`, Hungarian - `hu`, Italian - `it`, Japanese - `ja`, Korean - `kr`, Latvian - `la`, Lithuanian - `lt`, Macedonian - `mk`, Dutch - `nl`, Polish - `pl`, Portuguese - `pt`, Romanian - `ro`, Russian - `ru`, Swedish - `se`, Slovak - `sk`, Slovenian - `sl`, Spanish - `es`, Turkish - `tr`, Ukrainian - `ua`, Vietnamese - `vi`, Chinese Simplified - `zh_cn`, Chinese Traditional - `zh_tw`.' + schema: + type: string + enum: [ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw] + default: "en" + + mode: + name: mode + in: query + description: "**Mode**. *Example: html*. Determines format of response. Possible values are `xml` and `html`. If mode parameter is empty the format is `json` by default." + schema: + type: string + enum: [json, xml, html] + default: "json" + + schemas: + 200: + title: Successful response + type: object + properties: + coord: + $ref: '#/components/schemas/Coord' + weather: + type: array + items: + $ref: '#/components/schemas/Weather' + description: (more info Weather condition codes) + base: + type: string + description: Internal parameter + example: cmc stations + main: + $ref: '#/components/schemas/Main' + visibility: + type: integer + description: Visibility, meter + example: 16093 + wind: + $ref: '#/components/schemas/Wind' + clouds: + $ref: '#/components/schemas/Clouds' + rain: + $ref: '#/components/schemas/Rain' + snow: + $ref: '#/components/schemas/Snow' + dt: + type: integer + description: Time of data calculation, unix, UTC + format: int32 + example: 1435658272 + sys: + $ref: '#/components/schemas/Sys' + id: + type: integer + description: City ID + format: int32 + example: 2172797 + name: + type: string + example: Cairns + description: Name + cod: + type: integer + description: Internal parameter + format: int32 + example: 200 + Coord: + title: Coord + type: object + description: Geo location + properties: + lon: + type: number + description: City geo location, longitude + example: 145.77000000000001 + lat: + type: number + description: City geo location, latitude + example: -16.920000000000002 + Weather: + title: Weather + type: object + description: Weather + properties: + id: + type: integer + description: Weather condition id + format: int32 + example: 803 + main: + type: string + description: Group of weather parameters (Rain, Snow, Extreme etc.) + example: Clouds + description: + type: string + description: Weather condition within the group + example: broken clouds + icon: + type: string + description: Weather icon id + example: 04n + Main: + title: Main + type: object + description: Main weather data + properties: + temp: + type: number + description: 'Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 293.25 + pressure: + type: integer + description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa + format: int32 + example: 1019 + humidity: + type: integer + description: Humidity, % + format: int32 + example: 83 + temp_min: + type: number + description: 'Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 289.81999999999999 + temp_max: + type: number + description: 'Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.' + example: 295.37 + sea_level: + type: number + description: Atmospheric pressure on the sea level, hPa + example: 984 + grnd_level: + type: number + description: Atmospheric pressure on the ground level, hPa + example: 990 + Wind: + title: Wind + type: object + description: wind related data + properties: + speed: + type: number + description: 'Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.' + example: 5.0999999999999996 + deg: + type: integer + description: Wind direction, degrees (meteorological) + format: int32 + example: 150 + Clouds: + title: Clouds + type: object + description: Cloud related data + properties: + all: + type: integer + description: Cloudiness, % + format: int32 + example: 75 + Rain: + title: Rain + type: object + description: Rain related data + properties: + 3h: + type: integer + description: Rain volume for the last 3 hours + format: int32 + example: 3 + Snow: + title: Snow + type: object + description: Snow related data + properties: + 3h: + type: number + description: Snow volume for the last 3 hours + example: 6 + Sys: + title: Sys + type: object + description: System data + properties: + type: + type: integer + description: Internal parameter + format: int32 + example: 1 + id: + type: integer + description: Internal parameter + format: int32 + example: 8166 + message: + type: number + description: Internal parameter + example: 0.0166 + country: + type: string + description: Country code (GB, JP etc.) + example: AU + sunrise: + type: integer + description: Sunrise time, unix, UTC + format: int32 + example: 1435610796 + sunset: + type: integer + description: Sunset time, unix, UTC + format: int32 + example: 1435650870 + + securitySchemes: + app_id: + type: apiKey + description: API key to authorize requests. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/additional_properties_with_constraint.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/additional_properties_with_constraint.yaml new file mode 100644 index 000000000..2e8e5d640 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/additional_properties_with_constraint.yaml @@ -0,0 +1,93 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + additionalArray: + $ref: '#/components/schemas/Additional_Array' + event: + type: string + additionalNestedArray: + $ref: '#/components/schemas/Additional_NestedArray' + additionalPrimitive: + $ref: '#/components/schemas/Additional_Primitive' + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Additional_Primitive: + properties: + name: + type: string + age: + type: number + additionalProperties: + type: string + minLength: 10 + Additional_Array: + properties: + isArray: + type: boolean + additionalProperties: + items: + maxLength: 5000 + type: string + type: array + Additional_NestedArray: + properties: + isArray: + type: boolean + additionalProperties: + type: array + items: + maxItems: 50 + type: array + items: + type: string + maxLength: 500 + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/array.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/array.yaml new file mode 100644 index 000000000..9088fa2a9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/array.yaml @@ -0,0 +1,97 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Hobby: #scenario 01 : User define array (Annotations on a type) + type: array + items: + type: string + maxLength: 23 # scenario 02: For both array type and array items have constraints + maxItems: 5 + minItems: 2 + Subscribe: + type: object + required: + - event + - tag + properties: + person: + $ref: '#/components/schemas/Person' + event: + type: string + tag: + $ref: '#/components/schemas/Address' + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Person: + type: object + required: + - id + properties: + hobby: + $ref: '#/components/schemas/Hobby' # scenario 03: Reference array + Details: + type: array + items: + type: string + minLength: 7 + maxItems: 5 + id: + type: integer + fee: + type: array + items: + type: number #scenario 04 : Array items have constrained with number format + format: float + maximum: 445.4 + limit: + description: The maximum number of items in the response (as set in the query or by default). + items: + type: integer + maximum: 67 #scenario 05 : Only array items have constrained with number format + Address: # Use case 02 : Annotations on a type + type: string + minLength: 5 + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/nested_array_with_constraint.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/nested_array_with_constraint.yaml new file mode 100644 index 000000000..5c9e1aad6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/nested_array_with_constraint.yaml @@ -0,0 +1,111 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + nestedArray: + $ref: '#/components/schemas/NestedArray' + event: + type: string + nestedArray02: + $ref: '#/components/schemas/NestedArray02' + noConstraint: + $ref: '#/components/schemas/NoConstraint' + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + NestedArray: + type: object + description: "Every array items has constraint validation" + properties: + name: + type: string + examples: + type: array + minItems: 2 + maxItems: 200 + items: + type: array + minItems: 1 + maxItems: 2 + items: + type: string + minLength: 1 + NestedArray02: + type: object + description: "Some array items have constraint" + properties: + name: + type: string + examples: + type: array + minItems: 2 + maxItems: 200 + items: + type: array + items: + type: string + minLength: 1 + NoConstraint: + type: object + description: "Last array item hasn't constraint values" + properties: + name: + type: string + examples: + type: array + minItems: 2 + maxItems: 200 + items: + type: array + minItems: 1 + maxItems: 2 + items: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/record_field.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/record_field.yaml new file mode 100644 index 000000000..5f66e2b9d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/record_field.yaml @@ -0,0 +1,90 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + person: + $ref: '#/components/schemas/Person' + event: + type: string + tag: + $ref: '#/components/schemas/Address' + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Person: + type: object + required: + - id + properties: + name: + type: string + maxLength: 14 # Use case 01 : Annotations on a record field + hobby: + type: array + items: + type: string + maxItems: 5 + minItems: 2 + id: + type: integer + maximum: 5 + address: # Use case 03 : Annotations on a type used as a record field + $ref: "#/components/schemas/Address" + salary: + type: number + format: float + maximum: 100000 + net: + type: number + minimum: 500000 + Address: # Use case 02 : Annotations on a type + type: string + minLength: 5 + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/record_field_02.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/record_field_02.yaml new file mode 100644 index 000000000..fb3d46372 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/record_field_02.yaml @@ -0,0 +1,136 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + properties: + event: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Address: # Use case 02 : Annotations on a type + type: string + minLength: 0 + Person: + type: object + required: + - id + properties: + name: + type: string + maxLength: 14 # Use case 01 : Annotations on a record field + hobby: + type: array + items: + type: string + maxItems: 5 + minItems: 0 + id: + type: integer + maximum: 5 + address: # Use case 03 : Annotations on a type used as a record field + $ref: "#/components/schemas/Address" + salary: + type: number + format: float + maximum: 0 + net: + type: number + exclusiveMinimum: true + minimum: 0 + maxDeliveryCount: + maximum: 1E+2 + minimum: 1 + type: integer + format: int32 + service_class: + description: scenario 01 - field with nullable. + maxLength: 5000 + nullable: true + type: string + tax_rates: + description: scenario 02 - field with oneOf type. + oneOf: + - items: + maxLength: 5000 + type: string + type: array + maxItems: 6 + - type: integer + tax_rates_anyOf: + description: scenario 03 - field with anyOf. + anyOf: + - items: + maxLength: 5000 + type: string + type: array + maxItems: 6 + - type: integer + tax_rates_oneOF_array: + description: scenario 03 - field with a oneOf type array that items has oneOf. + oneOf: + - type: array + maxItems: 6 + items: + oneOf: + - type: string + maxLength: 500 + - type: integer + - type: string + tax_rates_anyOf_array: + description: scenario 04 - field with a anyOf type array items has anyOf. + anyOf: + - items: + anyOf: + - type: integer + maximum: 60 + - type: string + type: array + maxItems: 6 + - type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/type_def_node.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/type_def_node.yaml new file mode 100644 index 000000000..0ef2fc344 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/type_def_node.yaml @@ -0,0 +1,99 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + event: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + person: + $ref: "#/components/schemas/Person" + Person: + type: object + required: + - id + properties: + name: + type: string + maxLength: 14 + hobby: + type: array + items: + type: string + maxItems: 5 + minItems: 2 + id: + type: integer + maximum: 5 + address: + $ref: "#/components/schemas/Address" + salary: + type: number + format: float + maximum: 100000 + net: + type: number + minimum: 500000 + fav: + $ref: "#/components/schemas/Book" + Book: + properties: + name: + type: string + maxLength: 67 + price: + type: number + format: double + maximum: 89.0 + Address: # Use case 02 : Annotations on a type + type: string + minLength: 5 + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/union_type.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/union_type.yaml new file mode 100644 index 000000000..4afa848ec --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Constraint/union_type.yaml @@ -0,0 +1,75 @@ +openapi: 3.0.0 +info: + title: Shopify Admin API + version: "2021-10" +tags: + - name: customers + - name: products + - name: orders + - name: fulfillments + - name: order_risks +paths: + /admin: + post: + operationId: "test1" + requestBody: + content: + "application/json": + schema: + $ref: "#/components/schemas/Person" + responses: + 200: + description: Status OK + +components: + schemas: + Person: + type: object + required: + - service_class + properties: + service_class: + description: scenario 01 - field with nullable. + maxLength: 5000 + nullable: true + type: string + tax_rates: + description: scenario 02 - field with oneOf type. + oneOf: + - items: + maxLength: 5000 + type: string + type: array + maxItems: 6 + - type: integer + tax_rates_anyOf: + description: scenario 03 - field with anyOf. + anyOf: + - items: + maxLength: 5000 + type: string + type: array + maxItems: 6 + - type: integer + tax_rates_oneOF_array: + description: scenario 03 - field with a oneOf type array that items has oneOf. + oneOf: + - type: array + maxItems: 6 + items: + oneOf: + - type: string + maxLength: 500 + - type: integer + - type: string + tax_rates_anyOf_array: + description: scenario 04 - field with a anyOf type array items has anyOf. + anyOf: + - items: + anyOf: + - type: integer + maximum: 60 + - type: string + type: array + maxItems: 6 + - type: integer diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/Error.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/Error.yaml new file mode 100644 index 000000000..22a331fd6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/Error.yaml @@ -0,0 +1,12 @@ +components: + schemas: + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/openapi.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/openapi.yaml new file mode 100644 index 000000000..9cf27ebda --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/openapi.yaml @@ -0,0 +1,144 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: OpenApi Petstore + license: + name: MIT +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + operationId: createPet + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "Error.yaml#/components/schemas/Error" + /action: + x-MULTI: + operationId: getAction + responses: + '200': + description: Successful + examples: + application/json: Ok + x-METHODS: + - HEAD + - OPTIONS + - PATCH + - DELETE + - POST + - PUT + - GET +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/petstore_info_null.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/petstore_info_null.yaml new file mode 100644 index 000000000..63142343e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/petstore_info_null.yaml @@ -0,0 +1,150 @@ +openapi: "3.0.0" +info: +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag +security: + - petstore_auth: + - write:pets + - read:pets + - user_auth: + - read:user + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /action: + x-MULTI: + operationId: getAction + responses: + '200': + description: Successful + examples: + application/json: Ok + x-METHODS: + - HEAD + - OPTIONS + - PATCH + - DELETE + - POST + - PUT + - GET +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/petstore_without_info.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/petstore_without_info.yaml new file mode 100644 index 000000000..dbf524a8a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Errors/petstore_without_info.yaml @@ -0,0 +1,149 @@ +openapi: "3.0.0" +servers: + - url: http://petstore.{host}.io/v1 + description: The production API server + variables: + host: + default: openapi + description: this value is assigned by the service provider + - url: https://{subdomain}.swagger.io:{port}/{basePath} + description: The production API server + variables: + subdomain: + default: petstore + description: this value is assigned by the service provider + port: + enum: + - '8443' + - '443' + default: '443' + basePath: + default: v2 +tags: + - name: pets + description: Pets Tag + - name: list + description: List Tag +security: + - petstore_auth: + - write:pets + - read:pets + - user_auth: + - read:user + +paths: + /pets: + get: + summary: List all pets + description: Show a list of pets in the system + operationId: listPets + tags: + - pets + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /action: + x-MULTI: + operationId: getAction + responses: + '200': + description: Successful + examples: + application/json: Ok + x-METHODS: + - HEAD + - OPTIONS + - PATCH + - DELETE + - POST + - PUT + - GET +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/invalid.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/invalid.yaml new file mode 100644 index 000000000..fa9212e56 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/invalid.yaml @@ -0,0 +1,63 @@ +asyncapi: 2.4.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + tag: + type: array + items: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/petstore.txt b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/petstore.txt new file mode 100644 index 000000000..9090840c5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/petstore.txt @@ -0,0 +1,63 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + tag: + type: array + items: + type: string + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/undocument_ref.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/undocument_ref.yaml new file mode 100644 index 000000000..bf396d18c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Invalid/undocument_ref.yaml @@ -0,0 +1,63 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + - tag + properties: + zipCode: + type: integer + event: + type: string + tag: + type: array + items: + type: string + UnSubscribe: + type: object + required: + - event + properties: + request: + $ref: '#/components/schemas/Request' + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Map/additional_properties_composed_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Map/additional_properties_composed_schema.yaml new file mode 100644 index 000000000..ddc627af9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Map/additional_properties_composed_schema.yaml @@ -0,0 +1,192 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Pet: + description: Mock record + type: object + properties: + name: + type: string + age: + type: integer + Pet02: + description: Mock record 02 + type: object + properties: + name: + type: string + age: + type: integer + additionalProperties: + $ref: "#/components/schemas/Pet" + User01: + description: Without any additional field it maps to closed record. + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + User02: + description: Additional properties with `true` enable + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: true + User03: + description: Additional properties with {} + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: { } + User04: + description: Additional properties with type string + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: string + User05: + description: Multiple additional fields , result can not have multiple field + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: integer + additionalProperties: + type: array + items: + type: string + User06: + description: Additional properties with type object without properties + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + User07: + description: Additional properties with object with property fields + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + properties: + country: + type: string + state: + type: string + User08: + description: Reference has additional properties. + allOf: + - $ref: "#/components/schemas/Pet02" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: integer + nullable: false + User09: + description: Reference has additional properties with nullable true. + allOf: + - $ref: "#/components/schemas/Pet02" + - type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Map/additional_properties_true.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Map/additional_properties_true.yaml new file mode 100644 index 000000000..2bed7c12e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Map/additional_properties_true.yaml @@ -0,0 +1,238 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + User: + description: Mock record + type: object + properties: + name: + type: string + age: + type: integer + User01: + description: Additional properties with `true` enable + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: true + User02: + description: Additional properties with {} + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: { } + User03: + description: Without additional properties + type: object + properties: + name: + type: string + id: + type: integer + User04: + description: Additional properties with type string + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: string + User05: + description: Additional properties with type number + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: number + format: float + x-nullable: false + User06: + description: Additional properties with reference + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + $ref: "#/components/schemas/User01" + User07: + description: Additional properties with type object without properties + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + User08: + description: Additional properties with object with property fields + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + properties: + country: + type: string + state: + type: string + User09: + description: Additional properties with object with additional fields + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + additionalProperties: { } + User10: + description: Additional properties with object with additional fields type string + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + additionalProperties: + type: string + User11: + description: Additional properties with object with additional fields type with reference + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + additionalProperties: + $ref: "#/components/schemas/User" + User12: + description: Additional properties with `false` enable + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: false + User13: + description: Free-form object + type: object + User14: + description: Additional properties with object with additional fields type with inline object + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: object + additionalProperties: + type: object + properties: + name: + type: string + place: + type: string + User15: + description: Additional properties with Array + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: array + items: + type: string + User16: + description: Additional properties with type number, nullable true + type: object + properties: + name: + type: string + id: + type: integer + additionalProperties: + type: number + format: float + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/null_empty_record.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/null_empty_record.yaml new file mode 100644 index 000000000..ede5d80f0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/null_empty_record.yaml @@ -0,0 +1,76 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + details: + type: object + x-nullable: true + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_anyof_array_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_anyof_array_schema.yaml new file mode 100644 index 000000000..b9b5ed756 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_anyof_array_schema.yaml @@ -0,0 +1,77 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + properties: + address: + anyOf: + - type: array + items: + "$ref": "#/components/schemas/Response" + - type: string + x-nullable: true + description: The customer's address. + name: + type: string + type: object + Response: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_anyof_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_anyof_schema.yaml new file mode 100644 index 000000000..b2f8936d1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_anyof_schema.yaml @@ -0,0 +1,74 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + properties: + address: + anyOf: + - "$ref": "#/components/schemas/Response" + description: The customer's address. + x-nullable: true + name: + type: string + type: object + Response: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_array_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_array_schema.yaml new file mode 100644 index 000000000..d1850c72f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_array_schema.yaml @@ -0,0 +1,97 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + nullable: true + limit: + description: The maximum number of items in the response (as set in the query or by default). + items: + format: int32 + type: integer + x-nullable: true + next: + description: URL to the next page of items. ( `null` if none) + type: string + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + items: { } + x-nullable: true + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_false.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_false.yaml new file mode 100644 index 000000000..37f1370cd --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_false.yaml @@ -0,0 +1,60 @@ +openapi: 3.0.0 +info: + title: Title + description: Title + version: 1.0.0 +servers: + - url: 'https' +paths: + /: + get: + summary: List all songs + operationId: listSong + tags: + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of song +components: + schemas: + UserPlayListDetails: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + limit: + description: The maximum number of items in the response (as set in the query or by default). + format: int32 + type: integer + next: + description: URL to the next page of items. ( `null` if none) + type: string + nullable: false + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + nullable: false + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object + nullable: false diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_array_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_array_schema.yaml new file mode 100644 index 000000000..675569a5f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_array_schema.yaml @@ -0,0 +1,59 @@ +openapi: 3.0.0 +info: + title: Title + description: Title + version: 1.0.0 +servers: + - url: 'https' +paths: + /: + get: + summary: List all songs + operationId: listSong + tags: + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of song +components: + schemas: + UserPlayListDetails: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + limit: + description: The maximum number of items in the response (as set in the query or by default). + items: + format: int32 + type: integer + next: + description: URL to the next page of items. ( `null` if none) + type: string + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + items: {} + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_null_type.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_null_type.yaml new file mode 100644 index 000000000..50dfff67c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_null_type.yaml @@ -0,0 +1,90 @@ +openapi: "3.0.1" + +info: + title: "OpenWeather Map API for Query parameter" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city." + version: "2.5.2" + x-ballerina-display: + label: Open Weather Client + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /onecall: + get: + tags: + - Weather Forecast + summary: "Provide weather forecast for any geographical coordinates" + description: "test" + operationId: getWeatherForecast + parameters: + - description: "Latitude" + in: query + name: lat + required: true + schema: + $ref: '#/components/schemas/Latitude' + x-ballerina-display: + label: Latitude + - description: "Longtitude" + in: query + name: lon + required: true + schema: + type: string + x-ballerina-display: + label: Longtitude + - description: "test" + in: query + name: exclude + required: false + schema: + type: string + default: 'current' + x-ballerina-display: + label: Exclude + - description: 'tests' + in: query + name: units + required: false + schema: + type: integer + default: 12 + x-ballerina-display: + label: Units + x-ballerina-display: + label: "Weather Forecast" + responses: + 200: + description: Successful response + content: + application/json: + schema: {} + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found + +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + - name: Weather Forecast + description: "Get data related to weather forecast" +components: + schemas: + Latitude: + description: "Latitude" + securitySchemes: + app_id: + type: apiKey + description: API key. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_primitive_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_primitive_schema.yaml new file mode 100644 index 000000000..d1f989c08 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_primitive_schema.yaml @@ -0,0 +1,57 @@ +openapi: 3.0.0 +info: + title: Title + description: Title + version: 1.0.0 +servers: + - url: 'https' +paths: + /: + get: + summary: List all songs + operationId: listSong + tags: + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of song +components: + schemas: + UserPlayListDetails: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + limit: + description: The maximum number of items in the response (as set in the query or by default). + format: int32 + type: integer + next: + description: URL to the next page of items. ( `null` if none) + type: string + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_record_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_record_schema.yaml new file mode 100644 index 000000000..d1f989c08 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_record_schema.yaml @@ -0,0 +1,57 @@ +openapi: 3.0.0 +info: + title: Title + description: Title + version: 1.0.0 +servers: + - url: 'https' +paths: + /: + get: + summary: List all songs + operationId: listSong + tags: + - list + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: An paged array of song +components: + schemas: + UserPlayListDetails: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + limit: + description: The maximum number of items in the response (as set in the query or by default). + format: int32 + type: integer + next: + description: URL to the next page of items. ( `null` if none) + type: string + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_string_type.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_string_type.yaml new file mode 100644 index 000000000..31fe03974 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_option_string_type.yaml @@ -0,0 +1,90 @@ +openapi: "3.0.1" + +info: + title: "OpenWeather Map API for Query parameter" + description: "Get current weather, daily forecast for 16 days, and 3-hourly forecast 5 days for your city." + version: "2.5.2" + x-ballerina-display: + label: Open Weather Client + +servers: + - url: "http://api.openweathermap.org/data/2.5/" + +paths: + /onecall: + get: + tags: + - Weather Forecast + summary: "Provide weather forecast for any geographical coordinates" + description: "test" + operationId: getWeatherForecast + parameters: + - description: "Latitude" + in: query + name: lat + required: true + schema: + $ref: '#/components/schemas/Latitude' + x-ballerina-display: + label: Latitude + - description: "Longtitude" + in: query + name: lon + required: true + schema: + type: string + x-ballerina-display: + label: Longtitude + - description: "test" + in: query + name: exclude + required: false + schema: + type: string + default: 'current' + x-ballerina-display: + label: Exclude + - description: 'tests' + in: query + name: units + required: false + schema: + type: integer + default: 12 + x-ballerina-display: + label: Units + x-ballerina-display: + label: "Weather Forecast" + responses: + 200: + description: Successful response + content: + application/json: + schema: {} + 404: + description: Not found response + content: + text/plain: + schema: + title: Weather not found + type: string + example: Not found + +security: + - app_id: [] + +tags: + - name: Current Weather Data + description: "Get current weather details" + - name: Weather Forecast + description: "Get data related to weather forecast" +components: + schemas: + Latitude: + type: string + securitySchemes: + app_id: + type: apiKey + description: API key. + name: appid + in: query diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_primitive_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_primitive_schema.yaml new file mode 100644 index 000000000..8b4557958 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_primitive_schema.yaml @@ -0,0 +1,94 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + limit: + description: The maximum number of items in the response (as set in the query or by default). + format: int32 + type: integer + next: + description: URL to the next page of items. ( `null` if none) + type: string + x-nullable: true + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + x-nullable: true + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_ref_array.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_ref_array.yaml new file mode 100644 index 000000000..fd72e5e7e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/nullable_ref_array.yaml @@ -0,0 +1,90 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + time: + $ref: '#/components/schemas/Time' + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Response: + allOf: + - $ref: "#/components/schemas/Request" + - type: object + properties: + isTime: + type: boolean + Time: + type: array + items: + $ref: "#/components/schemas/Request" + x-nullable: true + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/xnullable_not_present.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/xnullable_not_present.yaml new file mode 100644 index 000000000..5b8e9c7fd --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Nullable/xnullable_not_present.yaml @@ -0,0 +1,94 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + externalDocs: + description: Find more info on the official Spotify Web API Reference + url: https://developer.spotify.com/documentation/web-api/reference/#object-pagingobject + properties: + href: + description: A link to the Web API endpoint returning the full result of the request + type: string + items: + description: The requested data. + items: + $ref: "#/components/schemas/ListObject" + limit: + description: The maximum number of items in the response (as set in the query or by default). + format: int32 + type: integer + next: + description: URL to the next page of items. ( `null` if none) + type: string + x-nullable: true + offset: + description: The offset of the items returned (as set in the query or by default) + format: int32 + type: integer + previous: + description: URL to the previous page of items. ( `null` if none) //anydata + nullable: true + total: + $ref: "#/components/schemas/ListObject" + type: object + ListObject: + type: object + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/nestedOneOfWithAllOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/nestedOneOfWithAllOf.yaml new file mode 100644 index 000000000..dade44146 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/nestedOneOfWithAllOf.yaml @@ -0,0 +1,101 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + UnSubscribe: + oneOf: + - allOf: + - properties: + streetNo: + type: string + description: Street No + houseNo: + type: string + description: House number + description: Address line 1 + - properties: + streatName: + type: string + description: Street Name + country: + type: string + description: Country Name + event: + type: string + required: + - event + description: Address line 2 + - properties: + zipCode: + type: integer + description: Zip code + event: + type: string + required: + - event + description: Other details + Subscribe: + oneOf: + - $ref: "#/components/schemas/Time" + - $ref: '#/components/schemas/Activity' + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + Activity: + required: + - event + properties: + uuid: + type: string + description: Unique identifier for the activity + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/oneOfAsProperties.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/oneOfAsProperties.yaml new file mode 100644 index 000000000..150a33986 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/oneOfAsProperties.yaml @@ -0,0 +1,82 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + UnSubscribe: + oneOf: + - $ref: "#/components/schemas/Time" + - $ref: '#/components/schemas/Activity' + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + Activity: + required: + - event + properties: + uuid: + type: string + description: Unique identifier for the activity + event: + type: string + subject_type: + oneOf: + - $ref: '#/components/schemas/Activity' + - $ref: '#/components/schemas/Time' + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/oneOfWithInlineSchemas.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/oneOfWithInlineSchemas.yaml new file mode 100644 index 000000000..3f1e0838d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/oneOfWithInlineSchemas.yaml @@ -0,0 +1,119 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + CountryDetails: + required: + - event + properties: + iso_code: + type: string + name: + type: string + event: + type: string + Subscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + UnSubscribe: + oneOf: + - $ref: "#/components/schemas/Time" + - $ref: '#/components/schemas/Activity' + - properties: + streetNo: + type: string + description: Street Number + houseNo: + type: string + description: House Number + event: + type: string + required: + - event + - properties: + streatName: + type: string + description: Street Name + event: + type: string + country: + type: string + description: Country Name + required: + - event + - properties: + zipCode: + type: integer + description: Zipcode + event: + type: string + required: + - event + - $ref: '#/components/schemas/CountryDetails' + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + Activity: + required: + - event + properties: + uuid: + type: string + description: Unique identifier for the activity + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/twoOneOf.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/twoOneOf.yaml new file mode 100644 index 000000000..19d8bb0ed --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/twoOneOf.yaml @@ -0,0 +1,78 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + UnSubscribe: + oneOf: + - $ref: "#/components/schemas/Time" + - $ref: '#/components/schemas/Activity' + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + Activity: + required: + - event + properties: + uuid: + type: string + description: Unique identifier for the activity + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/twoOneOfWithObjectType.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/twoOneOfWithObjectType.yaml new file mode 100644 index 000000000..b00e431e4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/OneOf/twoOneOfWithObjectType.yaml @@ -0,0 +1,79 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + UnSubscribe: + type: object + oneOf: + - $ref: "#/components/schemas/Time" + - $ref: '#/components/schemas/Activity' + Time: + required: + - minute + - event + properties: + minute: + type: integer + format: int64 + second: + type: string + hour: + type: string + day: + type: string + event: + type: string + Activity: + required: + - event + properties: + uuid: + type: string + description: Unique identifier for the activity + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/missDataType.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/missDataType.yaml new file mode 100644 index 000000000..fd7fe5980 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/missDataType.yaml @@ -0,0 +1,79 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + description: Test description + required: + - id + - name + properties: + id: + description: "this is missing dataType" + name: + type: string + tag: + type: number + format: decimal + type: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/scenario01.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/scenario01.yaml new file mode 100644 index 000000000..3939fea47 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/scenario01.yaml @@ -0,0 +1,83 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + description: Test description + required: + - id + - name + properties: + id: + description: tests + type: integer + format: int64 + name: + description: tests + type: string + tag: + description: tests + type: number + format: decimal + type: + description: tests + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/scenario02.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/scenario02.yaml new file mode 100644 index 000000000..fceaec135 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Primitive/scenario02.yaml @@ -0,0 +1,77 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_array_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_array_schema.yaml new file mode 100644 index 000000000..4443b819f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_array_schema.yaml @@ -0,0 +1,92 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tagArray: + type: array + items: + type: string + default: [ "available", "busy" ] + type: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_primitive_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_primitive_schema.yaml new file mode 100644 index 000000000..aa41bc831 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_primitive_schema.yaml @@ -0,0 +1,103 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tagNumber: + type: integer + default: 10 + type: + type: string + isTrue: + type: boolean + default: true + decimalValue: + type: number + default: 00.05 + floatValue: + type: number + format: float + default: 11.5 + stringDecimalValue: + type: string + default: "00.05" + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_schema_with_doublequote.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_schema_with_doublequote.yaml new file mode 100644 index 000000000..26fd35b49 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_schema_with_doublequote.yaml @@ -0,0 +1,90 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + textQualifier: + type: string + default: '"' + type: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_string_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_string_schema.yaml new file mode 100644 index 000000000..1b862bceb --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_optional_string_schema.yaml @@ -0,0 +1,105 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tagName: + type: string + default: TagName + type: + type: string + default: <|endoftext|> + x-nullable: true + prompt: + default: <|endoftext|> + x-nullable: true + oneOf: + - type: string + - type: array + items: + type: string + anyOfField: + default: <|endoftext|> + anyOf: + - type: integer + - type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_required_field_schema.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_required_field_schema.yaml new file mode 100644 index 000000000..421531aed --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/default_required_field_schema.yaml @@ -0,0 +1,88 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + default: Name + type: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/empty_record.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/empty_record.yaml new file mode 100644 index 000000000..35d21796b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/empty_record.yaml @@ -0,0 +1,77 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + type: object + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/nested_schema_refs.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/nested_schema_refs.yaml new file mode 100644 index 000000000..8d6e37546 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/nested_schema_refs.yaml @@ -0,0 +1,128 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/AsanaResource" + AsanaResource: + description: A generic Asana Resource, containing a globally unique identifier. + type: object + properties: + gid: + description: Globally unique identifier of the resource, as a string. + type: string + readOnly: true + example: '12345' + x-insert-after: false + resource_type: + description: The base type of this resource. + type: string + readOnly: true + example: task + x-insert-after: gid + UserCompact: + allOf: + - $ref: '#/components/schemas/AsanaResource' + - type: object + description: A user object represents an account in Asana that can be given + access to various workspaces, projects, and tasks. + x-docs-overrides: + properties.resource_type.example: user + properties: + name: + type: string + description: Read-only except when same user as requester. + example: Greg Sanchez + ProjectStatusCompact: + allOf: + - $ref: '#/components/schemas/AsanaResource' + - type: object + description: A project status is an update on the progress of a particular + project, and is sent out to all project followers when created. + properties: + title: + description: The title of the project status update. + type: string + example: Status Update - Jun 15 + ProjectStatusRequest: + $ref: '#/components/schemas/ProjectStatusBase' + ProjectStatusBase: + allOf: + - $ref: '#/components/schemas/ProjectStatusCompact' + - type: object + required: + - text + - color + properties: + author: + $ref: '#/components/schemas/UserCompact' + modified_at: + description: The time at which this project status was last modified. + text: + description: The text content of the status update. + type: string + example: The project is moving forward according to plan... + html_text: + type: string + example: >- + The project is moving forward according to + plan... + color: + description: The color associated with the status update. + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario05.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario05.yaml new file mode 100644 index 000000000..3d6afcce0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario05.yaml @@ -0,0 +1,83 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: "#/components/schemas/Request" + Response: + description: "Response details" + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Request: + required: + - time + properties: + time: + $ref: "#/components/schemas/Response" + detail: + type: boolean + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario10.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario10.yaml new file mode 100644 index 000000000..0445a6fc2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario10.yaml @@ -0,0 +1,60 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario11.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario11.yaml new file mode 100644 index 000000000..5f384500a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Record/scenario11.yaml @@ -0,0 +1,83 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + request: + $ref: '#/components/schemas/Request' + Request: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + description: name field + type: string + tag: + type: string + type: + type: object + properties: + typeId: + description: type id + type: string + tagType: + type: string + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/multiple_references.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/multiple_references.yaml new file mode 100644 index 000000000..fe821809f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/multiple_references.yaml @@ -0,0 +1,161 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Indicator: + type: object + properties: + id: + type: string + example: SP.POP.TOTL + value: + type: string + example: Population, total + Country: + type: object + properties: + id: + type: string + example: CHL + value: + type: string + example: Chilie + AccessToElectricity: + type: object + properties: + indicator: + "$ref": "#/components/schemas/Indicator" + country: + "$ref": "#/components/schemas/Country" + date: + type: string + example: "2016" + value: + type: integer + example: 100 + decimal: + type: integer + example: 2 + YouthLiteracyRate: + type: object + properties: + indicator: + $ref: "#/components/schemas/Indicator" + country: + $ref: "#/components/schemas/Country" + date: + type: string + example: "2016" + value: + type: integer + example: 100 + decimal: + type: integer + example: 2 + GrossDomesticProduct: + type: object + properties: + indicator: + type: object + "$ref": "#/components/schemas/Indicator" + country: + "$ref": "#/components/schemas/Country" + date: + type: string + example: "2016" + value: + type: integer + example: 100 + decimal: + type: integer + example: 2 + PrimaryEducationExpenditure: + type: object + properties: + indicator: + type: object + "$ref": "#/components/schemas/Indicator" + country: + "$ref": "#/components/schemas/Country" + date: + type: string + example: "2016" + value: + type: integer + example: 100 + decimal: + type: integer + example: 2 + CountryPoplutation: + type: object + properties: + indicator: + type: object + "$ref": "#/components/schemas/Indicator" + country: + "$ref": "#/components/schemas/Country" + date: + type: string + example: "2016" + value: + type: integer + example: 100 + decimal: + type: integer + example: 2 + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/referred_inclusion.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/referred_inclusion.yaml new file mode 100644 index 000000000..403ed3774 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/referred_inclusion.yaml @@ -0,0 +1,98 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Pet" + - type: object + properties: + bark: + type: boolean + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + + SimpleType: + type: integer + + ReferredSimpleType: + $ref: "#/components/schemas/SimpleType" + + TestPet: + $ref: "#/components/schemas/Pet" + + TestDog: + $ref: "#/components/schemas/Dog" + + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/resolve_reference_docs.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/resolve_reference_docs.yaml new file mode 100644 index 000000000..8dc474f04 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/Reference/resolve_reference_docs.yaml @@ -0,0 +1,91 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/UnSubscribe' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + properties: + pet_type: + not: + type: integer + event: + type: string + required: + - pet_type + - event + UnSubscribe: + type: object + required: + - event + properties: + zipCode: + type: integer + event: + type: string + Pet: + description: Pet details + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + type: + type: string + Dog: + description: Dog details + properties: + pet_details: + $ref: "#/components/schemas/Pet" + bark: + type: boolean + Pets: + description: Pets details + type: object + properties: + pet_details: + items: + $ref: "#/components/schemas/Pet" + numer_of_pets: + type: integer + messages: + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/UnSubscribe' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id + + + + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/ballerina_project/Ballerina.toml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/ballerina_project/Ballerina.toml new file mode 100644 index 000000000..290816894 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/ballerina_project/Ballerina.toml @@ -0,0 +1,5 @@ +[package] +org= "ballerina" +name= "test" +version= "0.0.0" + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/ballerina_project/Package.md b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/ballerina_project/Package.md new file mode 100644 index 000000000..ff3dffe23 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/ballerina_project/Package.md @@ -0,0 +1,145 @@ +## Module overview + +The OpenAPI tools provide the following capabilities. + + 1. Generate the Ballerina service or client code for a given OpenAPI definition. + 2. Export the OpenAPI definition of a Ballerina service. + 3. Validate the service implementation of a given OpenAPI contract. + +The `openapi` command in Ballerina is used for OpenAPI to Ballerina and Ballerina to OpenAPI code generations. +Code generation from OpenAPI to Ballerina can produce `ballerina service stubs` and `ballerina client stubs`. +The OpenAPI compiler plugin will allow you to validate a service implementation against an OpenAPI contract during + the compile time. +This plugin ensures that the implementation of a service does not deviate from its OpenAPI contract. + +### OpenAPI to Ballerina +#### Generate Service and Client Stub from an OpenAPI Contract + +```bash +bal openapi -i + [--service-name: generated files name] + [--tags: tags list] + [--operations: operationsID list] + [--mode service|client ] + [(-o|--output): output file path] +``` +Generates both the Ballerina service and Ballerina client stub for a given OpenAPI file. + +This `-i ` parameter of the command is mandatory. It will get the path to the + OpenAPI contract file (i.e., `my-api.yaml` or `my-api.json`) as an input. + +The `--service-name` is an optional parameter, which allows you to change the generated service name. + +You can give the specific tags and operations that you need to document as services without documenting all the operations using these optional `--tags` and `--operations` commands. + +The `(-o|--output)` is an optional parameter. You can use this to give the output path of the generated files. +If not, it will take the execution path as the output path. + +##### Modes +If you want to generate a service only, you can set the mode as `service` in the OpenAPI tool. + +```bash +bal openapi -i --mode service [(-o|--output) output file path] +``` + +If you want to generate a client only, you can set the mode as `client` in the OpenAPI tool. +This client can be used in client applications to call the service defined in the OpenAPI file. + +```bash +bal openapi -i --mode client + [(-o|--output) output file path] +``` + +### Ballerina to OpenAPI +#### Service to OpenAPI Export +```bash +bal openapi -i + [(-o|--output) output openapi file path] +``` +Export the Ballerina service to an OpenAPI Specification 3.0 definition. For the export to work properly, +the input Ballerina service should be defined using the basic service and resource-level HTTP annotations. +If you need to document an OpenAPI contract for only one given service, then use this command. +```bash + bal openapi -i (-s | --service) +``` + +### Samples for OpenAPI Commands +#### Generate Service and Client Stub from OpenAPI +```bash + bal openapi -i hello.yaml +``` + +This will generate a Ballerina service and client stub for the `hello.yaml` OpenAPI contract named `hello-service +` and client named `hello-client`. The above command can be run from within anywhere on the execution path. +It is not mandatory to run it from inside the Ballerina project. + +Output: +```bash +The service generation process is complete. The following files were created. +-- hello-service.bal +-- hello-client.bal +-- schema.bal +``` +#### Generate an OpenAPI Contract from a Service + + ```bash + bal openapi -i modules/helloworld/helloService.bal + ``` +This will generate the OpenAPI contracts for the Ballerina services, which are in the `hello.bal` Ballerina file. + ```bash + bal openapi -i modules/helloworld/helloService.bal (-s | --service) helloworld + ``` +This command will generate the `helloworld-openapi.yaml` file that is related to the `helloworld` service inside the + `helloService.bal` file. + +## OpenAPI Validator Compiler Plugin + +The OpenAPI Validator Compiler plugin validates a service against a given OpenAPI contract. +The Compiler Plugin is activated if a service has the `openapi:ServiceInfo` annotation. This plugin compares +the service and the OpenAPI Contract and validates both against a pre-defined set of validation rules. +If any of the rules fail, the plugin will give the result as one or more compilation errors. + +### Annotation for Validator Plugin +The `@openapi:ServiceInfo` annotation is used to bind the service with an OpenAPI contract. You need to add +this annotation to the service file with the required values for enabling the validations. +The following is an example of the annotation usage. +```ballerina +@openapi:ServiceInfo{ + contract: “/path/to/openapi.json|yaml”, + [ tag : “store” ], + [ operations: [“op1”, “op2”] ] + [ failOnErrors]: true/false → default : true + [ excludeTags ]: [“pets”, “user”] + [ excludeOperations: [“op1”, “op2”] ] + } +service greet on new http:Listener(9090) { + ... +} +``` +#### Annotation Support for the Following Attributes: +- **Contract** (Required) : **string** : +Here, you can provide a path to the OpenAPI contract as a string and the OpenAPI file can either be `.yaml` or `.json` +This is a required attribute. + +- **Tag** (Optional) : **string[]?** : +The compiler will only validate resources against operations, which are tagged with a tag specified in the list. +If not specified, the compiler will validate resources against all the operations defined in the OpenAPI contract. + +- **Operations** (Optional): **string[]?** : +Should contain a list of operation names that need to be validated against the resources in the service. +If not specified, the compiler will validate resources against all the operations defined in the OpenAPI contract. If both tags and operations are defined, it will validate against the union set of the resources. + +- **ExcludeTags** (Optional) : **string[]?** : +This feature is for users to store the tag. It does not need to be validated. +At the same time, the `excludeTag` and `Tag` cannot store and the plugin will generate warning messages regarding + it. + +- **ExcludeOperations** (Optional) : **string[]?** : +This feature is for users to store the operations that do not need to be validated. +At the same time, the `excludeOperations` and `Operations` can not store and they will generate warning messages. +The `Tag` feature can store with `excludeOperations`. Then, all the tag operations will be validated except the `exclude` + operations. + +- **FailOnErrors** (Optional) : **boolean value** : +If you need to turn off the validation, add this to the annotation with the value as `false`. + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOfWithEmptyObject.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOfWithEmptyObject.bal new file mode 100644 index 000000000..d40e165e0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOfWithEmptyObject.bal @@ -0,0 +1,16 @@ +public type Subscribe record { + boolean timing?; + string event; +}; + +public type UnSubscribe record { + *Time; +}; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOfWithNoType.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOfWithNoType.bal new file mode 100644 index 000000000..03b4e8c9d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOfWithNoType.bal @@ -0,0 +1,18 @@ +public type Subscribe record { + boolean pure?; + boolean timing?; + string event; +}; + +public type UnSubscribe record { + *Time; + boolean timing?; +}; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOf_with_cyclic.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOf_with_cyclic.bal new file mode 100644 index 000000000..e027e3cb8 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOf_with_cyclic.bal @@ -0,0 +1,17 @@ +public type Subscribe record { + boolean timing?; + string event; +}; + +public type UnSubscribe record { + *Time; + UnSubscribe time?; +}; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOf_with_one_ref.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOf_with_one_ref.bal new file mode 100644 index 000000000..735ee498b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/allOf_with_one_ref.bal @@ -0,0 +1,17 @@ +public type Subscribe record { + boolean timing?; + string event; +}; + +public type UnSubscribe record { + *Time; + Time time?; +}; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/nested_allOf_with_allOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/nested_allOf_with_allOf.bal new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/oneAllOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/oneAllOf.bal new file mode 100644 index 000000000..b7f484b5f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/oneAllOf.bal @@ -0,0 +1,17 @@ +public type Subscribe record { + boolean timing?; + string event; +}; + +public type UnSubscribe record { + *Time; + boolean timing?; +}; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/twoAllOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/twoAllOf.bal new file mode 100644 index 000000000..6671e53c4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AllOf/twoAllOf.bal @@ -0,0 +1,22 @@ +public type Subscribe record { + boolean timing?; + string event; +}; + +public type UnSubscribe record { + *Time; + *Activity; +}; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; + +public type Activity record { + # Unique identifier for the activity + string uuid?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AnyOf/oneAnyOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AnyOf/oneAnyOf.bal new file mode 100644 index 000000000..b470f09ea --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/AnyOf/oneAnyOf.bal @@ -0,0 +1,23 @@ +public type ResponseMessage record { + string event; +}; + +public type ResponseMessageWithId record { + string event; + string id; +}; + +public type Subscribe record { + boolean timing?; + string event; +}; + +public type UnSubscribe Time; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_max_item.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_max_item.bal new file mode 100644 index 000000000..4d5b6d389 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_max_item.bal @@ -0,0 +1,14 @@ +public type Subscribe record { + @constraint:Array {maxLength: 7} + int[] tag; + string event; + Activity activity?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +@constraint:Array {maxLength: 7} +public type Activity int[]; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_no_item_type.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_no_item_type.bal new file mode 100644 index 000000000..c29dc4432 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_no_item_type.bal @@ -0,0 +1,12 @@ +public type Subscribe record { + Activity activity?; + string event; + anydata[] tag; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Activity anydata[]; \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_allOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_allOf.bal new file mode 100644 index 000000000..37ac7e61c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_allOf.bal @@ -0,0 +1,27 @@ +public type Subscribe record { + record {*ActivityResponseObject; *EmployeeDetails;}[] data?; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type ActivityResponseObject record { + # Due date of the Activity. Format: YYYY-MM-DD + string due_date?; + # Due time of the Activity in UTC. Format: HH:MM + string due_time?; + # Duration of the Activity. Format: HH:MM + string duration?; + # The ID of the Deal this Activity is associated with + int deal_id?; +}; + +public type EmployeeDetails record { + # Employee ID + string employee_id?; + # Employee Name + string employee_name?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_inline_allOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_inline_allOf.bal new file mode 100644 index 000000000..9d459506a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_inline_allOf.bal @@ -0,0 +1,22 @@ +# List of addresses +public type Owner record { + record { + # Street No + string streetNo?; + # House number + string houseNo?; + # Street Name + string streatName?; + # Country Name + string country?; + # Zip code + int zipCode?; + *NameData; + }[] AdressList?; + string[] Pets?; +}; + +public type NameData record { + string FirstName?; + string LastName?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_oneOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_oneOf.bal new file mode 100644 index 000000000..cce1f91a8 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_oneOf.bal @@ -0,0 +1,27 @@ +public type Subscribe record { + (ActivityResponseObject|EmployeeDetails)[] data?; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type ActivityResponseObject record { + # Due date of the Activity. Format: YYYY-MM-DD + string due_date?; + # Due time of the Activity in UTC. Format: HH:MM + string due_time?; + # Duration of the Activity. Format: HH:MM + string duration?; + # The ID of the Deal this Activity is associated with + int deal_id?; +}; + +public type EmployeeDetails record { + # Employee ID + string employee_id?; + # Employee Name + string employee_name?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_oneOf_complex.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_oneOf_complex.bal new file mode 100644 index 000000000..c117f7fac --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/array_with_oneOf_complex.bal @@ -0,0 +1,30 @@ +public type Subscribe record { + (EmployeeDetails[]|ActivityResponseObject)[] data?; + string event; + Request request?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type ActivityResponseObject record { + # Due date of the Activity. Format: YYYY-MM-DD + string due_date?; + # Due time of the Activity in UTC. Format: HH:MM + string due_time?; + # Duration of the Activity. Format: HH:MM + string duration?; + # The ID of the Deal this Activity is associated with + int deal_id?; +}; + +public type EmployeeDetails record { + # Employee ID + string employee_id?; + # Employee Name + string employee_name?; +}; + +public type Request (EmployeeDetails[]|ActivityResponseObject)[]; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/nestedArray.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/nestedArray.bal new file mode 100644 index 000000000..46e581795 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/nestedArray.bal @@ -0,0 +1,10 @@ +public type Subscribe record { + int zipCode?; + string event; + string[][][] tag; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/oneArray.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/oneArray.bal new file mode 100644 index 000000000..539217ddd --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/oneArray.bal @@ -0,0 +1,5 @@ +public type Subscribe record { + int zipCode?; + string event; + string[] tag; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/refArray.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/refArray.bal new file mode 100644 index 000000000..eee282f8a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/refArray.bal @@ -0,0 +1,18 @@ +public type Subscribe record { + int zipCode?; + string event; + # Code array + Activity[] code?; + boolean codePen?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Activity record { + int id; + string name; + string tag?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schemaArray.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schemaArray.bal new file mode 100644 index 000000000..7927edbe0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schemaArray.bal @@ -0,0 +1,16 @@ +public type Subscribe record { + int zipCode?; + string event; + # Code array + Activity[] code?; + boolean codePen?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Activity Request[]; + +public type Request int; \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schema_with_array.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schema_with_array.bal new file mode 100644 index 000000000..03e9e8e78 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schema_with_array.bal @@ -0,0 +1,9 @@ +public type Address record { + int streetNo?; + string mainStreet?; + string country?; +}; + +public type UserAddress Address[]; + +public type Pet string[]; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schema_with_nested_array.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schema_with_nested_array.bal new file mode 100644 index 000000000..241dadd3e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Array/schema_with_nested_array.bal @@ -0,0 +1,9 @@ +public type Address record { + int streetNo?; + string mainStreet?; + string country?; +}; + +public type UserAddress Address[][][]; + +public type Pet string[][]; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/additional_properties_with_constraint.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/additional_properties_with_constraint.bal new file mode 100644 index 000000000..2636b3e1c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/additional_properties_with_constraint.bal @@ -0,0 +1,27 @@ +public type Subscribe record { + Additional_Array additionalArray?; + string event; + Additional_NestedArray additionalNestedArray?; + Additional_Primitive additionalPrimitive?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Additional_Primitive record {| + string name?; + decimal age?; + string...; +|}; + +public type Additional_Array record {| + boolean isArray?; + string[]...; +|}; + +public type Additional_NestedArray record {| + boolean isArray?; + string[][]...; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/array.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/array.bal new file mode 100644 index 000000000..9df57f2fc --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/array.bal @@ -0,0 +1,37 @@ +import ballerina/constraint; + +@constraint:String {maxLength: 23} +public type HobbyItemsString string; + +@constraint:String {minLength: 7} +public type PersonDetailsItemsString string; + +@constraint:Float {maxValue: 445.4} +public type PersonFeeItemsNumber float; + +@constraint:Array {maxLength: 5, minLength: 2} +public type Hobby HobbyItemsString[]; + +public type Subscribe record { + Person person?; + string event; + Address tag; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Person record { + Hobby hobby?; + @constraint:Array {maxLength: 5} + PersonDetailsItemsString[] Details?; + int id; + PersonFeeItemsNumber[] fee?; + # The maximum number of items in the response (as set in the query or by default). + anydata 'limit?; +}; + +@constraint:String {minLength: 5} +public type Address string; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/nested_array.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/nested_array.bal new file mode 100644 index 000000000..cfb373967 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/nested_array.bal @@ -0,0 +1,51 @@ +import ballerina/constraint; + +@constraint:Array {maxLength: 2, minLength: 1} +public type NestedarrayExamplesItemsArray NestedarrayexamplesitemsarrayItemsString[]; + +@constraint:String {minLength: 1} +public type NestedarrayexamplesitemsarrayItemsString string; + +public type Nestedarray02ExamplesItemsArray Nestedarray02examplesitemsarrayItemsString[]; + +@constraint:String {minLength: 1} +public type Nestedarray02examplesitemsarrayItemsString string; + +@constraint:Array {maxLength: 2, minLength: 1} +public type NoconstraintExamplesItemsArray int[]; + +public type Subscribe record { + # Every array items has constraint validation + NestedArray nestedArray?; + string event; + # Some array items have constraint + NestedArray02 nestedArray02?; + # Last array item hasn't constraint values + NoConstraint noConstraint?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +# Every array items has constraint validation +public type NestedArray record { + string name?; + @constraint:Array {maxLength: 200, minLength: 2} + NestedarrayExamplesItemsArray[] examples?; +}; + +# Some array items have constraint +public type NestedArray02 record { + string name?; + @constraint:Array {maxLength: 200, minLength: 2} + Nestedarray02ExamplesItemsArray[] examples?; +}; + +# Last array item hasn't constraint values +public type NoConstraint record { + string name?; + @constraint:Array {maxLength: 200, minLength: 2} + NoconstraintExamplesItemsArray[] examples?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/record_field.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/record_field.bal new file mode 100644 index 000000000..b4f143291 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/record_field.bal @@ -0,0 +1,29 @@ +import ballerina/constraint; + +public type Subscribe record { + Person person?; + string event; + Address tag; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Person record { + @constraint:String {maxLength: 14} + string name?; + @constraint:Array {maxLength: 5, minLength: 2} + string[] hobby?; + @constraint:Int {maxValue: 5} + int id; + Address address?; + @constraint:Float {maxValue: 100000} + float salary?; + @constraint:Number {minValue: 500000} + decimal net?; +}; + +@constraint:String {minLength: 5} +public type Address string; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/record_field_02.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/record_field_02.bal new file mode 100644 index 000000000..436d2da04 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/record_field_02.bal @@ -0,0 +1,45 @@ +import ballerina/constraint; + +@constraint:String {maxLength: 5000} +public type TaxratesItemsString string; + +@constraint:String {maxLength: 5000} +public type TaxratesanyofItemsString string; + +public type Subscribe record { + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Address string; + +public type Person record { + @constraint:String {maxLength: 14} + string name?; + @constraint:Array {maxLength: 5} + string[] hobby?; + @constraint:Int {maxValue: 5} + int id; + Address address?; + @constraint:Float {maxValue: 0} + float salary?; + @constraint:Number {minValue: 0} + decimal net?; + @constraint:Int {minValue: 1, maxValue: 100} + int maxDeliveryCount?; + # scenario 01 - field with nullable. + @constraint:String {maxLength: 5000} + string service_class?; + # scenario 02 - field with oneOf type. + TaxratesItemsString[]|int tax_rates?; + # scenario 03 - field with anyOf. + TaxratesanyofItemsString[]|int tax_rates_anyOf?; + # scenario 03 - field with a oneOf type array that items has oneOf. + (string|int)[]|string tax_rates_oneOF_array?; + # scenario 04 - field with a anyOf type array items has anyOf. + (int|string)[]|int tax_rates_anyOf_array?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/type_def_node.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/type_def_node.bal new file mode 100644 index 000000000..8ec333624 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Constraint/type_def_node.bal @@ -0,0 +1,36 @@ +import ballerina/constraint; + +public type Subscribe record { + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Person person?; +}; + +public type Person record { + @constraint:String {maxLength: 14} + string name?; + @constraint:Array {maxLength: 5, minLength: 2} + string[] hobby?; + @constraint:Int {maxValue: 5} + int id; + Address address?; + @constraint:Float {maxValue: 100000} + float salary?; + @constraint:Number {minValue: 500000} + decimal net?; + Book fav?; +}; + +public type Book record { + @constraint:String {maxLength: 67} + string name?; + @constraint:Number {maxValue: 89.0} + decimal price?; +}; + +@constraint:String {minLength: 5} +public type Address string; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Map/additional_properties_composed_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Map/additional_properties_composed_schema.bal new file mode 100644 index 000000000..edeebc58d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Map/additional_properties_composed_schema.bal @@ -0,0 +1,91 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +# Mock record +public type Pet record { + string name?; + int age?; +}; + +# Mock record 02 +public type Pet02 record {| + string name?; + int age?; + Pet...; +|}; + +# Without any additional field it maps to closed record. +public type User01 record { + *Pet; + string name?; + int id?; +}; + +# Additional properties with `true` enable +public type User02 record { + *Pet; + string name?; + int id?; +}; + +# Additional properties with {} +public type User03 record { + *Pet; + string name?; + int id?; +}; + +# Additional properties with type string +public type User04 record {| + *Pet; + string name?; + int id?; + string...; +|}; + +# Multiple additional fields , result can not have multiple field +public type User05 record {| + *Pet; + string name?; + int id?; + int|string[]...; +|}; + +# Additional properties with type object without properties +public type User06 record {| + *Pet; + string name?; + int id?; + record {}...; +|}; + +# Additional properties with object with property fields +public type User07 record {| + *Pet; + string name?; + int id?; + record {string country?; string state?;}...; +|}; + +# Reference has additional properties. +public type User08 record {| + *Pet02; + string name?; + int id?; + Pet|int...; +|}; + +# Reference has additional properties with nullable true. +public type User09 record {| + *Pet02; + string name?; + int id?; + Pet|int...; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Map/additional_properties_true.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Map/additional_properties_true.bal new file mode 100644 index 000000000..6710dd810 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Map/additional_properties_true.bal @@ -0,0 +1,120 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +# Mock record +public type User record { + string name?; + int age?; +}; + +# Additional properties with `true` enable +public type User01 record { + string name?; + int id?; +}; + +# Additional properties with {} +public type User02 record { + string name?; + int id?; +}; + +# Without additional properties +public type User03 record { + string name?; + int id?; +}; + +# Additional properties with type string +public type User04 record {| + string name?; + int id?; + string...; +|}; + +# Additional properties with type number +public type User05 record {| + string name?; + int id?; + float...; +|}; + +# Additional properties with reference +public type User06 record {| + string name?; + int id?; + User01...; +|}; + +# Additional properties with type object without properties +public type User07 record {| + string name?; + int id?; + record {}...; +|}; + +# Additional properties with object with property fields +public type User08 record {| + string name?; + int id?; + record {string country?; string state?;}...; +|}; + +# Additional properties with object with additional fields +public type User09 record {| + string name?; + int id?; + record {}...; +|}; + +# Additional properties with object with additional fields type string +public type User10 record {| + string name?; + int id?; + record {|string...;|}...; +|}; + +# Additional properties with object with additional fields type with reference +public type User11 record {| + string name?; + int id?; + record {|User...;|}...; +|}; + +# Additional properties with `false` enable +public type User12 record {| + string name?; + int id?; +|}; + +# Free-form object +public type User13 record { +}; + +# Additional properties with object with additional fields type with inline object +public type User14 record {| + string name?; + int id?; + record {|record {string name?; string place?;}...;|}...; +|}; + +# Additional properties with Array +public type User15 record {| + string name?; + int id?; + string[]...; +|}; + +# Additional properties with type number, nullable true +public type User16 record {| + string name?; + int id?; + float...; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/null_empty_record.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/null_empty_record.bal new file mode 100644 index 000000000..f0a3cb375 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/null_empty_record.bal @@ -0,0 +1,18 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + int id?; + string name?; + string tag?; + string 'type?; + record {}? details?; +}; \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_anyof_array_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_anyof_array_schema.bal new file mode 100644 index 000000000..c6fa4e6af --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_anyof_array_schema.bal @@ -0,0 +1,19 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + # The customer's address. + Response[]|string address?; + string name?; +}; + +public type Response string; + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_anyof_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_anyof_schema.bal new file mode 100644 index 000000000..3ea1ce0af --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_anyof_schema.bal @@ -0,0 +1,18 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + # The customer's address. + Response? address?; + string name?; +}; + +public type Response string; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_array.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_array.bal new file mode 100644 index 000000000..ce036e14e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_array.bal @@ -0,0 +1,29 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + # A link to the Web API endpoint returning the full result of the request + string href?; + # The requested data. + anydata items?; + # The maximum number of items in the response (as set in the query or by default). + anydata? 'limit?; + # URL to the next page of items. ( `null` if none) + string next?; + # The offset of the items returned (as set in the query or by default) + int offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata? previous?; + ListObject total?; +}; + +public type ListObject record { +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_false.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_false.bal new file mode 100644 index 000000000..cb0588e4a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_false.bal @@ -0,0 +1,18 @@ +public type ListObject record { +}; + +public type UserPlayListDetails record { + # A link to the Web API endpoint returning the full result of the request + string? href?; + # The requested data. + ListObject[]? items?; + # The maximum number of items in the response (as set in the query or by default). + int? 'limit?; + # URL to the next page of items. ( `null` if none) + string next?; + # The offset of the items returned (as set in the query or by default) + int? offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata previous?; + ListObject total?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_null_type.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_null_type.bal new file mode 100644 index 000000000..8769237ea --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_null_type.bal @@ -0,0 +1,2 @@ +# Latitude +public type Latitude anydata?; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_primitive_fields.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_primitive_fields.bal new file mode 100644 index 000000000..8805cfb5c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_primitive_fields.bal @@ -0,0 +1,18 @@ +public type ListObject record { +}; + +public type UserPlayListDetails record { + # A link to the Web API endpoint returning the full result of the request + string? href?; + # The requested data. + ListObject[]? items?; + # The maximum number of items in the response (as set in the query or by default). + int? 'limit?; + # URL to the next page of items. ( `null` if none) + string? next?; + # The offset of the items returned (as set in the query or by default) + int? offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata? previous?; + ListObject? total?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_record_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_record_schema.bal new file mode 100644 index 000000000..8805cfb5c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_option_record_schema.bal @@ -0,0 +1,18 @@ +public type ListObject record { +}; + +public type UserPlayListDetails record { + # A link to the Web API endpoint returning the full result of the request + string? href?; + # The requested data. + ListObject[]? items?; + # The maximum number of items in the response (as set in the query or by default). + int? 'limit?; + # URL to the next page of items. ( `null` if none) + string? next?; + # The offset of the items returned (as set in the query or by default) + int? offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata? previous?; + ListObject? total?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_primitive.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_primitive.bal new file mode 100644 index 000000000..b4d4f9d92 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_primitive.bal @@ -0,0 +1,29 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + # A link to the Web API endpoint returning the full result of the request + string href?; + # The requested data. + anydata items?; + # The maximum number of items in the response (as set in the query or by default). + int 'limit?; + # URL to the next page of items. ( `null` if none) + string? next?; + # The offset of the items returned (as set in the query or by default) + int offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata? previous?; + ListObject total?; +}; + +public type ListObject record { +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_record.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_record.bal new file mode 100644 index 000000000..db32c4c8b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_record.bal @@ -0,0 +1,18 @@ +public type ListObject record { +}; + +public type UserPlayListDetails record { + # A link to the Web API endpoint returning the full result of the request + string href?; + # The requested data. + ListObject[] items?; + # The maximum number of items in the response (as set in the query or by default). + int 'limit?; + # URL to the next page of items. ( `null` if none) + string next?; + # The offset of the items returned (as set in the query or by default) + int offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata? previous?; + ListObject? total?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_ref_array.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_ref_array.bal new file mode 100644 index 000000000..61aa49bcf --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullable_ref_array.bal @@ -0,0 +1,25 @@ +public type Subscribe record { + int pet_type; + string event; + Time time?; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + int id; + string name; + string tag?; + string 'type?; +}; + +public type Response record { + *Request; + boolean isTime?; +}; + +public type Time Request[]?; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullale_option_array_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullale_option_array_schema.bal new file mode 100644 index 000000000..08af971ab --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Nullable/nullale_option_array_schema.bal @@ -0,0 +1,18 @@ +public type ListObject record { +}; + +public type UserPlayListDetails record { + # A link to the Web API endpoint returning the full result of the request + string? href?; + # The requested data. + ListObject[]? items?; + # The maximum number of items in the response (as set in the query or by default). + int[]? 'limit?; + # URL to the next page of items. ( `null` if none) + string? next?; + # The offset of the items returned (as set in the query or by default) + int? offset?; + # URL to the previous page of items. ( `null` if none) //anydata + anydata[]? previous?; + ListObject? total?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/nestedOneOfWithAllOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/nestedOneOfWithAllOf.bal new file mode 100644 index 000000000..9d263893b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/nestedOneOfWithAllOf.bal @@ -0,0 +1,31 @@ +public type UnSubscribe record { + # Street No + string streetNo?; + # House number + string houseNo?; + # Street Name + string streatName?; + # Country Name + string country?; + string event; +}|record { + # Zip code + int zipCode?; + string event; +}; + +public type Subscribe Time|Activity; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; + +public type Activity record { + # Unique identifier for the activity + string uuid?; + string event; +}; \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/oneOfAsProperties.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/oneOfAsProperties.bal new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/oneOfWithInlineSchemas.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/oneOfWithInlineSchemas.bal new file mode 100644 index 000000000..81c687c3c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/oneOfWithInlineSchemas.bal @@ -0,0 +1,42 @@ +public type CountryDetails record { + string iso_code?; + string name?; + string event; +}; + +public type Subscribe record { + int zipCode?; + string event; +}; + +public type UnSubscribe Time|Activity|record { + # Street Number + string streetNo?; + # House Number + string houseNo?; + string event; +}|record { + # Street Name + string streatName?; + string event; + # Country Name + string country?; +}|record { + # Zipcode + int zipCode?; + string event; +}|CountryDetails; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; + +public type Activity record { + # Unique identifier for the activity + string uuid?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/twoOneOf.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/twoOneOf.bal new file mode 100644 index 000000000..88eaa094c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/twoOneOf.bal @@ -0,0 +1,20 @@ +public type Subscribe record { + int zipCode?; + string event; +}; + +public type UnSubscribe Time|Activity; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; + +public type Activity record { + # Unique identifier for the activity + string uuid?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/twoOneOfWithObjectType.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/twoOneOfWithObjectType.bal new file mode 100644 index 000000000..ce989b1c3 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/OneOf/twoOneOfWithObjectType.bal @@ -0,0 +1,20 @@ +public type Subscribe record { + int zipCode?; + string event; +}; + +public type UnSubscribe Time|Activity; + +public type Time record { + int minute; + string second?; + string hour?; + string day?; + string event; +}; + +public type Activity record { + # Unique identifier for the activity + string uuid?; + string event; +}; \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/missDataType.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/missDataType.bal new file mode 100644 index 000000000..c9ec18f59 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/missDataType.bal @@ -0,0 +1,20 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + # Test description + Request request?; +}; + +# Test description +public type Request record { + # this is missing dataType + anydata id; + string name; + decimal tag?; + string 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/schema01.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/schema01.bal new file mode 100644 index 000000000..00e1e7efe --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/schema01.bal @@ -0,0 +1,23 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + # Test description + Request request?; +}; + +# Test description +public type Request record { + # tests + int id; + # tests + string name; + # tests + decimal tag?; + # tests + string 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/schema02.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/schema02.bal new file mode 100644 index 000000000..78d026f69 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Primitive/schema02.bal @@ -0,0 +1,17 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + int id; + string name; + string tag?; + string 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_array_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_array_schema.bal new file mode 100644 index 000000000..7a00e6d3a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_array_schema.bal @@ -0,0 +1,25 @@ + +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { + int id; + string name; + string[] tagArray = ["available","busy"]; + string 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_primitive_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_primitive_schema.bal new file mode 100644 index 000000000..77e1f9af6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_primitive_schema.bal @@ -0,0 +1,28 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { + int id; + string name; + int tagNumber = 10; + string 'type?; + boolean isTrue = true; + decimal decimalValue = 0.05; + float floatValue = 11.5; + string stringDecimalValue = "00.05"; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_schema_with_doublequote.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_schema_with_doublequote.bal new file mode 100644 index 000000000..480d9873f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_schema_with_doublequote.bal @@ -0,0 +1,24 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { + int id; + string name; + string textQualifier = "\""; + string 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_string_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_string_schema.bal new file mode 100644 index 000000000..323ab3f79 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_optional_string_schema.bal @@ -0,0 +1,26 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { + int id; + string name; + string tagName = "TagName"; + string? 'type = "<|endoftext|>"; + string|string[]? prompt = "<|endoftext|>"; + int|string anyOfField = "<|endoftext|>"; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_required_field_schema.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_required_field_schema.bal new file mode 100644 index 000000000..cffe59011 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/default_required_field_schema.bal @@ -0,0 +1,23 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { + int id; + string name = "Name"; + string 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/empty_record.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/empty_record.bal new file mode 100644 index 000000000..33d87080b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/empty_record.bal @@ -0,0 +1,20 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/nested_schema_refs.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/nested_schema_refs.bal new file mode 100644 index 000000000..a98d53195 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/nested_schema_refs.bal @@ -0,0 +1,45 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + # A generic Asana Resource, containing a globally unique identifier. + AsanaResource request?; +}; + +# A generic Asana Resource, containing a globally unique identifier. +public type AsanaResource record { + # Globally unique identifier of the resource, as a string. + string gid?; + # The base type of this resource. + string resource_type?; +}; + +public type UserCompact record { + *AsanaResource; + # Read-only except when same user as requester. + string name?; +}; + +public type ProjectStatusCompact record { + *AsanaResource; + # The title of the project status update. + string title?; +}; + +public type ProjectStatusRequest ProjectStatusBase; + +public type ProjectStatusBase record { + *ProjectStatusCompact; + UserCompact author?; + # The time at which this project status was last modified. + anydata modified_at?; + # The text content of the status update. + string text; + string html_text?; + # The color associated with the status update. + string color; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema05.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema05.bal new file mode 100644 index 000000000..4c3380bee --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema05.bal @@ -0,0 +1,23 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +# Response details +public type Response record { + int id; + string name; + string tag?; +}; + +public type Request record { + # Response details + Response time; + boolean detail?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema10.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema10.bal new file mode 100644 index 000000000..ec4e60471 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema10.bal @@ -0,0 +1,9 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema11.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema11.bal new file mode 100644 index 000000000..e08ea4d4f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Record/schema11.bal @@ -0,0 +1,22 @@ +public type Subscribe record { + int pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; + Request request?; +}; + +public type Request record { + int id; + # name field + string name; + string tag?; + record { + # type id + string typeId?; + string tagType?; + } 'type?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/multiple_references.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/multiple_references.bal new file mode 100644 index 000000000..0efeb153d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/multiple_references.bal @@ -0,0 +1,59 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Indicator record { + string id?; + string value?; +}; + +public type Country record { + string id?; + string value?; +}; + +public type AccessToElectricity record { + Indicator indicator?; + Country country?; + string date?; + int value?; + int 'decimal?; +}; + +public type YouthLiteracyRate record { + Indicator indicator?; + Country country?; + string date?; + int value?; + int 'decimal?; +}; + +public type GrossDomesticProduct record { + Indicator indicator?; + Country country?; + string date?; + int value?; + int 'decimal?; +}; + +public type PrimaryEducationExpenditure record { + Indicator indicator?; + Country country?; + string date?; + int value?; + int 'decimal?; +}; + +public type CountryPoplutation record { + Indicator indicator?; + Country country?; + string date?; + int value?; + int 'decimal?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/referred_inclusion.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/referred_inclusion.bal new file mode 100644 index 000000000..102b4764a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/referred_inclusion.bal @@ -0,0 +1,31 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; + +public type Dog record { + *Pet; + boolean bark?; +}; + +public type Pets Pet[]; + +public type SimpleType int; + +public type ReferredSimpleType SimpleType; + +public type TestPet Pet; + +public type TestDog Dog; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/resolve_reference_docs.bal b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/resolve_reference_docs.bal new file mode 100644 index 000000000..2fd8eaebf --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/schema/baloutputs/Reference/resolve_reference_docs.bal @@ -0,0 +1,30 @@ +public type Subscribe record { + anydata pet_type; + string event; +}; + +public type UnSubscribe record { + int zipCode?; + string event; +}; + +# Pet details +public type Pet record { + int id; + string name; + string tag?; + string 'type?; +}; + +# Dog details +public type Dog record { + # Pet details + Pet pet_details?; + boolean bark?; +}; + +# Pets details +public type Pets record { + anydata pet_details?; + int numer_of_pets?; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/ballerina_project/Ballerina.toml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/ballerina_project/Ballerina.toml new file mode 100644 index 000000000..02b9bcfb7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/ballerina_project/Ballerina.toml @@ -0,0 +1,5 @@ +[package] +org= "ballerina" +name= "testopenapi" +version= "0.0.0" + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/ballerina_project/Package.md b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/ballerina_project/Package.md new file mode 100644 index 000000000..ff3dffe23 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/ballerina_project/Package.md @@ -0,0 +1,145 @@ +## Module overview + +The OpenAPI tools provide the following capabilities. + + 1. Generate the Ballerina service or client code for a given OpenAPI definition. + 2. Export the OpenAPI definition of a Ballerina service. + 3. Validate the service implementation of a given OpenAPI contract. + +The `openapi` command in Ballerina is used for OpenAPI to Ballerina and Ballerina to OpenAPI code generations. +Code generation from OpenAPI to Ballerina can produce `ballerina service stubs` and `ballerina client stubs`. +The OpenAPI compiler plugin will allow you to validate a service implementation against an OpenAPI contract during + the compile time. +This plugin ensures that the implementation of a service does not deviate from its OpenAPI contract. + +### OpenAPI to Ballerina +#### Generate Service and Client Stub from an OpenAPI Contract + +```bash +bal openapi -i + [--service-name: generated files name] + [--tags: tags list] + [--operations: operationsID list] + [--mode service|client ] + [(-o|--output): output file path] +``` +Generates both the Ballerina service and Ballerina client stub for a given OpenAPI file. + +This `-i ` parameter of the command is mandatory. It will get the path to the + OpenAPI contract file (i.e., `my-api.yaml` or `my-api.json`) as an input. + +The `--service-name` is an optional parameter, which allows you to change the generated service name. + +You can give the specific tags and operations that you need to document as services without documenting all the operations using these optional `--tags` and `--operations` commands. + +The `(-o|--output)` is an optional parameter. You can use this to give the output path of the generated files. +If not, it will take the execution path as the output path. + +##### Modes +If you want to generate a service only, you can set the mode as `service` in the OpenAPI tool. + +```bash +bal openapi -i --mode service [(-o|--output) output file path] +``` + +If you want to generate a client only, you can set the mode as `client` in the OpenAPI tool. +This client can be used in client applications to call the service defined in the OpenAPI file. + +```bash +bal openapi -i --mode client + [(-o|--output) output file path] +``` + +### Ballerina to OpenAPI +#### Service to OpenAPI Export +```bash +bal openapi -i + [(-o|--output) output openapi file path] +``` +Export the Ballerina service to an OpenAPI Specification 3.0 definition. For the export to work properly, +the input Ballerina service should be defined using the basic service and resource-level HTTP annotations. +If you need to document an OpenAPI contract for only one given service, then use this command. +```bash + bal openapi -i (-s | --service) +``` + +### Samples for OpenAPI Commands +#### Generate Service and Client Stub from OpenAPI +```bash + bal openapi -i hello.yaml +``` + +This will generate a Ballerina service and client stub for the `hello.yaml` OpenAPI contract named `hello-service +` and client named `hello-client`. The above command can be run from within anywhere on the execution path. +It is not mandatory to run it from inside the Ballerina project. + +Output: +```bash +The service generation process is complete. The following files were created. +-- hello-service.bal +-- hello-client.bal +-- schema.bal +``` +#### Generate an OpenAPI Contract from a Service + + ```bash + bal openapi -i modules/helloworld/helloService.bal + ``` +This will generate the OpenAPI contracts for the Ballerina services, which are in the `hello.bal` Ballerina file. + ```bash + bal openapi -i modules/helloworld/helloService.bal (-s | --service) helloworld + ``` +This command will generate the `helloworld-openapi.yaml` file that is related to the `helloworld` service inside the + `helloService.bal` file. + +## OpenAPI Validator Compiler Plugin + +The OpenAPI Validator Compiler plugin validates a service against a given OpenAPI contract. +The Compiler Plugin is activated if a service has the `openapi:ServiceInfo` annotation. This plugin compares +the service and the OpenAPI Contract and validates both against a pre-defined set of validation rules. +If any of the rules fail, the plugin will give the result as one or more compilation errors. + +### Annotation for Validator Plugin +The `@openapi:ServiceInfo` annotation is used to bind the service with an OpenAPI contract. You need to add +this annotation to the service file with the required values for enabling the validations. +The following is an example of the annotation usage. +```ballerina +@openapi:ServiceInfo{ + contract: “/path/to/openapi.json|yaml”, + [ tag : “store” ], + [ operations: [“op1”, “op2”] ] + [ failOnErrors]: true/false → default : true + [ excludeTags ]: [“pets”, “user”] + [ excludeOperations: [“op1”, “op2”] ] + } +service greet on new http:Listener(9090) { + ... +} +``` +#### Annotation Support for the Following Attributes: +- **Contract** (Required) : **string** : +Here, you can provide a path to the OpenAPI contract as a string and the OpenAPI file can either be `.yaml` or `.json` +This is a required attribute. + +- **Tag** (Optional) : **string[]?** : +The compiler will only validate resources against operations, which are tagged with a tag specified in the list. +If not specified, the compiler will validate resources against all the operations defined in the OpenAPI contract. + +- **Operations** (Optional): **string[]?** : +Should contain a list of operation names that need to be validated against the resources in the service. +If not specified, the compiler will validate resources against all the operations defined in the OpenAPI contract. If both tags and operations are defined, it will validate against the union set of the resources. + +- **ExcludeTags** (Optional) : **string[]?** : +This feature is for users to store the tag. It does not need to be validated. +At the same time, the `excludeTag` and `Tag` cannot store and the plugin will generate warning messages regarding + it. + +- **ExcludeOperations** (Optional) : **string[]?** : +This feature is for users to store the operations that do not need to be validated. +At the same time, the `excludeOperations` and `Operations` can not store and they will generate warning messages. +The `Tag` feature can store with `excludeOperations`. Then, all the tag operations will be validated except the `exclude` + operations. + +- **FailOnErrors** (Optional) : **boolean value** : +If you need to turn off the validation, add this to the annotation with the value as `false`. + diff --git a/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/sample_yamls/no_auth.yaml b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/sample_yamls/no_auth.yaml new file mode 100644 index 000000000..d50e3524e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/asyncapi-to-ballerina/test_cases/sample_yamls/no_auth.yaml @@ -0,0 +1,189 @@ +asyncapi: 2.5.0 +info: + title: Chat + version: 0.0.0 +servers: + development: + url: "{server}:{port}/chat" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + Error: + type: object + required: + - type + properties: + type: + type: string + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + ErrorMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + ErrorMessage: + payload: + $ref: '#/components/schemas/ErrorMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + description: subscribe payload description + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/ErrorMessage' + description: subscribe response description + x-response-type: server-streaming + description: subscribemessage description + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc +x-dispatcherKey: type +x-dispatcherStreamId: id \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/additional/dispatcherStreamId_present.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/additional/dispatcherStreamId_present.bal new file mode 100644 index 000000000..a8cbdc633 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/additional/dispatcherStreamId_present.bal @@ -0,0 +1,41 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event",dispatcherStreamId: "id"} +service /chat on new websocket:Listener(9090) { + resource function get .() returns websocket:Service { + return new ChatService(); + } +} + +service class ChatService { + *websocket:Service; + remote function onPing(Ping message) returns Pong { + return {"event":"pong","id":"5"}; + } +} + +public type Ping record{ + string event; + string id; +}; + +public type Pong record { + string event; + string id; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/additional/override_description_of_record.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/additional/override_description_of_record.bal new file mode 100644 index 000000000..9330c911a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/additional/override_description_of_record.bal @@ -0,0 +1,49 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +# Subscribe record description +# + id - Override id description +# + event - Override event description +public type Subscribe record{ + #Subscribe id description + int id; + #Subscribe event description + string event; +}; + +public type Ticker record{ + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker{ + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/graphql_over_websocket.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/graphql_over_websocket.bal new file mode 100644 index 000000000..89397e2e7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/graphql_over_websocket.bal @@ -0,0 +1,118 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/io; + +@websocket:ServiceConfig {dispatcherKey: "type", subProtocols: ["graphql-transport-ws"]} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribeMessage(SubscribeMessage message) returns stream { + NextMessage returnMessage = {id: message.id, payload: (), 'type: "next"}; + NextMessage[] array = genStream(10, returnMessage, message.id); + return array.toStream(); + } + + remote function onPingMessage(PingMessage message) returns PongMessage { + return {'type: "error"}; + } + + remote function onPongMessage(PongMessage message) { + io:println(message); + } + + remote function onConnectionInitMessage(ConnectionInitMessage message) returns ConnectionAckMessage { + return {'type: "connectionack"}; + } + + remote function onCompleteMessage(CompleteMessage message) { + io:println(message); + } + + remote function onError(websocket:Caller caller, error err) returns error? { + check caller->writeMessage({"type": "error"}); + } + + remote function onIdleTimeout() { + io:println("timeout"); + } +} + +isolated function genStream(int times, NextMessage payload, string id) returns NextMessage[] { + NextMessage[] array = []; + int time = 0; + while (time < times) { + array.push(payload); + time += 1; + } + array.push({id, 'type: "complete", payload: ()}); + return array; +} + +type ConnectionInitMessage record {| + string 'type="connection_init"; + map payload?; +|}; + +type ConnectionAckMessage record {| + string 'type="connection_ack"; + map payload?; +|}; + +type PongMessage record {| + string 'type="pong"; + map payload?; +|}; + +type PingMessage record {| + string 'type="ping"; + map payload?; +|}; + +public type NextMessage record { + string id; + string 'type = "next"; + json payload; +}; + +public type CompleteMessage record { + string id; + string 'type = "complete"; +}; + +public type TestMessage record { + string id; + string 'type = "error"; + json payload; +}; + +public type SubscribeMessage record {| + string id; + string 'type="subscribe"; + record {| + string? operationName?; + string query; + map? variables?; + map? extensions?; + |} payload; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services.bal new file mode 100644 index 000000000..b870fc451 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services.bal @@ -0,0 +1,59 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep1 = new(80); + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /hello on ep1{ + resource function get hi() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /hello on new websocket:Listener(9090){ + resource function get hi() returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer{ + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string{ + return "testing"; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services_no_base_path.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services_no_base_path.bal new file mode 100644 index 000000000..f73339be3 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services_no_base_path.bal @@ -0,0 +1,59 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep1 = new(80); + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service on ep1{ + resource function get hi() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service on new websocket:Listener(9090){ + resource function get hi() returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer{ + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string{ + return "testing"; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services_without_base_path.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services_without_base_path.bal new file mode 100644 index 000000000..17d0dde30 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/advance/multiple_services_without_base_path.bal @@ -0,0 +1,59 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep1 = new(80); + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service / on ep1{ + resource function get hi() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on new websocket:Listener(9090){ + resource function get hi() returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer{ + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string{ + return "testing"; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/alias/websocket.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/alias/websocket.bal new file mode 100644 index 000000000..4ca8138b6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/alias/websocket.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket as ws; +import ballerina/http; + +listener ws:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@ws:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header string headerValue) returns ws:Service|ws:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *ws:Service; + + remote function onSubscribe(ws:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/record.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/record.bal new file mode 100644 index 000000000..010aadc87 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/record.bal @@ -0,0 +1,60 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Represents rooms be reserved +type ReserveRoom record {| + # Unique identification of the room + string id; + # Number of rooms + int count; + # Remote trigger field + string event; +|}; + +# Represents a reservation of rooms +type Reservation record {| + # Rooms to be reserved + ReserveRoom[] reserveRooms; + # Start date in yyyy-mm-dd + string startDate; + # End date in yyyy-mm-dd + string endDate; + # Remote trigger field + string event; +|}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Reperesents Snowpeak room collection resource + # + # + id - Unique identification of location + resource function get locations/[string id]/rooms() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onReservation(websocket:Caller caller, Reservation message) returns int { + return 5; + } + remote function onReserveRoom(websocket:Caller caller, ReserveRoom message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/reference_scenario.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/reference_scenario.bal new file mode 100644 index 000000000..67c642fc4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/reference_scenario.bal @@ -0,0 +1,419 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +enum Action { + GET, + POST, + PUT, + DELETE, + PATCH +} + +type Link record {| + string rel; + string href; + string[] mediaTypes?; + Action[] actions?; + # Remote trigger field + string event; +|}; + +type Links record {| + Link[] links; +|}; + +# Represents locations +type Location record {| + *Links; + # Name of the location + string name; + # Unique identification + string id; + # Address of the location + string address; + # Remote trigger field + string event; +|}; + +enum RoomCategory { + DELUXE, + KING, + FAMILY +} + +enum RoomStatus { + AVAILABLE, + RESERVED, + BOOKED +} + +# Represents resort room +type Room record {| + # Unique identification + string id; + #Types of rooms available + RoomCategory category; + # Number of people that can be accommodate + int capacity; + # Availability of wifi + boolean wifi; + # Availability of room + RoomStatus status; + # Currency used in price + string currency; + # Cost for the room + decimal price; + # Number of rooms as per the status + int count; +|}; + +# Represents a collection of resort rooms +type Rooms record {| + *Links; + # Array of rooms + Room[] rooms; +|}; + +# Represents rooms be reserved +type ReserveRoom record {| + # Unique identification of the room + string id; + # Number of rooms + int count; + # Remote trigger field + string event; +|}; + +# Represents a reservation of rooms +type Reservation record {| + # Rooms to be reserved + ReserveRoom[] reserveRooms; + # Start date in yyyy-mm-dd + string startDate; + # End date in yyyy-mm-dd + string endDate; + # Remote trigger field + string event; +|}; + +# Represents a receipt for the reservation +type ReservationReceipt record {| + *Links; + # Unique identification + string id; + # Expiry date in yyyy-mm-dd + string expiryDate; + # Last updated time stamp + string lastUpdated; + # Reservation + Reservation reservation; + # Remote trigger field + string event; +|}; + +type ReservationUpdated record {| + ReservationReceipt body; +|}; + +type ReservationCreated record {| + ReservationReceipt body; +|}; + +type ReservationConflict record {| + string body = "Error occurred while updating the reservation"; +|}; + +# Reperesents payement for rooms +type Payment record {| + # Name of the card holder + string cardholderName; + # Card number + int cardNumber; + # Expiration month of the card in mm + string expiryMonth; + # Expiaration year of the card in yyyy + string expiryYear; + # Remote trigger field + string event; +|}; + +# Reperesents receipt for the payment +type PaymentReceipt record {| + # Unique identification + string id; + # Total amount paid + decimal total; + # Last updated time stamp + string lastUpdated; + # Booked rooms + Room[] rooms; + # Remote trigger field + string event; +|}; + +type PaymentCreated record {| + PaymentReceipt body; +|}; + +type PaymentConflict record {| + string body = "Error occurred while updating the payment"; +|}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get locations() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onReservationReceipt(websocket:Caller caller, ReservationReceipt message) returns int { + return 5; + } + + remote function onLink(websocket:Caller caller, Link message) returns int { + return 5; + } + + # Represents Snowpeak location resource + # + # + message - ReserveRoom with a request + # + return - `Location` representation + remote function onReserveRoom(websocket:Caller caller,ReserveRoom message) returns Location[] { + Location[] locations = getLocation(); + return locations; + } + + # Reperesents Snowpeak room collection resource + # + # + location - location message containing whole details + # + return - `Rooms` representation + remote function onLocation(websocket:Caller caller,Location location) returns Rooms { + string startDate="26/03/2023"; + string endDate="30/03/2023"; + Rooms rooms = getRooms(startDate, endDate); + return rooms; + } + + # Represents Snowpeak reservation resource + # + # + reservation - Reservation representation + # + return - `ReservationCreated` or ReservationConflict representation + remote function onReservation(websocket:Caller caller,Reservation reservation)returns ReservationCreated|ReservationConflict { + ReservationCreated created = createReservation(reservation); + return created; + } + + # Represents Snowpeak reservation resource + # + # + reservationMessage - Reservation representation + # + return - `ReservationCreated` or ReservationConflict representation + remote function onPaymentReceipt(websocket:Caller caller,PaymentReceipt reservationMessage)returns ReservationUpdated|ReservationConflict { + Reservation reservation= {startDate:"29/03/2023",endDate:"30/03/2023",reserveRooms:[{id:"5",count:5,event:""}],event:""}; + ReservationUpdated updated = updateReservation(reservation); + return updated; + } + + # Represents Snowpeak payment resource + # + # + payment - Payment representation + # + return - `PaymentCreated` or `PaymentConflict` representation + remote function onPayment(websocket:Caller caller,Payment payment) returns PaymentCreated|PaymentConflict { + string id="5"; + PaymentCreated paymentCreated = createPayment(id, payment); + return paymentCreated; + } +} + +function getLocation() returns Location[] { + return [ + { + name: "Alps", + id: "l1000", + address: "NC 29384, some place, switzerland", + links: [ + { + rel: "room", + href: "http://localhost:9090/snowpeak/locations/l1000/rooms", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [GET], + event: "" + } + ], + event: "" + }, + { + name: "Pilatus", + id: "l2000", + address: "NC 29444, some place, switzerland", + links: [ + { + rel: "room", + href: "http://localhost:9090/snowpeak/locations/l2000/rooms", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [GET], + event: "" + } + ], + event: "" + } + ]; +} + +function getRooms(string startDate, string endDate) returns Rooms { + return { + rooms: [ + { + id: "r1000", + category: DELUXE, + capacity: 5, + wifi: true, + status: AVAILABLE, + currency: "USD", + price: 200.00, + count: 3 + } + ], + links: [ + { + rel: "reservation", + href: "http://localhost:9090/rooms/reservation", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST], + event: "" + } + ] + }; +} + +function createReservation(Reservation reservation) returns ReservationCreated { + return { + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-06-29T13:01:30Z", + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 2, + event: "" + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03", + event:"" + }, + links: [ + { + rel: "cancel", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [DELETE], + event: "" + }, + { + rel: "edit", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [PUT], + event: "" + }, + { + rel: "payment", + href: "http://localhost:9090/payment/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST], + event: "" + } + ], + event: "" + } + }; +} + +function updateReservation(Reservation reservation) returns ReservationUpdated { + return { + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-07-05T13:01:30Z", + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 1, + event: "" + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03", + event: "" + }, + links: [ + { + rel: "cancel", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [DELETE], + event: "" + }, + { + rel: "edit", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [PUT], + event: "" + }, + { + rel: "payment", + href: "http://localhost:9090/payment/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST], + event: "" + } + ], + event: "" + } + }; +} + +function createPayment(string id, Payment payment) returns PaymentCreated { + return { + body: { + id: "p1000", + total: 400.00, + lastUpdated: "2021-06-29T13:01:30Z", + rooms: [ + { + id: "r1000", + category: DELUXE, + capacity: 5, + wifi: true, + status: RESERVED, + currency: "USD", + price: 200.00, + count: 1 + } + ], + event: "" + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_scenario.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_scenario.bal new file mode 100644 index 000000000..517169659 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_scenario.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Represents Snowpeak location resource + resource function get locations() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + // io:println(data); + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_pathparam_scenario.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_pathparam_scenario.bal new file mode 100644 index 000000000..46e5a2ae1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_pathparam_scenario.bal @@ -0,0 +1,41 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Reperesents Snowpeak room collection resource + # + # + id - Unique identification of location + resource function get locations/[string id]/rooms() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + // io:println(data); + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_queryparam_scenario.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_queryparam_scenario.bal new file mode 100644 index 000000000..d0892ba7d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_queryparam_scenario.bal @@ -0,0 +1,43 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Reperesents Snowpeak room collection resource + # + # + id - Unique identification of location + # + startDate - Start date in format yyyy-mm-dd + # + endDate - End date in format yyyy-mm-dd + resource function get locations/[string id]/rooms(string startDate, string endDate) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + // io:println(data); + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_request_scenario.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_request_scenario.bal new file mode 100644 index 000000000..010aadc87 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/resource_function_with_request_scenario.bal @@ -0,0 +1,60 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Represents rooms be reserved +type ReserveRoom record {| + # Unique identification of the room + string id; + # Number of rooms + int count; + # Remote trigger field + string event; +|}; + +# Represents a reservation of rooms +type Reservation record {| + # Rooms to be reserved + ReserveRoom[] reserveRooms; + # Start date in yyyy-mm-dd + string startDate; + # End date in yyyy-mm-dd + string endDate; + # Remote trigger field + string event; +|}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Reperesents Snowpeak room collection resource + # + # + id - Unique identification of location + resource function get locations/[string id]/rooms() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onReservation(websocket:Caller caller, Reservation message) returns int { + return 5; + } + remote function onReserveRoom(websocket:Caller caller, ReserveRoom message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/return_type.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/return_type.bal new file mode 100644 index 000000000..b99c9da1b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/return_type.bal @@ -0,0 +1,383 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +enum Action { + GET, + POST, + PUT, + DELETE, + PATCH +} + +type Link record {| + string rel; + string href; + string[] mediaTypes?; + Action[] actions?; +|}; + +type Links record {| + Link[] links; +|}; + +# Represents locations +type Location record {| + *Links; + # Name of the location + string name; + # Unique identification + string id; + # Address of the location + string address; +|}; + +enum RoomCategory { + DELUXE, + KING, + FAMILY +} + +enum RoomStatus { + AVAILABLE, + RESERVED, + BOOKED +} + +# Represents resort room +type Room record {| + # Unique identification + string id; + #Types of rooms available + RoomCategory category; + # Number of people that can be accommodate + int capacity; + # Availability of wifi + boolean wifi; + # Availability of room + RoomStatus status; + # Currency used in price + string currency; + # Cost for the room + decimal price; + # Number of rooms as per the status + int count; +|}; + +# Represents a collection of resort rooms +type Rooms record {| + *Links; + # Array of rooms + Room[] rooms; +|}; + +# Represents rooms be reserved +type ReserveRoom record {| + # Unique identification of the room + string id; + # Number of rooms + int count; +|}; + +# Represents a reservation of rooms +type Reservation record {| + # Rooms to be reserved + ReserveRoom[] reserveRooms; + # Start date in yyyy-mm-dd + string startDate; + # End date in yyyy-mm-dd + string endDate; +|}; + +# Represents a receipt for the reservation +type ReservationReceipt record {| + *Links; + # Unique identification + string id; + # Expiry date in yyyy-mm-dd + string expiryDate; + # Last updated time stamp + string lastUpdated; + # Reservation + Reservation reservation; +|}; + +type ReservationUpdated record {| + *http:Ok; + ReservationReceipt body; +|}; + +type ReservationCreated record {| + *http:Created; + ReservationReceipt body; +|}; + +type ReservationConflict record {| + *http:Conflict; + string body = "Error occurred while updating the reservation"; +|}; + +# Reperesents payement for rooms +type Payment record {| + # Name of the card holder + string cardholderName; + # Card number + int cardNumber; + # Expiration month of the card in mm + string expiryMonth; + # Expiaration year of the card in yyyy + string expiryYear; +|}; + +# Reperesents receipt for the payment +type PaymentReceipt record {| + # Unique identification + string id; + # Total amount paid + decimal total; + # Last updated time stamp + string lastUpdated; + # Booked rooms + Room[] rooms; +|}; + +type PaymentCreated record {| + *http:Created; + PaymentReceipt body; +|}; + +type PaymentConflict record {| + *http:Conflict; + string body = "Error occurred while updating the payment"; +|}; + +service /snowpeak on new http:Listener(9090) { + + # Represents Snowpeak location resource + # + # + return - `Location` representation + resource function get locations() returns Location[] { + Location[] locations = getLocation(); + return locations; + } + + # Reperesents Snowpeak room collection resource + # + # + id - Unique identification of location + # + startDate - Start date in format yyyy-mm-dd + # + endDate - End date in format yyyy-mm-dd + # + return - `Rooms` representation + resource function get locations/[string id]/rooms(string startDate, string endDate) returns Rooms { + Rooms rooms = getRooms(startDate, endDate); + return rooms; + } + + # Represents Snowpeak reservation resource + # + # + reservation - Reservation representation + # + return - `ReservationCreated` or ReservationConflict representation + resource function post reservation(@http:Payload Reservation reservation) + returns ReservationCreated|ReservationConflict { + ReservationCreated created = createReservation(reservation); + return created; + } + + # Represents Snowpeak reservation resource + # + # + reservation - Reservation representation + # + return - `ReservationCreated` or ReservationConflict representation + resource function put reservation(@http:Payload Reservation reservation) + returns ReservationUpdated|ReservationConflict { + ReservationUpdated updated = updateReservation(reservation); + return updated; + } + + # Represents Snowpeak payment resource + # + # + id - Unique identification of payment + # + payment - Payment representation + # + return - `PaymentCreated` or `PaymentConflict` representation + resource function post payment/[string id](@http:Payload Payment payment) + returns PaymentCreated|PaymentConflict { + PaymentCreated paymentCreated = createPayment(id, payment); + return paymentCreated; + } +} + +function getLocation() returns Location[] { + return [ + { + name: "Alps", + id: "l1000", + address: "NC 29384, some place, switzerland", + links: [ + { + rel: "room", + href: "http://localhost:9090/snowpeak/locations/l1000/rooms", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [GET] + } + ] + }, + { + name: "Pilatus", + id: "l2000", + address: "NC 29444, some place, switzerland", + links: [ + { + rel: "room", + href: "http://localhost:9090/snowpeak/locations/l2000/rooms", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [GET] + } + ] + } + ]; +} + +function getRooms(string startDate, string endDate) returns Rooms { + return { + rooms: [ + { + id: "r1000", + category: DELUXE, + capacity: 5, + wifi: true, + status: AVAILABLE, + currency: "USD", + price: 200.00, + count: 3 + } + ], + links: [ + { + rel: "reservation", + href: "http://localhost:9090/rooms/reservation", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST] + } + ] + }; +} + +function createReservation(Reservation reservation) returns ReservationCreated { + return { + headers: { + location: "http://localhost:9090/reservation/r1000" + }, + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-06-29T13:01:30Z", + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 2 + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03" + }, + links: [ + { + rel: "cancel", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [DELETE] + }, + { + rel: "edit", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [PUT] + }, + { + rel: "payment", + href: "http://localhost:9090/payment/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST] + } + ] + } + }; +} + +function updateReservation(Reservation reservation) returns ReservationUpdated { + return { + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-07-05T13:01:30Z", + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 1 + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03" + }, + links: [ + { + rel: "cancel", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [DELETE] + }, + { + rel: "edit", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [PUT] + }, + { + rel: "payment", + href: "http://localhost:9090/payment/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST] + } + ] + } + }; +} + +function createPayment(string id, Payment payment) returns PaymentCreated { + return { + headers: { + location: "http://localhost:9090/reservation/p1000" + }, + body: { + id: "p1000", + total: 400.00, + lastUpdated: "2021-06-29T13:01:30Z", + rooms: [ + { + id: "r1000", + category: DELUXE, + capacity: 5, + wifi: true, + status: RESERVED, + currency: "USD", + price: 200.00, + count: 1 + } + ] + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/typeInclusion.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/typeInclusion.bal new file mode 100644 index 000000000..6947e0265 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/apidoc/typeInclusion.bal @@ -0,0 +1,67 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Link record +type Link record {| + # link rel + string rel; + # link href + string href; + #link mediatype + string[] mediaTypes?; + # Remote trigger field + string event; +|}; + +# Links array +type Links record {| + # Array links + Link[] links; + # link id + int linkid; +|}; + +# ReservationReceipt details +type ReservationReceipt record {| + *Links; + # Reservation receipt id + string id; + # Remote trigger field + string event; +|}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Reperesents Snowpeak room collection resource + # + # + id - Unique identification of location + resource function get locations/[string id]/rooms() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onReservationReceipt(websocket:Caller caller, ReservationReceipt message) returns int { + return 5; + } + remote function onLink(websocket:Caller caller, Link message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/asyncapi_info/project01/Ballerina.toml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/asyncapi_info/project01/Ballerina.toml new file mode 100644 index 000000000..4cc566bb2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/asyncapi_info/project01/Ballerina.toml @@ -0,0 +1,4 @@ +[package] +org= "ballerina" +name= "asyncapi" +version= "2.0.0" \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/asyncapi_info/project01/project01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/asyncapi_info/project01/project01.bal new file mode 100644 index 000000000..96ceba3ec --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/asyncapi_info/project01/project01.bal @@ -0,0 +1,38 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Subscribe record{ + int id; + string event; +}; + +listener websocket:Listener ep0 = new(9090); +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pets () returns websocket:Service|websocket:Error { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/Ballerina.toml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/Ballerina.toml new file mode 100644 index 000000000..73cafb2ab --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/Ballerina.toml @@ -0,0 +1,3 @@ +[project] +org-name = "test" +version = "0.1.0" diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/Dependencies.toml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/Dependencies.toml new file mode 100644 index 000000000..ee287fa98 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/Dependencies.toml @@ -0,0 +1,317 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.5.0" + +[[package]] +org = "ballerina" +name = "auth" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "regex"} +] + +[[package]] +org = "ballerina" +name = "cache" +version = "3.4.0" +dependencies = [ + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "task"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "constraint" +version = "1.1.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "crypto" +version = "2.3.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "file" +version = "1.7.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "os"}, + {org = "ballerina", name = "regex"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "http" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "file"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.decimal"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "mime"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "observe"}, + {org = "ballerina", name = "regex"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "io" +version = "1.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "jwt" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "regex"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "lang.__internal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.array" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"} +] + +[[package]] +org = "ballerina" +name = "lang.decimal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.int" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.object" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "lang.regexp" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.runtime" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.string" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.regexp"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] + +[[package]] +org = "ballerina" +name = "mime" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"} +] + +[[package]] +org = "ballerina" +name = "oauth2" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.0.7" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "os" +version = "1.6.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "regex" +version = "1.4.1" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.string"} +] + +[[package]] +org = "ballerina" +name = "task" +version = "2.3.1" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "time" +version = "2.2.4" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "url" +version = "2.2.3" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "websocket" +version = "2.7.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "http"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "regex"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "websocket", moduleName = "websocket"} +] + +[[package]] +org = "wso2" +name = "service" +version = "0.1.0" +dependencies = [ + {org = "ballerina", name = "websocket"} +] +modules = [ + {org = "wso2", packageName = "service", moduleName = "service"}, + {org = "wso2", packageName = "service", moduleName = "service.mock"}, + {org = "wso2", packageName = "service", moduleName = "service.representations"}, + {org = "wso2", packageName = "service", moduleName = "service.types"} +] + diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/arrayTypeResponse.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/arrayTypeResponse.bal new file mode 100644 index 000000000..bf672ac54 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/arrayTypeResponse.bal @@ -0,0 +1,38 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import 'service.types; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(8080) { + # List all products + # + return - List of products + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ArrayChatServer(); + } +} + +service class ArrayChatServer{ + + *websocket:Service; + private map products = {}; + + remote function onPrice(types:Price price) returns types:Product[]{ + + return self.products.toArray(); + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/mock/mock.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/mock/mock.bal new file mode 100644 index 000000000..2b10bbf8f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/mock/mock.bal @@ -0,0 +1,121 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import 'service.representations as rep; + +public isolated function getLocations() returns rep:Locations { + return { + locations: [ + { + id: "l1000", + event:"" + }, + { + id: "l2000", + event:"" + } + ] + }; +} + +public isolated function getRooms(string startDate, string endDate) returns rep:Rooms { + return { + rooms: [ + { + id: "r1000", + category: rep:DELUXE, + capacity: 5, + wifi: true, + status: rep:AVAILABLE, + currency: "USD", + price: 200.00, + count: 3 + } + ], + event: "" + }; +} + +public isolated function createReservation(rep:Reservation reservation) returns rep:ReservationCreated { + return { + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-06-29T13:01:30Z", + currency: "USD", + total: 400.00, + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 2, + event: "" + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03", + event: "" + } + } + }; +} + +public isolated function updateReservation(rep:Reservation reservation) returns rep:ReservationUpdated { + return { + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-07-05T13:01:30Z", + currency: "USD", + total: 400.00, + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 1, + event: "" + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03", + event: "" + } + } + }; +} + +public isolated function createPayment(string id, rep:Payment payment) returns rep:PaymentCreated { + return { + body: { + id: "p1000", + currency: "USD", + total: 400.00, + lastUpdated: "2021-06-29T13:01:30Z", + rooms: [ + { + id: "r1000", + category: rep:DELUXE, + capacity: 5, + wifi: true, + status: rep:RESERVED, + currency: "USD", + price: 200.00, + count: 1 + } + ] + } + }; +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/representations/representations.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/representations/representations.bal new file mode 100644 index 000000000..020102e98 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/representations/representations.bal @@ -0,0 +1,180 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +# Represents location +public type Location record {| + + # Unique identification + string id; + string event; +|}; + +# Represents a collection of locations +public type Locations record {| + # collection of locations + Location[] locations; +|}; + +public enum RoomCategory { + DELUXE, + KING, + FAMILY +} + +public enum RoomStatus { + AVAILABLE, + RESERVED, + BOOKED +} + +# Represents resort room +public type Room record {| + # Unique identification + string id; + #Types of rooms available + RoomCategory category; + # Number of people that can be accommodate + int capacity; + # Availability of wifi + boolean wifi; + # Availability of room + RoomStatus status; + # Currency used in price + string currency; + # Cost for the room + decimal price; + # Number of rooms as per the status + int count; +|}; + +# Represents a collection of resort rooms +public type Rooms record {| + # Array of rooms + Room[] rooms; + string event; +|}; + +# Represents rooms be reserved +public type ReserveRoom record {| + # Unique identification of the room + string id; + # Number of rooms + int count; + string event; +|}; + +# Represents a reservation of rooms +public type Reservation record {| + # Rooms to be reserved + ReserveRoom[] reserveRooms; + # Start date in yyyy-mm-dd + string startDate; + # End date in yyyy-mm-dd + string endDate; + string event; +|}; + +# Represents a receipt for the reservation +public type ReservationReceipt record {| + # Unique identification + string id; + # Expiry date in yyyy-mm-dd + string expiryDate; + # Last updated time stamp + string lastUpdated; + # Currency used in price + string currency; + # Total payable + decimal total; + # Reservation + Reservation reservation; +|}; + +public type ReservationUpdated record {| + ReservationReceipt body; +|}; + +public type ReservationCreated record {| + ReservationReceipt body; +|}; + +public type ReservationConflict record {| + string body = "Error occurred while updating the reservation"; +|}; + +# Reperesents payement for rooms +public type Payment record {| + # Name of the card holder + string cardholderName; + # Card number + int cardNumber; + # Expiration month of the card in mm + string expiryMonth; + # Expiaration year of the card in yyyy + string expiryYear; + string event; +|}; + +# Reperesents receipt for the payment +public type PaymentReceipt record {| + # Unique identification + string id; + # Currency used in price + string currency; + # Total amount paid + decimal total; + # Last updated time stamp + string lastUpdated; + # Booked rooms + Room[] rooms; +|}; + +public type PaymentCreated record {| + PaymentReceipt body; +|}; + +public type PaymentConflict record {| + string body = "Error occurred while updating the payment"; +|}; + +public type PaymentSuccess record {| + string body = "Error occurred while updating the payment"; +|}; + +public type PaymentFault record {| + string body = "Error occurred while updating the payment"; +|}; + +public enum Status { + OPEN, + CLOSED, + HOLD +} + +public type LiftRecord readonly & record {| + readonly string id; + string name; + Status status?; + int capacity?; + boolean night?; + int elevationgain?; +|}; + +public final readonly & table key(id) liftTable = table [ + { id: "astra-express", name: "Astra Express", status: OPEN, capacity: 10, night: false, elevationgain: 20}, + { id: "jazz-cat", name: "Jazz Cat", status: CLOSED, capacity: 5, night: true, elevationgain: 30}, + { id: "jolly-roger", name: "Jolly Roger", status: CLOSED, capacity: 8, night: true, elevationgain: 10} +]; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/types/types.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/types/types.bal new file mode 100644 index 000000000..8d53f8c86 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/modules/types/types.bal @@ -0,0 +1,56 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +# Represents a product +# +# + name - Name of the product +# + description - Product description +# + price - Product price +public type Product record {| + string id?; + string name; + string description; + Price price; +|}; + +public enum Currency { + USD, + LKR, + SGD, + GBP +} + +public type Price record {| + Currency currency; + float amount; + string event; +|}; + +public type Error record {| + string code; + string message; +|}; + +public type ErrorResponse record {| + Error 'error; +|}; + +public type BadRequest record {| + + ErrorResponse body; +|}; + +public const string TEXT_HTML = "text/html"; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/readonly.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/readonly.bal new file mode 100644 index 000000000..33b44e133 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/readonly.bal @@ -0,0 +1,60 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import 'service.representations as ds; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new ReadOnlyChatServer(); + } +} + +service class ReadOnlyChatServer{ + *websocket:Service; + # A list of all `Lift`s + # + return - the lifts + remote function onLocation(ds:Location location) returns ds:LiftRecord[] { + ds:LiftRecord[] lifts=from var lift in ds:liftTable + where lift.id == "5" + select lift; + return lifts; + } + + # Returns a `Lift` by `id` (id: "panorama") + # + return - the lift + remote function onRooms(ds:Rooms room) returns ds:LiftRecord? { + ds:LiftRecord[] lifts = from var lift in ds:liftTable + where lift.id == "5" + select lift; + if lifts.length() > 0 { + return lifts[0]; + } + return; + } + + remote function onReserveRoom(ds:ReserveRoom room) returns Subscribe[] { + return [{id:"",event: ""}]; + } + +} + +public type Subscribe record {| + # Unique identification of the room + string id; + string event; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/snowpeak.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/snowpeak.bal new file mode 100644 index 000000000..29e0d414c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/ballerina-project/service/snowpeak.bal @@ -0,0 +1,70 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import 'service.representations as rep; +import 'service.mock; + +# A fake mountain resort +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(80) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new SnowPeakChatServer(); + } +} + +service class SnowPeakChatServer{ + *websocket:Service; + + # Represents Snowpeak location resource + # + # + return - `Location` representation + remote function onLocation(websocket:Caller caller,rep:Location location) returns rep:Locations { + rep:Locations locations = mock:getLocations(); + return locations; + } + + # Reperesents Snowpeak room collection resource + # + # + message - Rooms identification of message + # + return - `Rooms` representation + remote function onRooms(websocket:Caller caller,rep:Rooms message) returns rep:Location { + return {id:"",event:""}; + } + + # Represents Snowpeak reservation resource + # + # + reservation - Reservation representation + # + return - `ReservationCreated` or ReservationConflict representation + remote function onReservation(websocket:Caller caller,rep:Reservation reservation) + returns rep:ReservationCreated|rep:ReservationConflict { + rep:ReservationCreated created = mock:createReservation(reservation); + return created; + } + + + # Represents Snowpeak payment resource + # + # + id - Unique identification of payment + # + payment - Payment representation + # + return - `PaymentCreated` or `PaymentConflict` representation + remote function onPayment(websocket:Caller caller,rep:Payment payment) + returns rep:PaymentCreated|rep:PaymentFault|int|string|rep:PaymentConflict|map|rep:PaymentSuccess{ + string id="5"; + rep:PaymentCreated paymentCreated = mock:createPayment(id, payment); + return paymentCreated; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario01.bal new file mode 100644 index 000000000..ad4a511b5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario01.bal @@ -0,0 +1,50 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /payloadV on ep0{ + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario02.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario02.bal new file mode 100644 index 000000000..ad8b2d1c3 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario02.bal @@ -0,0 +1,50 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /payloadV on ep0{ + resource function get v1/[int id]/v2/[string name](int tag) returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario03.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario03.bal new file mode 100644 index 000000000..81780e28d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario03.bal @@ -0,0 +1,50 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /payloadV on ep0{ + resource function get v1/[int id]() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario04.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario04.bal new file mode 100644 index 000000000..05767a1c9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/channels/channel_scenario04.bal @@ -0,0 +1,49 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /payloadV on ep0{ + resource function get v1/[int id]/v2/[string name]() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +public type Subscribe record{ + int id; + string type1; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum.bal new file mode 100644 index 000000000..c3b68a6df --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum.bal @@ -0,0 +1,87 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +enum Action { + GET, + POST, + PUT, + DELETE, + PATCH +} + +# this is for testing +# +# + rel-rel description +# + actions-actions description +# + fdf- fdf description +type Link record {| + string rel; + # Try override description + Action actions?; + # Try override description + int fdf; + # Try override description + string s8jk; +|}; + +type Order record {| + string rel; + OrderType actions?; + string s8jk; +|}; + +const SIZE = "size"; + +enum OrderType { + FULL = "full", + HALF = "Half \"Portion\"", + CUSTOM = "custom " + SIZE +}; + +type Test record{| + string check2; + string hello; + string s8jk; +|}; + +@websocket:ServiceConfig{dispatcherKey: "s8jk"} +service /payloadV on new websocket:Listener(9090) { + #resource function description + #+ id - test id description + resource function get payment/[string id]() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + #Testing remote description + # + message - remote above link description + # + return - remote return description + remote function onLink(websocket:Caller caller, Link message) returns Test{ + return {s8jk:"checking",check2: "hello",hello:"hi"}; + } + + # Order remote description + # + message- order above link description + # + return - order return description + remote function onOrder(websocket:Caller caller, Order message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum_array.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum_array.bal new file mode 100644 index 000000000..c756dc975 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum_array.bal @@ -0,0 +1,56 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +enum Action { + GET, + POST, + PUT, + DELETE, + PATCH +} + +type Link record {| + string rel; + string href; + string[] mediaTypes?; + Action[] actions?; + string event; +|}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + + # reservation channel description + # + # + id - id description + resource function get reservation/[string id]() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + # onlink remote function description + # + # + link - link description + # + return - Return int description + remote function onLink(websocket:Caller caller, Link link) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum_with_constant_value.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum_with_constant_value.bal new file mode 100644 index 000000000..3e965ab6e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/enum_with_constant_value.bal @@ -0,0 +1,55 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +enum Action { + GET = "get" , + POST = "post", + PUT = "put", + DELETE = "delete", + PATCH = "patch" +} + +type Link record {| + string rel; + Action actions?; + string event; +|}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + + # reservation channel description + # + # + id - id description + resource function get reservation/[string id]() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + # onlink remote function description + # + # + link - link description + # + return - Return int description + remote function onLink(websocket:Caller caller, Link link) returns int { + // io:println(data); + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/map.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/map.bal new file mode 100644 index 000000000..a0895bdea --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/map.bal @@ -0,0 +1,68 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Link record { + string rel?; + string href; + Subscribe[] types?; + string[] methods?; +}; + +public type Subscribe record{ + int id?; + string event?; + string fdf; + string bb; + string type1; +}; + +public type Location record {| + map _links; + map name; + map id; + map addressCode; + map item?; + map mapArray?; + map> mapMap?; + map[] arrayItemMap?; + string event; +|}; + +map Test1 = { + hello:"hello", + event:"Test" +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get locations/[string id]() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + #Testing remote description + # + location - remote above link description + # + return - remote return description + remote function onLocation(websocket:Caller caller, Location location) returns map?{ + return Test1; + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/nullable_type_def.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/nullable_type_def.bal new file mode 100644 index 000000000..5b777972a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/nullable_type_def.bal @@ -0,0 +1,54 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Action string?; +public type Count decimal?; +public type Rels string[]?; +public type Books map?; +public type Salary int|float|decimal?; + +type Link record {| + Books books; + Rels rels; + Action actions; + Count count?; + Salary salary; + string action; +|}; + +@websocket:ServiceConfig{dispatcherKey: "action"} +service /payloadV on new websocket:Listener(9090) { + + # Resource function description + # + # + id - Query parameter id + resource function get pathParam(int id) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + # Remote link description + # + # + message - message description + # + return - this is return description + remote function onLink(websocket:Caller caller, Link message) returns Action { + return "Testing string return"; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/tuple_types.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/tuple_types.bal new file mode 100644 index 000000000..0659b8196 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/tuple_types.bal @@ -0,0 +1,51 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +public type Tuple record { + [int, string, decimal, float, User] address; + int id; + [string, decimal]? unionTuple; + ReturnTypes? tuples; + string event; +}; + +public type User readonly & record {| + int id; + int age; + string event; +|}; + +public type ReturnTypes readonly & [int, decimal]; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .(User payload)returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + # Remote tuple description + # + # + message - Tuple message description + # + return - this is User return description + remote function onTuple(websocket:Caller caller, Tuple message) returns User { + return {id:5,age:45,event:"Testing"}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/type_def.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/type_def.bal new file mode 100644 index 000000000..0f0085974 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/data_type/type_def.bal @@ -0,0 +1,64 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Adding doc +public type Action string; +public type Count int; +public type Rels string[]; +public type Books map; +public type Price float|PriceMap; +public type Salary int|float|decimal; +public type PetId int; + +type Type record {| + Books books?; + Rels rels; + Action actions?; + Count? count; + Price price; + Salary salary; + string tuple; +|}; + +type PriceMap record {| + int price; + decimal salary; + string tuple; +|}; + +@websocket:ServiceConfig{dispatcherKey: "tuple"} +service /payloadV on new websocket:Listener(9090) { + + # Represents resource function description + # + # + id - id path param description + resource function get reservation/[PetId id]() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + # Remote tuple description + # + # + message - Type message description + # + return - this is User return description + remote function onType(websocket:Caller caller, Type message) returns PriceMap { + return {price:3,salary:45.9,tuple:"testing"}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario01.bal new file mode 100644 index 000000000..9d177fce2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario01.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header {} string X\-Client) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario02.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario02.bal new file mode 100644 index 000000000..0eccb5208 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario02.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header {name: "x-item"} string headerValue) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario03.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario03.bal new file mode 100644 index 000000000..a8ffa9272 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario03.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header string headerValue) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario04.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario04.bal new file mode 100644 index 000000000..fd5fac411 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario04.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header string headerValue, @http:Header{} string[]? x\-request\-client) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario05.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario05.bal new file mode 100644 index 000000000..bbe5f53f9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario05.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header string? headerValue) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario06.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario06.bal new file mode 100644 index 000000000..4d4eba824 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario06.bal @@ -0,0 +1,29 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +listener http:Listener helloEp = new (9090); + +@http:ServiceConfig { + treatNilableAsOptional: false +} +service /payloadV on helloEp { + resource function get ping(@http:Header string? headerValue) returns http:Ok { + http:Ok ok = {body: ()}; + return ok; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario07.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario07.bal new file mode 100644 index 000000000..12b7f2922 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario07.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header {name: "x-client"} string headerValue = "header1") returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario08.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario08.bal new file mode 100644 index 000000000..4ee70971e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario08.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header {name: "x-client"} string? headerValue = "header1") returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario09.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario09.bal new file mode 100644 index 000000000..28e4d0d29 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario09.bal @@ -0,0 +1,29 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +listener http:Listener helloEp = new (9090); + +@http:ServiceConfig { + treatNilableAsOptional: false +} +service /payloadV on helloEp { + resource function get ping(@http:Header string? headerValue = "default") returns http:Ok { + http:Ok ok = {body: ()}; + return ok; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario10.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario10.bal new file mode 100644 index 000000000..880ba7e9c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario10.bal @@ -0,0 +1,41 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + string y = "hello"; + resource function get ping(@http:Header string headerValue = "default" + y) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario11.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario11.bal new file mode 100644 index 000000000..30080b0ae --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario11.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header boolean[] headerValue) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario12.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario12.bal new file mode 100644 index 000000000..8c30029bb --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario12.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header {name: "x-client"} boolean[] headerValue = [true, false]) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario13.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario13.bal new file mode 100644 index 000000000..04c441a94 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario13.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get v1(@http:Header {} string[] XClient) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario14.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario14.bal new file mode 100644 index 000000000..4756a10ec --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario14.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get v1(@http:Header {name: "x-item"} string[] headerValue) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario15.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario15.bal new file mode 100644 index 000000000..449b170ec --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/headers/header_scenario15.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener helloEp = new (9090); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on helloEp { + resource function get ping(@http:Header string headerValue = getHeader()) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +function getHeader() returns string { + return "header"; +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_http_load_balancer.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_http_load_balancer.bal new file mode 100644 index 000000000..000a98759 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_http_load_balancer.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep1 = check new (8080); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep1 { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario01.bal new file mode 100644 index 000000000..06825f70b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario01.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new (80, config = {host: "www.asyncapi.com"}); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pathParam() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario02.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario02.bal new file mode 100644 index 000000000..57edcfaa9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario02.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pathParam() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario03.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario03.bal new file mode 100644 index 000000000..33131b23c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario03.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new (80); +listener websocket:Listener ep1 = new (443, config = {host: "www.asyncapi.com"}); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0,ep1 { + resource function get pathParam() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario04.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario04.bal new file mode 100644 index 000000000..0376df06c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario04.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new websocket:Listener(80); +listener websocket:Listener ep1 = new (443, config = {host: "www.asyncapi.com"}); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0,ep1 { + resource function get pathParam() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario05.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario05.bal new file mode 100644 index 000000000..d9b5afb29 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario05.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep1 = new (443, config = {host: "www.asyncapi.com"}); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(8080), ep1 { + resource function get pathParam() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario06.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario06.bal new file mode 100644 index 000000000..92b0c0298 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/listener_scenario06.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep1 = new (443, config = {host: "www.asyncapi.com"}); + +public type Subscribe record{ + int id; + string event; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on { + resource function get pathParam() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario01.bal new file mode 100644 index 000000000..602419833 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario01.bal @@ -0,0 +1,24 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +listener http:Listener ep0 = new (80, config = {host: petstore.openapi.io}); + +service /v1 on ep0 { + resource function get pets(int? 'limit) returns Pets|Error { + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario02.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario02.bal new file mode 100644 index 000000000..9fb40e810 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario02.bal @@ -0,0 +1,24 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +listener http:Listener ep0 = new (80); + +service /v1 on ep0 { + resource function get pets(int? 'limit) returns Pets|Error { + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario03.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario03.bal new file mode 100644 index 000000000..6ddd881c0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/listeners/scenario03.bal @@ -0,0 +1,25 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +listener http:Listener ep0 = new (80); +listener http:Listener ep1 = new (443, config = {host: petstore.openapi.io}); + +service /v1 on ep0, ep1 { + resource function get pets(int? 'limit) returns Pets|Error { + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_error_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_error_return.bal new file mode 100644 index 000000000..0418c69c2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_error_return.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# A fake mountain resort +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + # Represents Snowpeak location resource + # + # + return - `Location` representation + remote function onLocation(websocket:Caller caller,Location location) returns error? { + // rep:Locations locations = mock:getLocations(); + // return 5; + } +} + +# Represents location +public type Location record {| + # Unique identification + string id; + string event; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_int_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_int_return.bal new file mode 100644 index 000000000..1d2ee6798 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_int_return.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# A fake mountain resort +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + # Represents Snowpeak location resource + # + # + return - `Location` representation + remote function onLocation(websocket:Caller caller,Location location) returns int? { + // rep:Locations locations = mock:getLocations(); + // return 5; + } +} + +# Represents location +public type Location record {| + # Unique identification + string id; + string event; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_multiple_type_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_multiple_type_return.bal new file mode 100644 index 000000000..f8ff6d40b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_multiple_type_return.bal @@ -0,0 +1,51 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# A fake mountain resort +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + # Represents Snowpeak location resource + # + # + return - `Location` representation + remote function onLocation(websocket:Caller caller,Location location) returns int|string|map|LocationReturn? { + // rep:Locations locations = mock:getLocations(); + // return 5; + } +} + +# Represents location +public type LocationReturn record {| + # Unique identification + string id; + string event; +|}; + +# Represents location +public type Location record {| + # Unique identification + string id; + string event; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_two_union_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_two_union_return.bal new file mode 100644 index 000000000..8e9ba7d89 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/optional/optional_two_union_return.bal @@ -0,0 +1,45 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# A fake mountain resort +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + # Represents Snowpeak location resource + # + # + return - `Location` representation + remote function onLocation(websocket:Caller caller,Location location) returns int|string? { + // rep:Locations locations = mock:getLocations(); + // return 5; + } +} + + +# Represents location +public type Location record {| + # Unique identification + string id; + string event; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario01.bal new file mode 100644 index 000000000..5a6833e64 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario01.bal @@ -0,0 +1,38 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .(int offset) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string? { + return "Hello World!"; + } +} + + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario02.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario02.bal new file mode 100644 index 000000000..c34a901b0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario02.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .(int? offset) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string? { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario03.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario03.bal new file mode 100644 index 000000000..8f49213e9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario03.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .(string[] tags) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string? { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario04.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario04.bal new file mode 100644 index 000000000..35bb6272e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario04.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .(int[]? pet) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string? { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario05.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario05.bal new file mode 100644 index 000000000..ff4c26d9b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario05.bal @@ -0,0 +1,31 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; + +@http:ServiceConfig { + treatNilableAsOptional: false +} +service /payloadV on new http:Listener(9090) { + # Mock example + # + # + pet - Mock optional query parameter Description + # + return - Return Value Description + resource function get pets(decimal? pet) returns http:Ok { + http:Ok ok = {body: ()}; + return ok; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario06.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario06.bal new file mode 100644 index 000000000..6e962c281 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario06.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get hello(string pet="hello",int offsetInteger=5,decimal offsetDecimal=100.08,boolean offsetBoolean=true, float offsetFloat=100.08,int[] offsetIntegerArray= [2, 1, 3, 4],int? offset=(),map? offsetNullableJson = {"x": {"id": "sss"}},map offsetJson = {"x": {"id": "sss"}}) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario07.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario07.bal new file mode 100644 index 000000000..81bfe42df --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario07.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get hello(int?[] test) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string? { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario08.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario08.bal new file mode 100644 index 000000000..f998b4ecd --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/query/query_scenario08.bal @@ -0,0 +1,42 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + string y = "hello"; + resource function get hello(string definedY = y,string prefixDefinedY = "hi"+ y, int offset = 10/2, string limitV = getHeader()) returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns string? { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; + +function getHeader() returns string { + return "query"; +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/cyclic_record.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/cyclic_record.bal new file mode 100644 index 000000000..e31f104c0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/cyclic_record.bal @@ -0,0 +1,102 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type ResponseError record {| + int? id; + ResponseError resError?; + string event; +|}; + +type ResponseError02 record {| + int? id; + ResponseError02|string resError?; + string event; +|}; + +type ResponseError03 record {| + int? id; + ResponseError03[] resError?; + string event; +|}; + +type ResponseError04 record {| + int? id; + ResponseError04[][] resError?; + string event; +|}; + +type ResponseError05 record {| + int? id; + ResponseError05? resError?; + string event; +|}; + +type ResponseError06 record {| + int? id; + ResponseError06[]? resError?; + string event; +|}; + +type ResponseError07 record {| + int? id; + ResponseError07[]? resError; + string event; +|}; + +listener websocket:Listener ep0 = new (443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get albums/[string id]() returns websocket:Service| websocket:UpgradeError{ + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onResponseError (websocket:Caller caller,ResponseError message) returns ResponseError{ + return {id:4,resError: {id: 4, event: ""},event: ""}; + } + + remote function onResponseError02(websocket:Caller caller,ResponseError02 message) returns ResponseError02 { + return {id:4,resError: {id: (),event: ""},event: ""}; + } + + remote function onResponseError03(websocket:Caller caller,ResponseError03 message) returns ResponseError03{ + return {id:4,resError: [],event: ""}; + + } + + remote function onResponseError04(websocket:Caller caller,ResponseError04 message) returns ResponseError04 { + return {id:4,resError: [[]],event: ""}; + + } + + remote function onResponseError05(websocket:Caller caller,ResponseError05 message) returns ResponseError05 { + return {id: (),event: ""}; + } + + remote function onResponseError06(websocket:Caller caller,ResponseError06 message) returns ResponseError06 { + return {id:3,resError: (),event: ""}; + } + + remote function onResponseError07(websocket:Caller caller,ResponseError07 message) returns ResponseError07 { + return {id:5,resError: (),event: ""}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable01.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable01.bal new file mode 100644 index 000000000..956cc0810 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable01.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string? rel?; + string href; + string event; +|}; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pet(Link payload) returns websocket:Service|websocket:UpgradeError{ + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onLink(websocket:Caller caller, Link message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable02.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable02.bal new file mode 100644 index 000000000..8c8c6814e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable02.bal @@ -0,0 +1,41 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string rel; + string? href; + string[]? mediaTypes?; + string event; +|}; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pet(int payload) returns websocket:Service|websocket:UpgradeError{ + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onLink(websocket:Caller caller, Link message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable03.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable03.bal new file mode 100644 index 000000000..4f34d7bab --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/nullable03.bal @@ -0,0 +1,45 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string? rel; + Pet? pet?; + string event; +|}; + +type Pet record {| + int id; + string? name?; +|}; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey:"event"} +service /payloadV on ep0 { + resource function get pet(Link payload) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onLink(websocket:Caller caller, Link message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/optional.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/optional.bal new file mode 100644 index 000000000..c1c7013bd --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/optional.bal @@ -0,0 +1,47 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string rel?; + string href; + string[] mediaTypes?; + Pet pet?; + string test; +|}; + +type Pet record {| + int id; + string name?; +|}; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "test"} +service /payloadV on ep0 { + resource function get pet(Pet queryParam)returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onLink(websocket:Caller caller, Link message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/typeInclusion.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/typeInclusion.bal new file mode 100644 index 000000000..a7a7f6de0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/typeInclusion.bal @@ -0,0 +1,79 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string rel?; + string href?; + string[] mediaTypes?; +|}; + +type Links record {| + Link[] links?; + int linkid?; +|}; + +type ReservationReceipt record {| + *Links; + string id?; + string event; +|}; + +public type Subscribe record{ + Depth depth?; + Interval interval?; + MaxRateCount maxratecount?; + Name name; + Token token?; + string event; +}; + +public type Depth int?; +public type Token string?; + +public enum Name { + book, + ohlc, + openOrders, + ownTrades, + spread, + ticker, + trade +} + +public type MaxRateCount int?; +public type Interval int?; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pathParam(ReservationReceipt queryParam) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } + remote function onReservationReceipt(websocket:Caller caller, ReservationReceipt message) returns int { + return 5; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union.bal new file mode 100644 index 000000000..8b518bf30 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union.bal @@ -0,0 +1,51 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket ; + +type Link record {| + string rel; + Dog|Cat pet; +|}; + +type Dog record {| + int? id; + string name?; + string event; +|}; + +type Cat record {| + int id; + string eat?; + string event; +|}; + +listener websocket:Listener ep0 = new(443); + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on ep0 { + resource function get pet(Link payload) returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onDog(websocket:Caller caller, Dog message) returns Cat { + return {id:5,eat:"ate",event:"Cat"}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union_with_nullable.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union_with_nullable.bal new file mode 100644 index 000000000..07dbd4040 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union_with_nullable.bal @@ -0,0 +1,51 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string rel; + Dog|Cat? pet; +|}; + +type Dog record {| + int? id; + string name?; + string testing; +|}; + +type Cat record {| + int id; + string eat?; + string testing; +|}; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "testing"} +service /payloadV on ep0 { + resource function get pet(Link payload) returns websocket:Service|websocket:UpgradeError{ + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onDog(websocket:Caller caller, Dog message) returns Cat { + return {id:5,eat:"ate",testing:"testing"}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union_with_primitive.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union_with_primitive.bal new file mode 100644 index 000000000..981eb99f5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/union_with_primitive.bal @@ -0,0 +1,52 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +type Link record {| + string rel; + string|Cat pet; + string testing; +|}; + +type Dog record {| + int? id; + string name?; + string testing; +|}; + +type Cat record {| + int id; + string eat?; + string testing; +|}; + +listener websocket:Listener ep0 = new(443, config = {host: "petstore.swagger.io"}); + +@websocket:ServiceConfig{dispatcherKey: "testing"} +service /payloadV on ep0 { + resource function get pet(Link payload) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onDog(websocket:Caller caller, Dog message) returns Cat { + return {id:5,eat:"ate",testing:"testing"}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/with_readonly_keyword.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/with_readonly_keyword.bal new file mode 100644 index 000000000..b020d25b0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/record/with_readonly_keyword.bal @@ -0,0 +1,50 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +configurable int port = 8080; + +type Album readonly & record {| + readonly & string title; + string id; + string artist; + decimal price; + string event; +|}; + +type Testing string[]; + +table key(id) albums = table [ + {event: "Album",id: "1", title: "Blue Train", artist: "John Coltrane", price: 56.99}, + {event:"Album",id: "2", title: "Jeru", artist: "Gerry Mulligan", price: 17.99}, + {event:"Album",id: "3", title: "Sarah Vaughan and Clifford Brown", artist: "Sarah Vaughan", price: 39.99} + ]; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(port) { + resource function get albums/[string id]() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onAlbum(Album message, websocket:Caller caller) returns Album[] { + return albums.toArray(); + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario01_json.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario01_json.bal new file mode 100644 index 000000000..d4036b576 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario01_json.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get hello() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote isolated function onSubscribe(websocket:Caller caller, Subscribe data) returns json { + return "Hello World!"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario02_simple_name_reference_record.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario02_simple_name_reference_record.bal new file mode 100644 index 000000000..acc147b41 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario02_simple_name_reference_record.bal @@ -0,0 +1,43 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns SubscriptionStatus{ + return {id:1,type1: "subscriptionStatus"}; + } + +} + +public type Subscribe record{ + int id; + string event; +}; + +public type SubscriptionStatus record { + int id; + string type1; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario03_builtin_array.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario03_builtin_array.bal new file mode 100644 index 000000000..1f8b59499 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario03_builtin_array.bal @@ -0,0 +1,54 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns SubscriptionStatus[] { + SubscriptionStatus subscriptionStatus={id:1,type1: "subscriptionStatus"}; + SubscriptionStatus[] subscriptionArray=[subscriptionStatus]; + return subscriptionArray; + } + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message) returns string[] { + string[] st=["test"]; + return st; + } +} + +public type Subscribe record{ + int id; + string event; +}; + +public type UnSubscribe record{ + int id; + string event; +}; + +public type SubscriptionStatus record { + int id; + string type1; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario04_builtin.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario04_builtin.bal new file mode 100644 index 000000000..302e8c4a7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario04_builtin.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns string{ + return "subscribed"; + } +} + +public type Subscribe record{ + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario05_inline_record_builtin.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario05_inline_record_builtin.bal new file mode 100644 index 000000000..aad848e0a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario05_inline_record_builtin.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns record{| int id; string body;|} { + return {id:1, body: "ooo"}; + } +} + +public type Subscribe record { + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario06_xml.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario06_xml.bal new file mode 100644 index 000000000..fdd823bae --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario06_xml.bal @@ -0,0 +1,38 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns xml { + xml x1 = xml `The Lost World`; + return x1; + } +} + +public type Subscribe record { + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario07_inline_record_type_reference.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario07_inline_record_type_reference.bal new file mode 100644 index 000000000..43e4e5af3 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario07_inline_record_type_reference.bal @@ -0,0 +1,42 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns record{| int id; Test body;|} { + return {id:1, body: {id:0 ,name:""}}; + } +} + +public type Subscribe record { + int id; + string event; +}; + +type Test record { + int id ; + string name; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario08_float.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario08_float.bal new file mode 100644 index 000000000..e33e08c74 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario08_float.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns float { + return 1.0; + } +} + +public type Subscribe record { + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario09_decimal.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario09_decimal.bal new file mode 100644 index 000000000..f51d23e49 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario09_decimal.bal @@ -0,0 +1,37 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns decimal { + return 1.0; + } +} + +public type Subscribe record { + int id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario10_inline_record_type_inclusion.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario10_inline_record_type_inclusion.bal new file mode 100644 index 000000000..70c6380d8 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario10_inline_record_type_inclusion.bal @@ -0,0 +1,42 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns record {| *Test; string body;|} { + return {id:1, name: "",body: ""}; + } +} + +public type Subscribe record { + int id; + string event; +}; + +type Test record { + int id ; + string name; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario11_record_including_type_inclusion.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario11_record_including_type_inclusion.bal new file mode 100644 index 000000000..b0c97c9b8 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario11_record_including_type_inclusion.bal @@ -0,0 +1,155 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Represents Snowpeak location resource + resource function get locations() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns ReservationCreated|ReservationConflict { + Reservation reservation= { + reserveRooms: [ + { + id: "r1000", + count: 2 + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03" + }; + ReservationCreated created = createReservation(reservation); + return created; + } +} + +function createReservation(Reservation reservation) returns ReservationCreated { + return { + body: { + id: "re1000", + expiryDate: "2021-07-01", + lastUpdated: "2021-06-29T13:01:30Z", + reservation: { + reserveRooms: [ + { + id: "r1000", + count: 2 + } + ], + startDate: "2021-08-01", + endDate: "2021-08-03" + }, + links: [ + { + rel: "cancel", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [DELETE] + }, + { + rel: "edit", + href: "http://localhost:9090/reservation/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [PUT] + }, + { + rel: "payment", + href: "http://localhost:9090/payment/re1000", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"], + actions: [POST] + } + ] + } + }; +} + +public type Subscribe record{ + int id; + string event; +}; + +# Link details +type Link record {| + # linnk rel + string rel; + # link href + string href; + # mediaTypes + string[] mediaTypes?; + # actions + Action[] actions?; +|}; + +# Link details +type Links record {| + # Array links + Link[] links; +|}; + +enum Action { + GET, + POST, + PUT, + DELETE, + PATCH +} + +# Represents rooms be reserved +type ReserveRoom record {| + # Unique identification of the room + string id; + # Number of rooms + int count; +|}; + +# Represents a reservation of rooms +type Reservation record {| + # Rooms to be reserved + ReserveRoom[] reserveRooms; + # Start date in yyyy-mm-dd + string startDate; + # End date in yyyy-mm-dd + string endDate; +|}; + +# Represents a receipt for the reservation +type ReservationReceipt record {| + *Links; + # Unique identification + string id; + # Expiry date in yyyy-mm-dd + string expiryDate; + # Last updated time stamp + string lastUpdated; + # Reservation + Reservation reservation; +|}; + +type ReservationCreated record {| + + ReservationReceipt body; +|}; + +type ReservationConflict record {| + string body = "Error occurred while updating the reservation"; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario12_array_record.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario12_array_record.bal new file mode 100644 index 000000000..9fd4846de --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario12_array_record.bal @@ -0,0 +1,96 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + # Represents Snowpeak location resource + resource function get locations() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns Location[] { + Location[] locations=getLocation(); + return locations; + } +} + +function getLocation() returns Location[] { + return [ + { + name: "Alps", + id: "l1000", + address: "NC 29384, some place, switzerland", + links: [ + { + rel: "room", + href: "http://localhost:9090/snowpeak/locations/l1000/rooms", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"] + + } + ] + }, + { + name: "Pilatus", + id: "l2000", + address: "NC 29444, some place, switzerland", + links: [ + { + rel: "room", + href: "http://localhost:9090/snowpeak/locations/l2000/rooms", + mediaTypes: ["applicaion/vnd.snowpeak.resort+json"] + } + ] + } + ]; +} + +public type Subscribe record{ + int id; + string event; +}; + +# Link details +type Link record {| + # linnk rel + string rel; + # link href + string href; + # link mediatype + string[] mediaTypes?; +|}; + +# Link details +type Links record {| + # Array links + Link[] links; +|}; + +# Represents locations +type Location record {| + *Links; + # Name of the location + string name; + # Unique identification + string id; + # Address of the location + string address; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario13_multiple_builtin_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario13_multiple_builtin_return.bal new file mode 100644 index 000000000..6235d8c03 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario13_multiple_builtin_return.bal @@ -0,0 +1,61 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# A fake mountain resort +@websocket:ServiceConfig{dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .()returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe payment) returns int|string|boolean { + return 1; + } + + # Represents Snowpeak payment resource + # + # + id - Unique identification of payment + # + payment - Payment representation + # + return - `PaymentCreated` or `PaymentConflict` representation + remote function onPayment(websocket:Caller caller,Payment payment) returns int|string|map|map { + return "1"; + } +} + +public type Subscribe record {| + string body = "Error occurred while updating the payment"; + string event; +|}; + +# Reperesents payement for rooms +public type Payment record {| + # Name of the card holder + string cardholderName; + # Card number + int cardNumber; + # Expiration month of the card in mm + string expiryMonth; + # Expiaration year of the card in yyyy + string expiryYear; + # Event description + string event; +|}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario14_stream_string_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario14_stream_string_return.bal new file mode 100644 index 000000000..bcde0b442 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario14_stream_string_return.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80 ); + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on ep0{ + resource function get v1/[int id]/v2/[string name](int tag) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns stream { + string[] array=["hello"]; + return array.toStream(); + } +} + +public type Subscribe record{ + int id=5; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario15_multiple_stream_types_return.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario15_multiple_stream_types_return.bal new file mode 100644 index 000000000..8a836cf91 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/response/rs_scenario15_multiple_stream_types_return.bal @@ -0,0 +1,39 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80 ); + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on ep0{ + resource function get v1/[int id]/v2/[string name](int tag) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns stream|stream|stream { + string[] array=["hello"]; + return array.toStream(); + } +} + +public type Subscribe record{ + int id=5; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/security/secure_socket_present.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/security/secure_socket_present.bal new file mode 100644 index 000000000..f9d4a3518 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/security/secure_socket_present.bal @@ -0,0 +1,49 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +} ); + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /payloadV on ep0{ + resource function get v1/[int id]/v2/[string name](int tag) returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +public type Subscribe record { + int id; + string type1; +}; + +public type UnSubscribe record { + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/basic_service.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/basic_service.bal new file mode 100644 index 000000000..2bc0d3712 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/basic_service.bal @@ -0,0 +1,66 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + +@websocket:ServiceConfig {subProtocols: [],dispatcherKey: "type1"} +service /hello on ep0{ + resource function get payment/[string id]() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /hello02 on ep0,new websocket:Listener(8081){ + resource function get v1/[int id]/v2/[string name]/v3/[float value]/payment/[int data] (@http:Header {} string X\-Client) returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } +} + +service class FirstChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer { + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string { + return "testing"; + } +} + +public type Subscribe record { + int id; + string type1; +}; + +public type UnSubscribe record { + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/compiler_warning.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/compiler_warning.bal new file mode 100644 index 000000000..aba73119d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/compiler_warning.bal @@ -0,0 +1,49 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +@websocket:ServiceConfig {dispatcherKey: "event"} +service /payloadV on new websocket:Listener(9090) { + resource function get .() returns websocket:Service|websocket:Error { + return new WsService(); + } +} + +service class WsService { + *websocket:Service; + int yy = 0; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + self.yy = 10; + return 5; + } + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message) returns int { + self.yy = 20; + return 5; + } +} + +public type Subscribe record{ + int id; + string event; +}; + +public type UnSubscribe record{ + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/complex_base_path.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/complex_base_path.bal new file mode 100644 index 000000000..4e13237ab --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/complex_base_path.bal @@ -0,0 +1,67 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + + +@websocket:ServiceConfig {subProtocols: [],dispatcherKey: "type1"} +service /hello/foo/bar on ep0{ + resource function get payment/[string id]() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /hello02/bar/baz on ep0{ + resource function get v1/[int id]/v2/[string name]/v3/[float value]/payment/[int data] (@http:Header {} string X\-Client) returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } +} + +service class FirstChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer{ + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string{ + return "testing"; + } +} + +public type Subscribe record { + int id; + string type1; +}; + +public type UnSubscribe record { + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/escape_identifier.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/escape_identifier.bal new file mode 100644 index 000000000..17fcf5984 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/escape_identifier.bal @@ -0,0 +1,66 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /v1/abc\-hello on new websocket:Listener(9090) { + # Description + # + # + path\-param - Path Parameter Description + # + q\-paramter - Query Parameter Description + resource function get say\-hello/[string path\-param](string q\-paramter,string ชื่\u{E2D}) returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /'limit on new websocket:Listener(9091) { + # Query parameter + # + # + 'limit - QParameter Description + # + 'check - HParameter Description + resource function get steps/'from/date/[int 'join]/พิมพ์ชื่อ(@http:Header string 'check,string 'limit,string ชื่อ) returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } +} + +service class FirstChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer { + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string{ + return "testing"; + } +} + +public type Subscribe record { + int id; + string type1; +}; + +public type UnSubscribe record { + string id; + string event; +}; \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/kafka_service.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/kafka_service.bal new file mode 100644 index 000000000..4e39d69f0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/kafka_service.bal @@ -0,0 +1,42 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerinax/kafka; +import ballerina/log; + +public type Order readonly & record { + int orderId; + string productName; + decimal price; + boolean isValid; +}; + +listener kafka:Listener orderListener = new (kafka:DEFAULT_URL, { + groupId: "order-group-id", + topics: "order-topic" +}); + +service on orderListener { + + remote function onConsumerRecord(Order[] orders) returns error? { + // The set of orders received by the service are processed one by one. + check from Order 'order in orders + where 'order.isValid + do { + log:printInfo(string `Received valid order for ${'order.productName}`); + }; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/no_base_path_service.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/no_base_path_service.bal new file mode 100644 index 000000000..c24c86d21 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/no_base_path_service.bal @@ -0,0 +1,45 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(80,config = { secureSocket : { + key: { + certFile: "../resource/path/to/public.crt", + keyFile: "../resource/path/to/private.key" + } + } +}); + +@websocket:ServiceConfig {subProtocols: [],dispatcherKey: "type1"} +service / on ep0{ + resource function get payment/[string id]() returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +service class FirstChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +public type Subscribe record { + int id; + string type1; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/Ballerina.toml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/Ballerina.toml new file mode 100644 index 000000000..9926946ae --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/Ballerina.toml @@ -0,0 +1,4 @@ +[package] +org= "ballerina" +name= "asyncAPI" +version= "0.1.0" diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/record_request_service.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/record_request_service.bal new file mode 100644 index 000000000..507af1346 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/record_request_service.bal @@ -0,0 +1,38 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener ep0 = new(9090); + + +@websocket:ServiceConfig {subProtocols: [],dispatcherKey: "type1"} +service /payloadV on ep0{ + resource function get hi(int param) returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } + +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } + +} + diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/schema.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/schema.bal new file mode 100644 index 000000000..10b84087c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/project_bal/schema.bal @@ -0,0 +1,20 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +public type Subscribe record{ + int id; + string type1; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/rabbitmq_service.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/rabbitmq_service.bal new file mode 100644 index 000000000..37fe6cda4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/rabbitmq_service.bal @@ -0,0 +1,35 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/log; +import ballerinax/rabbitmq; + +public type Order record { + int orderId; + string productName; + decimal price; + boolean isValid; +}; + +// The consumer service listens to the "OrderQueue" queue. +service "query" on new rabbitmq:Listener(rabbitmq:DEFAULT_HOST, rabbitmq:DEFAULT_PORT) { + + remote function onMessage(Order 'order) returns error? { + if 'order.isValid { + log:printInfo(string `Received valid order for ${'order.productName}`); + } + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/websubhub_service.bal b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/websubhub_service.bal new file mode 100644 index 000000000..4f8f99c6c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/service/websubhub_service.bal @@ -0,0 +1,90 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/http; +import ballerina/websubhub; + +isolated string[] locations = []; +isolated map newsReceiversCache = {}; + +service /query on new websubhub:Listener(9000) { + + // Topic registration is not supported by this `hub` + remote function onRegisterTopic(websubhub:TopicRegistration msg) + returns websubhub:TopicRegistrationError { + return error websubhub:TopicRegistrationError( + "Topic registration not supported", statusCode = http:STATUS_NOT_IMPLEMENTED); + } + + // Topic deregistration is not supported by this `hub` + remote function onDeregisterTopic(websubhub:TopicDeregistration msg) returns websubhub:TopicDeregistrationError { + return error websubhub:TopicDeregistrationError( + "Topic deregistration not supported", statusCode = http:STATUS_NOT_IMPLEMENTED); + } + + // Content update is not supported by this `hub` + remote function onUpdateMessage(websubhub:UpdateMessage msg) returns websubhub:UpdateMessageError { + return error websubhub:UpdateMessageError( + "Content update not supported", statusCode = http:STATUS_NOT_IMPLEMENTED); + } + + remote function onSubscriptionValidation(readonly & websubhub:Subscription subscription) returns websubhub:SubscriptionDeniedError? { + string newsReceiverId = string `${subscription.hubTopic}-${subscription.hubCallback}`; + boolean newsReceiverAvailable = false; + lock { + newsReceiverAvailable = newsReceiversCache.hasKey(newsReceiverId); + } + if newsReceiverAvailable { + return error websubhub:SubscriptionDeniedError( + string `News receiver for location ${subscription.hubTopic} and endpoint ${subscription.hubCallback} already available`, + statusCode = http:STATUS_NOT_ACCEPTABLE + ); + } + } + + remote function onSubscriptionIntentVerified(readonly & websubhub:VerifiedSubscription subscription) returns error? { + lock { + if locations.indexOf(subscription.hubTopic) is () { + locations.push(subscription.hubTopic); + } + } + string newsReceiverId = string `${subscription.hubTopic}-${subscription.hubCallback}`; + lock { + newsReceiversCache[newsReceiverId] = subscription; + } + } + + remote function onUnsubscriptionValidation(readonly & websubhub:Unsubscription unsubscription) returns websubhub:UnsubscriptionDeniedError? { + string newsReceiverId = string `${unsubscription.hubTopic}-${unsubscription.hubCallback}`; + boolean newsReceiverNotAvailable = false; + lock { + newsReceiverNotAvailable = !newsReceiversCache.hasKey(newsReceiverId); + } + if newsReceiverNotAvailable { + return error websubhub:UnsubscriptionDeniedError( + string `News receiver for location ${unsubscription.hubTopic} and endpoint ${unsubscription.hubCallback} not available`, + statusCode = http:STATUS_NOT_ACCEPTABLE + ); + } + } + + remote function onUnsubscriptionIntentVerified(readonly & websubhub:VerifiedUnsubscription unsubscription) returns error? { + string newsReceiverId = string `${unsubscription.hubTopic}-${unsubscription.hubCallback}`; + lock { + _ = newsReceiversCache.removeIfHasKey(newsReceiverId); + } + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/additional/dispatcherStreamId_present.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/additional/dispatcherStreamId_present.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/additional/override_description_of_record.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/additional/override_description_of_record.yaml new file mode 100644 index 000000000..452aa15b2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/additional/override_description_of_record.yaml @@ -0,0 +1,58 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/Ticker' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + description: Override id description + format: int64 + event: + type: string + const: Subscribe + description: Override event description + description: Subscribe record description + Ticker: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + messages: + Ticker: + payload: + $ref: '#/components/schemas/Ticker' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/Ticker' + x-response-type: simple-rpc +x-dispatcherKey: event diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/compiler_warning.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/compiler_warning.yaml new file mode 100644 index 000000000..0b322cb9f --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/compiler_warning.yaml @@ -0,0 +1,69 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/UnSubscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + UnSubscribe: + type: object + required: + - id + - event + properties: + id: + type: string + event: + type: string + const: UnSubscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/escape_identifier.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/escape_identifier.yaml new file mode 100644 index 000000000..6eeaa678c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/escape_identifier.yaml @@ -0,0 +1,81 @@ +#openapi: 3.0.1 +#info: +# title: V1 Abc Hello +# version: 0.0.0 +#servers: +# - url: "{server}:{port}/v1/abc-hello" +# variables: +# server: +# default: http://localhost +# port: +# default: "9090" +#paths: +# /say-hello/{path-param}: +# get: +# summary: Description +# operationId: getSayHelloPathParam +# parameters: +# - name: path-param +# in: path +# description: Path Parameter Description +# required: true +# schema: +# type: string +# - name: q-paramter +# in: query +# required: true +# schema: +# type: string +# responses: +# "200": +# description: Ok +# content: +# application/json: +# schema: +# $ref: '#/components/schemas/Pet-Task' +# /v2/say-hello: +# post: +# summary: Description +# operationId: postV2SayHello +# parameters: +# - name: x-client +# in: header +# required: true +# schema: +# type: string +# requestBody: +# description: Body Parameter Description +# content: +# application/json: +# schema: +# $ref: '#/components/schemas/Pet-Task' +# responses: +# "202": +# description: Accepted +#components: +# schemas: +# Pet-Task: +# required: +# - pet-id +# type: object +# properties: +# pet-id: +# type: integer +# description: Field id Description +# format: int64 +# pet-types: +# type: array +# description: Field type Description +# items: +# type: string +# store: +# $ref: '#/components/schemas/Pet-Store' +# description: Description +# Pet-Store: +# required: +# - id +# type: object +# properties: +# id: +# type: integer +# format: int64 diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/escape_identifier_02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/escape_identifier_02.yaml new file mode 100644 index 000000000..5094e0495 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/escape_identifier_02.yaml @@ -0,0 +1,138 @@ +#openapi: 3.0.1 +#info: +# title: Limit +# version: 0.0.0 +#servers: +# - url: "{server}:{port}/limit" +# variables: +# server: +# default: http://localhost +# port: +# default: "9090" +#paths: +# /steps/from/date: +# get: +# summary: Query parameter +# operationId: getStepsFromDate +# parameters: +# - name: limit +# in: query +# description: QParameter Description +# required: true +# schema: +# type: string +# responses: +# "200": +# description: Ok +# content: +# text/plain: +# schema: +# type: string +# "500": +# description: Internal server error +# content: +# text/plain: +# schema: +# type: string +# /steps/{join}: +# get: +# summary: Header parameter +# operationId: getStepsJoin +# parameters: +# - name: join +# in: path +# required: true +# schema: +# type: integer +# format: int64 +# - name: limit +# in: header +# description: HParameter Description +# required: true +# schema: +# type: string +# responses: +# "200": +# description: Ok +# content: +# text/plain: +# schema: +# type: string +# "500": +# description: Internal server error +# content: +# text/plain: +# schema: +# type: string +# /steps: +# post: +# operationId: postSteps +# requestBody: +# content: +# application/json: +# schema: +# $ref: '#/components/schemas/Offset' +# responses: +# "201": +# description: Created +# content: +# text/plain: +# schema: +# type: string +# "500": +# description: Internal server error +# content: +# text/plain: +# schema: +# type: string +# /พิมพ์ชื่อ: +# get: +# operationId: getพิมพ์ชื่อ +# parameters: +# - name: ชื่อ +# in: query +# required: true +# schema: +# type: string +# responses: +# "202": +# description: Accepted +# put: +# operationId: putพิมพ์ชื่อ +# parameters: +# - name: ชื่อ +# in: query +# required: true +# schema: +# type: string +# responses: +# "202": +# description: Accepted +#components: +# schemas: +# Pet: +# required: +# - id +# - type +# type: object +# properties: +# type: +# type: string +# id: +# type: integer +# format: int64 +# Offset: +# required: +# - id +# - join +# - type +# type: object +# properties: +# type: +# type: string +# description: pet type +# id: +# type: integer +# format: int64 +# join: +# $ref: '#/components/schemas/Pet' diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/graphql_over_websocket.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/graphql_over_websocket.yaml new file mode 100644 index 000000000..a52820dca --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/graphql_over_websocket.yaml @@ -0,0 +1,160 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionAckMessage' + publish: + message: + oneOf: + - $ref: '#/components/messages/SubscribeMessage' + - $ref: '#/components/messages/PingMessage' + - $ref: '#/components/messages/PongMessage' + - $ref: '#/components/messages/ConnectionInitMessage' + - $ref: '#/components/messages/CompleteMessage' +components: + schemas: + SubscribeMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + const: SubscribeMessage + payload: + type: object + required: + - query + properties: + operationName: + type: string + x-nullable: true + query: + type: string + variables: + x-nullable: true + extensions: + x-nullable: true + NextMessage: + type: object + required: + - id + - type + - payload + properties: + id: + type: string + type: + type: string + payload: + additionalProperties: true + CompleteMessage: + type: object + required: + - id + - type + properties: + id: + type: string + type: + type: string + const: CompleteMessage + PingMessage: + type: object + required: + - type + properties: + type: + type: string + const: PingMessage + payload: + type: object + additionalProperties: true + PongMessage: + type: object + required: + - type + properties: + type: + type: string + const: PongMessage + payload: + type: object + additionalProperties: true + ConnectionInitMessage: + type: object + required: + - type + properties: + type: + type: string + const: ConnectionInitMessage + payload: + type: object + additionalProperties: true + ConnectionAckMessage: + type: object + required: + - type + properties: + type: + type: string + payload: + type: object + additionalProperties: true + messages: + NextMessage: + payload: + $ref: '#/components/schemas/NextMessage' + CompleteMessage: + payload: + $ref: '#/components/schemas/CompleteMessage' + SubscribeMessage: + payload: + $ref: '#/components/schemas/SubscribeMessage' + x-response: + oneOf: + - $ref: '#/components/messages/NextMessage' + - $ref: '#/components/messages/CompleteMessage' + x-response-type: server-streaming + PongMessage: + payload: + $ref: '#/components/schemas/PongMessage' + PingMessage: + payload: + $ref: '#/components/schemas/PingMessage' + x-response: + $ref: '#/components/messages/PongMessage' + x-response-type: simple-rpc + ConnectionAckMessage: + payload: + $ref: '#/components/schemas/ConnectionAckMessage' + ConnectionInitMessage: + payload: + $ref: '#/components/schemas/ConnectionInitMessage' + x-response: + $ref: '#/components/messages/ConnectionAckMessage' + x-response-type: simple-rpc +x-dispatcherKey: type diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_01.yaml new file mode 100644 index 000000000..09f35d58c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_01.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: Hello + version: 0.0.0 +servers: + development: + url: "{server}:{port}/hello" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /hi: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - type1 + properties: + id: + type: integer + format: int64 + type1: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_02.yaml new file mode 100644 index 000000000..55c909bb1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_02.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: / + version: 0.0.0 +servers: + development: + url: "{server}:{port}/" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /hi: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - type1 + properties: + id: + type: integer + format: int64 + type1: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_03.yaml new file mode 100644 index 000000000..9b33432e4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/advance/multiple_service_03.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: "" + version: 0.0.0 +servers: + development: + url: "{server}:{port}" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /hi: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - type1 + properties: + id: + type: integer + format: int64 + type1: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/alias/websocket.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/alias/websocket.yaml new file mode 100644 index 000000000..cbaed9fc4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/alias/websocket.yaml @@ -0,0 +1,56 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: string +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/path_param.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/path_param.yaml new file mode 100644 index 000000000..4037a6bc4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/path_param.yaml @@ -0,0 +1,54 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + description: Unique identification of location + schema: + type: string +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/query_param.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/query_param.yaml new file mode 100644 index 000000000..662d97018 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/query_param.yaml @@ -0,0 +1,66 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + description: Unique identification of location + schema: + type: string + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + startDate: + type: string + description: Start date in format yyyy-mm-dd + endDate: + type: string + description: End date in format yyyy-mm-dd +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/record.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/record.yaml new file mode 100644 index 000000000..2383c4976 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/record.yaml @@ -0,0 +1,95 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + oneOf: + - $ref: '#/components/messages/Reservation' + - $ref: '#/components/messages/ReserveRoom' + parameters: + id: + description: Unique identification of location + schema: + type: string +components: + schemas: + ReserveRoom: + type: object + required: + - id + - count + - event + properties: + id: + type: string + description: Unique identification of the room + count: + type: integer + description: Number of rooms + format: int64 + event: + type: string + const: ReserveRoom + description: Remote trigger field + description: Represents rooms be reserved + Reservation: + type: object + required: + - reserveRooms + - startDate + - endDate + - event + properties: + reserveRooms: + type: array + items: + $ref: '#/components/schemas/ReserveRoom' + description: Rooms to be reserved + startDate: + type: string + description: Start date in yyyy-mm-dd + endDate: + type: string + description: End date in yyyy-mm-dd + event: + type: string + const: Reservation + description: Remote trigger field + description: Represents a reservation of rooms + messages: + Reservation: + payload: + $ref: '#/components/schemas/Reservation' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + ReserveRoom: + payload: + $ref: '#/components/schemas/ReserveRoom' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/reference_scenario.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/reference_scenario.yaml new file mode 100644 index 000000000..94c3c301d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/reference_scenario.yaml @@ -0,0 +1,419 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + subscribe: + message: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: array + items: + $ref: '#/components/schemas/Location' + - $ref: '#/components/messages/Rooms' + - $ref: '#/components/messages/ReservationCreated' + - $ref: '#/components/messages/ReservationConflict' + - $ref: '#/components/messages/ReservationUpdated' + - $ref: '#/components/messages/PaymentCreated' + - $ref: '#/components/messages/PaymentConflict' + publish: + message: + oneOf: + - $ref: '#/components/messages/ReservationReceipt' + - $ref: '#/components/messages/Link' + - $ref: '#/components/messages/ReserveRoom' + - $ref: '#/components/messages/Location' + - $ref: '#/components/messages/Reservation' + - $ref: '#/components/messages/PaymentReceipt' + - $ref: '#/components/messages/Payment' +components: + schemas: + Link: + type: object + required: + - rel + - href + - event + properties: + rel: + type: string + href: + type: string + mediaTypes: + type: array + items: + type: string + actions: + type: array + items: + type: string + enum: + - GET + - POST + - PUT + - DELETE + - PATCH + event: + type: string + const: Link + description: Remote trigger field + Links: + type: object + required: + - links + properties: + links: + type: array + items: + $ref: '#/components/schemas/Link' + ReserveRoom: + type: object + required: + - id + - count + - event + properties: + id: + type: string + description: Unique identification of the room + count: + type: integer + description: Number of rooms + format: int64 + event: + type: string + const: ReserveRoom + description: Remote trigger field + description: Represents rooms be reserved + Reservation: + type: object + required: + - reserveRooms + - startDate + - endDate + - event + properties: + reserveRooms: + type: array + items: + $ref: '#/components/schemas/ReserveRoom' + description: Rooms to be reserved + startDate: + type: string + description: Start date in yyyy-mm-dd + endDate: + type: string + description: End date in yyyy-mm-dd + event: + type: string + const: Reservation + description: Remote trigger field + description: Represents a reservation of rooms + ReservationReceipt: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - id + - expiryDate + - lastUpdated + - reservation + - event + properties: + id: + type: string + description: Unique identification + expiryDate: + type: string + description: Expiry date in yyyy-mm-dd + lastUpdated: + type: string + description: Last updated time stamp + reservation: + $ref: '#/components/schemas/Reservation' + description: Reservation + event: + type: string + const: ReservationReceipt + description: Remote trigger field + description: Represents a receipt for the reservation + Location: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - name + - id + - address + - event + properties: + name: + type: string + description: Name of the location + id: + type: string + description: Unique identification + address: + type: string + description: Address of the location + event: + type: string + const: Location + description: Remote trigger field + description: Represents locations + Room: + type: object + required: + - id + - category + - capacity + - wifi + - status + - currency + - price + - count + properties: + id: + type: string + description: Unique identification + category: + type: string + enum: + - DELUXE + - KING + - FAMILY + description: Types of rooms available + capacity: + type: integer + description: Number of people that can be accommodate + format: int64 + wifi: + type: boolean + description: Availability of wifi + status: + type: string + enum: + - AVAILABLE + - RESERVED + - BOOKED + description: Availability of room + currency: + type: string + description: Currency used in price + price: + type: number + description: Cost for the room + format: double + count: + type: integer + description: Number of rooms as per the status + format: int64 + description: Represents resort room + Rooms: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - rooms + properties: + rooms: + type: array + items: + $ref: '#/components/schemas/Room' + description: Array of rooms + description: Represents a collection of resort rooms + ReservationCreated: + type: object + required: + - body + properties: + body: + $ref: '#/components/schemas/ReservationReceipt' + ReservationConflict: + type: object + required: + - body + properties: + body: + type: string + PaymentReceipt: + type: object + required: + - id + - total + - lastUpdated + - rooms + - event + properties: + id: + type: string + description: Unique identification + total: + type: number + description: Total amount paid + format: double + lastUpdated: + type: string + description: Last updated time stamp + rooms: + type: array + items: + $ref: '#/components/schemas/Room' + description: Booked rooms + event: + type: string + const: PaymentReceipt + description: Remote trigger field + description: Reperesents receipt for the payment + ReservationUpdated: + type: object + required: + - body + properties: + body: + $ref: '#/components/schemas/ReservationReceipt' + Payment: + type: object + required: + - cardholderName + - cardNumber + - expiryMonth + - expiryYear + - event + properties: + cardholderName: + type: string + description: Name of the card holder + cardNumber: + type: integer + description: Card number + format: int64 + expiryMonth: + type: string + description: Expiration month of the card in mm + expiryYear: + type: string + description: Expiaration year of the card in yyyy + event: + type: string + const: Payment + description: Remote trigger field + description: Reperesents payement for rooms + PaymentCreated: + type: object + required: + - body + properties: + body: + $ref: '#/components/schemas/PaymentReceipt' + PaymentConflict: + type: object + required: + - body + properties: + body: + type: string + messages: + ReservationReceipt: + payload: + $ref: '#/components/schemas/ReservationReceipt' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + Link: + payload: + $ref: '#/components/schemas/Link' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + ReserveRoom: + payload: + $ref: '#/components/schemas/ReserveRoom' + description: ReserveRoom with a request + description: Represents Snowpeak location resource + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/Location' + description: '`Location` representation' + x-response-type: simple-rpc + Rooms: + payload: + $ref: '#/components/schemas/Rooms' + Location: + payload: + $ref: '#/components/schemas/Location' + description: location message containing whole details + description: Reperesents Snowpeak room collection resource + x-response: + $ref: '#/components/messages/Rooms' + description: '`Rooms` representation' + x-response-type: simple-rpc + ReservationCreated: + payload: + $ref: '#/components/schemas/ReservationCreated' + ReservationConflict: + payload: + $ref: '#/components/schemas/ReservationConflict' + Reservation: + payload: + $ref: '#/components/schemas/Reservation' + description: Reservation representation + description: Represents Snowpeak reservation resource + x-response: + oneOf: + - $ref: '#/components/messages/ReservationCreated' + - $ref: '#/components/messages/ReservationConflict' + description: '`ReservationCreated` or ReservationConflict representation' + x-response-type: simple-rpc + ReservationUpdated: + payload: + $ref: '#/components/schemas/ReservationUpdated' + PaymentReceipt: + payload: + $ref: '#/components/schemas/PaymentReceipt' + description: Reservation representation + description: Represents Snowpeak reservation resource + x-response: + oneOf: + - $ref: '#/components/messages/ReservationUpdated' + - $ref: '#/components/messages/ReservationConflict' + description: '`ReservationCreated` or ReservationConflict representation' + x-response-type: simple-rpc + PaymentCreated: + payload: + $ref: '#/components/schemas/PaymentCreated' + PaymentConflict: + payload: + $ref: '#/components/schemas/PaymentConflict' + Payment: + payload: + $ref: '#/components/schemas/Payment' + description: Payment representation + description: Represents Snowpeak payment resource + x-response: + oneOf: + - $ref: '#/components/messages/PaymentCreated' + - $ref: '#/components/messages/PaymentConflict' + description: '`PaymentCreated` or `PaymentConflict` representation' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/request.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/request.yaml new file mode 100644 index 000000000..2383c4976 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/request.yaml @@ -0,0 +1,95 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + oneOf: + - $ref: '#/components/messages/Reservation' + - $ref: '#/components/messages/ReserveRoom' + parameters: + id: + description: Unique identification of location + schema: + type: string +components: + schemas: + ReserveRoom: + type: object + required: + - id + - count + - event + properties: + id: + type: string + description: Unique identification of the room + count: + type: integer + description: Number of rooms + format: int64 + event: + type: string + const: ReserveRoom + description: Remote trigger field + description: Represents rooms be reserved + Reservation: + type: object + required: + - reserveRooms + - startDate + - endDate + - event + properties: + reserveRooms: + type: array + items: + $ref: '#/components/schemas/ReserveRoom' + description: Rooms to be reserved + startDate: + type: string + description: Start date in yyyy-mm-dd + endDate: + type: string + description: End date in yyyy-mm-dd + event: + type: string + const: Reservation + description: Remote trigger field + description: Represents a reservation of rooms + messages: + Reservation: + payload: + $ref: '#/components/schemas/Reservation' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + ReserveRoom: + payload: + $ref: '#/components/schemas/ReserveRoom' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/resource_function.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/resource_function.yaml new file mode 100644 index 000000000..b0b7c2727 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/resource_function.yaml @@ -0,0 +1,49 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Represents Snowpeak location resource + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/typeInclusion.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/typeInclusion.yaml new file mode 100644 index 000000000..cc194310c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/apidoc/typeInclusion.yaml @@ -0,0 +1,107 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}/rooms: + description: Reperesents Snowpeak room collection resource + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + oneOf: + - $ref: '#/components/messages/ReservationReceipt' + - $ref: '#/components/messages/Link' + parameters: + id: + description: Unique identification of location + schema: + type: string +components: + schemas: + Link: + type: object + required: + - rel + - href + - event + properties: + rel: + type: string + description: link rel + href: + type: string + description: link href + mediaTypes: + type: array + items: + type: string + description: link mediatype + event: + type: string + const: Link + description: Remote trigger field + description: Link record + Links: + type: object + required: + - links + - linkid + properties: + links: + type: array + items: + $ref: '#/components/schemas/Link' + description: Array links + linkid: + type: integer + description: link id + format: int64 + description: Links array + ReservationReceipt: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - id + - event + properties: + id: + type: string + description: Reservation receipt id + event: + type: string + const: ReservationReceipt + description: Remote trigger field + description: ReservationReceipt details + messages: + ReservationReceipt: + payload: + $ref: '#/components/schemas/ReservationReceipt' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + Link: + payload: + $ref: '#/components/schemas/Link' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project01.yaml new file mode 100644 index 000000000..c53bd8b8e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project01.yaml @@ -0,0 +1,11 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 0.1.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + port: + default: "9090" diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project02.yaml new file mode 100644 index 000000000..92960da2c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project02.yaml @@ -0,0 +1,11 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 2.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + port: + default: "9090" diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project03.yaml new file mode 100644 index 000000000..d61275363 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project03.yaml @@ -0,0 +1,12 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 2.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + port: + default: "9090" + diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project04.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project04.yaml new file mode 100644 index 000000000..92960da2c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/asyncapi_info/project04.yaml @@ -0,0 +1,11 @@ +openapi: 3.0.1 +info: + title: PayloadV + version: 2.0.0 +servers: + - url: "{server}:{port}/payloadV" + variables: + server: + default: http://localhost + port: + default: "9090" diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/arrayTypeResponse.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/arrayTypeResponse.yaml new file mode 100644 index 000000000..8b7886c69 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/arrayTypeResponse.yaml @@ -0,0 +1,78 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.1.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "8080" +channels: + /: + description: List all products + subscribe: + message: + payload: + type: array + items: + $ref: '#/components/schemas/Product' + publish: + message: + $ref: '#/components/messages/Price' +components: + schemas: + Price: + type: object + required: + - currency + - amount + - event + properties: + currency: + type: string + enum: + - USD + - LKR + - SGD + - GBP + amount: + type: number + format: float + event: + type: string + const: Price + Product: + type: object + required: + - name + - description + - price + properties: + id: + type: string + name: + type: string + description: Name of the product + description: + type: string + description: Product description + price: + $ref: '#/components/schemas/Price' + description: Product price + description: Represents a product + messages: + Price: + payload: + $ref: '#/components/schemas/Price' + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/Product' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/readonly.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/readonly.yaml new file mode 100644 index 000000000..30f401d50 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/readonly.yaml @@ -0,0 +1,199 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.1.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - payload: + type: array + items: + $ref: '#/components/schemas/LiftRecord' + - $ref: '#/components/messages/LiftRecord' + - payload: + type: array + items: + $ref: '#/components/schemas/Subscribe' + publish: + message: + oneOf: + - $ref: '#/components/messages/Location' + - $ref: '#/components/messages/Rooms' + - $ref: '#/components/messages/ReserveRoom' +components: + schemas: + Location: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + const: Location + description: Represents location + LiftRecord: + type: object + required: + - id + - name + properties: + id: + type: string + name: + type: string + status: + type: string + enum: + - OPEN + - CLOSED + - HOLD + capacity: + type: integer + format: int64 + night: + type: boolean + elevationgain: + type: integer + format: int64 + Room: + type: object + required: + - id + - category + - capacity + - wifi + - status + - currency + - price + - count + properties: + id: + type: string + description: Unique identification + category: + type: string + enum: + - DELUXE + - KING + - FAMILY + description: Types of rooms available + capacity: + type: integer + description: Number of people that can be accommodate + format: int64 + wifi: + type: boolean + description: Availability of wifi + status: + type: string + enum: + - AVAILABLE + - RESERVED + - BOOKED + description: Availability of room + currency: + type: string + description: Currency used in price + price: + type: number + description: Cost for the room + format: double + count: + type: integer + description: Number of rooms as per the status + format: int64 + description: Represents resort room + Rooms: + type: object + required: + - rooms + - event + properties: + rooms: + type: array + items: + $ref: '#/components/schemas/Room' + description: Array of rooms + event: + type: string + const: Rooms + description: Represents a collection of resort rooms + ReserveRoom: + type: object + required: + - id + - count + - event + properties: + id: + type: string + description: Unique identification of the room + count: + type: integer + description: Number of rooms + format: int64 + event: + type: string + const: ReserveRoom + description: Represents rooms be reserved + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification of the room + event: + type: string + messages: + Location: + payload: + $ref: '#/components/schemas/Location' + description: A list of all `Lift`s + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/LiftRecord' + description: the lifts + x-response-type: simple-rpc + LiftRecord: + payload: + $ref: '#/components/schemas/LiftRecord' + Rooms: + payload: + $ref: '#/components/schemas/Rooms' + description: "Returns a `Lift` by `id` (id: \"panorama\")" + x-response: + $ref: '#/components/messages/LiftRecord' + description: the lift + x-required: false + x-response-type: simple-rpc + ReserveRoom: + payload: + $ref: '#/components/schemas/ReserveRoom' + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/Subscribe' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/snowpeak.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/snowpeak.yaml new file mode 100644 index 000000000..28e15c08b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/ballerina-project/service/snowpeak.yaml @@ -0,0 +1,369 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.1.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/Locations' + - $ref: '#/components/messages/Location' + - $ref: '#/components/messages/ReservationCreated' + - $ref: '#/components/messages/ReservationConflict' + - $ref: '#/components/messages/PaymentCreated' + - $ref: '#/components/messages/PaymentFault' + - payload: + type: integer + format: int64 + - payload: + type: string + - $ref: '#/components/messages/PaymentConflict' + - payload: + type: object + additionalProperties: {} + - $ref: '#/components/messages/PaymentSuccess' + publish: + message: + oneOf: + - $ref: '#/components/messages/Location' + - $ref: '#/components/messages/Rooms' + - $ref: '#/components/messages/Reservation' + - $ref: '#/components/messages/Payment' +components: + schemas: + Location: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + const: Location + description: Represents location + Locations: + type: object + required: + - locations + properties: + locations: + type: array + items: + $ref: '#/components/schemas/Location' + description: collection of locations + description: Represents a collection of locations + Room: + type: object + required: + - id + - category + - capacity + - wifi + - status + - currency + - price + - count + properties: + id: + type: string + description: Unique identification + category: + type: string + enum: + - DELUXE + - KING + - FAMILY + description: Types of rooms available + capacity: + type: integer + description: Number of people that can be accommodate + format: int64 + wifi: + type: boolean + description: Availability of wifi + status: + type: string + enum: + - AVAILABLE + - RESERVED + - BOOKED + description: Availability of room + currency: + type: string + description: Currency used in price + price: + type: number + description: Cost for the room + format: double + count: + type: integer + description: Number of rooms as per the status + format: int64 + description: Represents resort room + Rooms: + type: object + required: + - rooms + - event + properties: + rooms: + type: array + items: + $ref: '#/components/schemas/Room' + description: Array of rooms + event: + type: string + const: Rooms + description: Represents a collection of resort rooms + ReserveRoom: + type: object + required: + - id + - count + - event + properties: + id: + type: string + description: Unique identification of the room + count: + type: integer + description: Number of rooms + format: int64 + event: + type: string + description: Represents rooms be reserved + Reservation: + type: object + required: + - reserveRooms + - startDate + - endDate + - event + properties: + reserveRooms: + type: array + items: + $ref: '#/components/schemas/ReserveRoom' + description: Rooms to be reserved + startDate: + type: string + description: Start date in yyyy-mm-dd + endDate: + type: string + description: End date in yyyy-mm-dd + event: + type: string + const: Reservation + description: Represents a reservation of rooms + ReservationReceipt: + type: object + required: + - id + - expiryDate + - lastUpdated + - currency + - total + - reservation + properties: + id: + type: string + description: Unique identification + expiryDate: + type: string + description: Expiry date in yyyy-mm-dd + lastUpdated: + type: string + description: Last updated time stamp + currency: + type: string + description: Currency used in price + total: + type: number + description: Total payable + format: double + reservation: + $ref: '#/components/schemas/Reservation' + description: Reservation + description: Represents a receipt for the reservation + ReservationCreated: + type: object + required: + - body + properties: + body: + $ref: '#/components/schemas/ReservationReceipt' + ReservationConflict: + type: object + required: + - body + properties: + body: + type: string + Payment: + type: object + required: + - cardholderName + - cardNumber + - expiryMonth + - expiryYear + - event + properties: + cardholderName: + type: string + description: Name of the card holder + cardNumber: + type: integer + description: Card number + format: int64 + expiryMonth: + type: string + description: Expiration month of the card in mm + expiryYear: + type: string + description: Expiaration year of the card in yyyy + event: + type: string + const: Payment + description: Reperesents payement for rooms + PaymentReceipt: + type: object + required: + - id + - currency + - total + - lastUpdated + - rooms + properties: + id: + type: string + description: Unique identification + currency: + type: string + description: Currency used in price + total: + type: number + description: Total amount paid + format: double + lastUpdated: + type: string + description: Last updated time stamp + rooms: + type: array + items: + $ref: '#/components/schemas/Room' + description: Booked rooms + description: Reperesents receipt for the payment + PaymentCreated: + type: object + required: + - body + properties: + body: + $ref: '#/components/schemas/PaymentReceipt' + PaymentFault: + type: object + required: + - body + properties: + body: + type: string + PaymentConflict: + type: object + required: + - body + properties: + body: + type: string + PaymentSuccess: + type: object + required: + - body + properties: + body: + type: string + messages: + Locations: + payload: + $ref: '#/components/schemas/Locations' + Location: + payload: + $ref: '#/components/schemas/Location' + description: Represents Snowpeak location resource + x-response: + $ref: '#/components/messages/Locations' + description: '`Location` representation' + x-response-type: simple-rpc + Rooms: + payload: + $ref: '#/components/schemas/Rooms' + description: Rooms identification of message + description: Reperesents Snowpeak room collection resource + x-response: + $ref: '#/components/messages/Location' + description: '`Rooms` representation' + x-response-type: simple-rpc + ReservationCreated: + payload: + $ref: '#/components/schemas/ReservationCreated' + ReservationConflict: + payload: + $ref: '#/components/schemas/ReservationConflict' + Reservation: + payload: + $ref: '#/components/schemas/Reservation' + description: Reservation representation + description: Represents Snowpeak reservation resource + x-response: + oneOf: + - $ref: '#/components/messages/ReservationCreated' + - $ref: '#/components/messages/ReservationConflict' + description: '`ReservationCreated` or ReservationConflict representation' + x-response-type: simple-rpc + PaymentCreated: + payload: + $ref: '#/components/schemas/PaymentCreated' + PaymentFault: + payload: + $ref: '#/components/schemas/PaymentFault' + PaymentConflict: + payload: + $ref: '#/components/schemas/PaymentConflict' + PaymentSuccess: + payload: + $ref: '#/components/schemas/PaymentSuccess' + Payment: + payload: + $ref: '#/components/schemas/Payment' + description: Payment representation + description: Represents Snowpeak payment resource + x-response: + oneOf: + - $ref: '#/components/messages/PaymentCreated' + - $ref: '#/components/messages/PaymentFault' + - payload: + type: integer + format: int64 + - payload: + type: string + - $ref: '#/components/messages/PaymentConflict' + - payload: + type: object + additionalProperties: {} + - $ref: '#/components/messages/PaymentSuccess' + description: '`PaymentCreated` or `PaymentConflict` representation' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario01.yaml new file mode 100644 index 000000000..949c755ac --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario01.yaml @@ -0,0 +1,10 @@ +channels: + /: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario02.yaml new file mode 100644 index 000000000..5fc6a59f9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario02.yaml @@ -0,0 +1,27 @@ +channels: + /v1/{id}/v2/{name}: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + schema: + type: integer + format: int64 + name: + schema: + type: string + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + tag: + type: integer + format: int64 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario03.yaml new file mode 100644 index 000000000..7f679872e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario03.yaml @@ -0,0 +1,15 @@ +channels: + /v1/{id}: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + schema: + type: integer + format: int64 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario04.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario04.yaml new file mode 100644 index 000000000..cf274ad95 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/channels/channel_scenario04.yaml @@ -0,0 +1,18 @@ +channels: + /v1/{id}/v2/{name}: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + schema: + type: integer + format: int64 + name: + schema: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum.yaml new file mode 100644 index 000000000..4c44fd6fb --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum.yaml @@ -0,0 +1,119 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /payment/{id}: + description: resource function description + subscribe: + message: + oneOf: + - $ref: '#/components/messages/Test' + - payload: + type: integer + format: int64 + publish: + message: + oneOf: + - $ref: '#/components/messages/Link' + - $ref: '#/components/messages/Order' + parameters: + id: + description: test id description + schema: + type: string +components: + schemas: + Link: + type: object + required: + - rel + - fdf + - s8jk + properties: + rel: + type: string + description: rel description + actions: + type: string + enum: + - GET + - POST + - PUT + - DELETE + - PATCH + description: actions description + fdf: + type: integer + description: fdf description + format: int64 + s8jk: + type: string + const: Link + description: Try override description + description: this is for testing + Test: + type: object + required: + - check2 + - hello + - s8jk + properties: + check2: + type: string + hello: + type: string + s8jk: + type: string + Order: + type: object + required: + - rel + - s8jk + properties: + rel: + type: string + actions: + type: string + enum: + - full + - Half "Portion" + - custom size + s8jk: + type: string + const: Order + messages: + Test: + payload: + $ref: '#/components/schemas/Test' + Link: + payload: + $ref: '#/components/schemas/Link' + description: remote above link description + description: Testing remote description + x-response: + $ref: '#/components/messages/Test' + description: remote return description + x-response-type: simple-rpc + Order: + payload: + $ref: '#/components/schemas/Order' + description: order above link description + description: Order remote description + x-response: + payload: + type: integer + format: int64 + description: order return description + x-response-type: simple-rpc +x-dispatcherKey: s8jk \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum_array.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum_array.yaml new file mode 100644 index 000000000..517ec9257 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum_array.yaml @@ -0,0 +1,73 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /reservation/{id}: + description: reservation channel description + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Link' + parameters: + id: + description: id description + schema: + type: string +components: + schemas: + Link: + type: object + required: + - rel + - href + - event + properties: + rel: + type: string + href: + type: string + mediaTypes: + type: array + items: + type: string + actions: + type: array + items: + type: string + enum: + - GET + - POST + - PUT + - DELETE + - PATCH + event: + type: string + const: Link + messages: + Link: + payload: + $ref: '#/components/schemas/Link' + description: link description + description: onlink remote function description + x-response: + payload: + type: integer + format: int64 + description: Return int description + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum_with_constant_value.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum_with_constant_value.yaml new file mode 100644 index 000000000..4241660f5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/enum_with_constant_value.yaml @@ -0,0 +1,64 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /reservation/{id}: + description: reservation channel description + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Link' + parameters: + id: + description: id description + schema: + type: string +components: + schemas: + Link: + type: object + required: + - rel + - event + properties: + rel: + type: string + actions: + type: string + enum: + - get + - post + - put + - delete + - patch + event: + type: string + const: Link + messages: + Link: + payload: + $ref: '#/components/schemas/Link' + description: link description + description: onlink remote function description + x-response: + payload: + type: integer + format: int64 + description: Return int description + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/map.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/map.yaml new file mode 100644 index 000000000..0cebf5335 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/map.yaml @@ -0,0 +1,131 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations/{id}: + subscribe: + message: + payload: + type: object + additionalProperties: + type: string + publish: + message: + $ref: '#/components/messages/Location' + parameters: + id: + schema: + type: string +components: + schemas: + Subscribe: + type: object + required: + - fdf + - bb + - type1 + properties: + id: + type: integer + format: int64 + event: + type: string + fdf: + type: string + bb: + type: string + type1: + type: string + Link: + type: object + required: + - href + properties: + rel: + type: string + href: + type: string + types: + type: array + items: + $ref: '#/components/schemas/Subscribe' + methods: + type: array + items: + type: string + Location: + type: object + required: + - _links + - name + - id + - addressCode + - event + properties: + _links: + type: object + additionalProperties: + $ref: '#/components/schemas/Link' + name: + type: object + additionalProperties: + type: string + id: + type: object + additionalProperties: + type: integer + format: int64 + addressCode: + type: object + additionalProperties: + type: number + format: float + item: + type: object + additionalProperties: true + mapArray: + type: object + additionalProperties: + type: array + items: + type: string + mapMap: + type: object + additionalProperties: + type: object + additionalProperties: true + arrayItemMap: + type: array + items: + type: object + additionalProperties: + type: string + event: + type: string + const: Location + messages: + Location: + payload: + $ref: '#/components/schemas/Location' + description: remote above link description + description: Testing remote description + x-response: + payload: + type: object + additionalProperties: + type: string + description: remote return description + x-required: false + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/nullable_type_def.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/nullable_type_def.yaml new file mode 100644 index 000000000..76fb5fcd2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/nullable_type_def.yaml @@ -0,0 +1,97 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /pathParam: + description: Resource function description + subscribe: + message: + $ref: '#/components/messages/Action' + publish: + message: + $ref: '#/components/messages/Link' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + id: + type: integer + description: Query parameter id + format: int64 +components: + schemas: + Books: + type: object + additionalProperties: + type: string + x-nullable: true + Rels: + type: array + items: + type: string + x-nullable: true + Action: + type: string + x-nullable: true + Count: + type: number + format: double + x-nullable: true + Salary: + oneOf: + - type: integer + format: int64 + - type: number + format: float + - type: number + format: double + x-nullable: true + Link: + type: object + required: + - books + - rels + - actions + - salary + - action + properties: + books: + $ref: '#/components/schemas/Books' + rels: + $ref: '#/components/schemas/Rels' + actions: + $ref: '#/components/schemas/Action' + count: + $ref: '#/components/schemas/Count' + salary: + $ref: '#/components/schemas/Salary' + action: + type: string + const: Link + messages: + Action: + payload: + $ref: '#/components/schemas/Action' + Link: + payload: + $ref: '#/components/schemas/Link' + description: message description + description: Remote link description + x-response: + $ref: '#/components/messages/Action' + description: this is return description + x-response-type: simple-rpc +x-dispatcherKey: action \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/tuple_type.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/tuple_type.yaml new file mode 100644 index 000000000..8578d27bb --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/tuple_type.yaml @@ -0,0 +1,107 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/User' + publish: + message: + $ref: '#/components/messages/Tuple' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + required: + - id + - age + - event + properties: + id: + type: integer + format: int64 + age: + type: integer + format: int64 + event: + type: string + ReturnTypes: + type: array + items: + oneOf: + - type: integer + format: int64 + - type: number + format: double + Tuple: + type: object + required: + - address + - id + - unionTuple + - tuples + - event + properties: + address: + type: array + items: + oneOf: + - type: integer + format: int64 + - type: string + - type: number + format: double + - type: number + format: float + - $ref: '#/components/schemas/User' + id: + type: integer + format: int64 + unionTuple: + type: array + items: + oneOf: + - type: string + - type: number + format: double + x-nullable: true + tuples: + $ref: '#/components/schemas/ReturnTypes' + x-nullable: true + event: + type: string + const: Tuple + messages: + User: + payload: + $ref: '#/components/schemas/User' + Tuple: + payload: + $ref: '#/components/schemas/Tuple' + description: Tuple message description + description: Remote tuple description + x-response: + $ref: '#/components/messages/User' + description: this is User return description + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/type_def.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/type_def.yaml new file mode 100644 index 000000000..4903cc13a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/data_type/type_def.yaml @@ -0,0 +1,112 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /reservation/{id}: + description: Represents resource function description + subscribe: + message: + $ref: '#/components/messages/PriceMap' + publish: + message: + $ref: '#/components/messages/Type' + parameters: + id: + description: id path param description + schema: + $ref: '#/components/schemas/PetId' +components: + schemas: + PetId: + type: integer + Books: + type: object + additionalProperties: + type: string + Rels: + type: array + items: + type: string + Action: + type: string + description: Adding doc + Count: + type: integer + PriceMap: + type: object + required: + - price + - salary + - tuple + properties: + price: + type: integer + format: int64 + salary: + type: number + format: double + tuple: + type: string + Price: + oneOf: + - type: number + format: float + - $ref: '#/components/schemas/PriceMap' + Salary: + oneOf: + - type: integer + format: int64 + - type: number + format: float + - type: number + format: double + Type: + type: object + required: + - rels + - count + - price + - salary + - tuple + properties: + books: + $ref: '#/components/schemas/Books' + rels: + $ref: '#/components/schemas/Rels' + actions: + $ref: '#/components/schemas/Action' + count: + $ref: '#/components/schemas/Count' + x-nullable: true + price: + $ref: '#/components/schemas/Price' + salary: + $ref: '#/components/schemas/Salary' + tuple: + type: string + const: Type + messages: + PriceMap: + payload: + $ref: '#/components/schemas/PriceMap' + Type: + payload: + $ref: '#/components/schemas/Type' + description: Type message description + description: Remote tuple description + x-response: + $ref: '#/components/messages/PriceMap' + description: this is User return description + x-response-type: simple-rpc +x-dispatcherKey: tuple \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario01.yaml new file mode 100644 index 000000000..0b8206971 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario01.yaml @@ -0,0 +1,18 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + X-Client: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario02.yaml new file mode 100644 index 000000000..8a385a4c4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario02.yaml @@ -0,0 +1,18 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + x-item: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario03.yaml new file mode 100644 index 000000000..6a6096870 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario03.yaml @@ -0,0 +1,18 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario04.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario04.yaml new file mode 100644 index 000000000..078f637a2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario04.yaml @@ -0,0 +1,22 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: string + x-request-client: + type: string + extensions: + x-nullable: true \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario05.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario05.yaml new file mode 100644 index 000000000..52de1453d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario05.yaml @@ -0,0 +1,20 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: string + extensions: + x-nullable: true \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario06.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario06.yaml new file mode 100644 index 000000000..18f11fc92 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario06.yaml @@ -0,0 +1,15 @@ +paths: + /ping: + get: + operationId: getPing + parameters: + - name: headerValue + in: header + required: true + schema: + type: string + nullable: true + responses: + "200": + description: Ok +components: {} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario07.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario07.yaml new file mode 100644 index 000000000..e5895b491 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario07.yaml @@ -0,0 +1,19 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + x-client: + type: string + default: header1 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario08.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario08.yaml new file mode 100644 index 000000000..84a28b447 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario08.yaml @@ -0,0 +1,21 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + x-client: + type: string + extensions: + x-nullable: true + default: header1 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario09.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario09.yaml new file mode 100644 index 000000000..1ce13b96d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario09.yaml @@ -0,0 +1,15 @@ +paths: + /ping: + get: + operationId: getPing + parameters: + - name: headerValue + in: header + schema: + type: string + nullable: true + default: default + responses: + "200": + description: Ok +components: {} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario10.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario10.yaml new file mode 100644 index 000000000..6a6096870 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario10.yaml @@ -0,0 +1,18 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario11.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario11.yaml new file mode 100644 index 000000000..cfc17e13a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario11.yaml @@ -0,0 +1,21 @@ +default: "9090" +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: array + items: + type: boolean \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario12.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario12.yaml new file mode 100644 index 000000000..0ff1a7f21 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario12.yaml @@ -0,0 +1,21 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + x-client: + type: array + items: + type: boolean + default: "[true, false]" \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario13.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario13.yaml new file mode 100644 index 000000000..a7e826917 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario13.yaml @@ -0,0 +1,20 @@ +channels: + /v1: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + XClient: + type: array + items: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario14.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario14.yaml new file mode 100644 index 000000000..a492b8fe2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario14.yaml @@ -0,0 +1,20 @@ +channels: + /v1: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + x-item: + type: array + items: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario15.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario15.yaml new file mode 100644 index 000000000..6a6096870 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/headers/header_scenario15.yaml @@ -0,0 +1,18 @@ +channels: + /ping: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + headers: + type: object + properties: + headerValue: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario01.yaml new file mode 100644 index 000000000..c102ca941 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario01.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://www.asyncapi.com + port: + default: "80" +channels: + /pathParam: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario02.yaml new file mode 100644 index 000000000..eaeb8db7d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario02.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /pathParam: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario03.yaml new file mode 100644 index 000000000..1a11e5ab6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario03.yaml @@ -0,0 +1,54 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + enum: + - ws://www.asyncapi.com + - ws://localhost + default: ws://localhost + port: + enum: + - "443" + - "80" + default: "80" +channels: + /pathParam: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario04.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario04.yaml new file mode 100644 index 000000000..1a11e5ab6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario04.yaml @@ -0,0 +1,54 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + enum: + - ws://www.asyncapi.com + - ws://localhost + default: ws://localhost + port: + enum: + - "443" + - "80" + default: "80" +channels: + /pathParam: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario05.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario05.yaml new file mode 100644 index 000000000..d27858dfe --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/listener_scenario05.yaml @@ -0,0 +1,54 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + enum: + - ws://www.asyncapi.com + - ws://localhost + default: ws://localhost + port: + enum: + - "443" + - "8080" + default: "8080" +channels: + /pathParam: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/with_check_key_word.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/with_check_key_word.yaml new file mode 100644 index 000000000..a57661344 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/listeners/with_check_key_word.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "8080" +channels: + /: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_error_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_error_return.yaml new file mode 100644 index 000000000..744f0464e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_error_return.yaml @@ -0,0 +1,40 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + publish: + message: + $ref: '#/components/messages/Location' +components: + schemas: + Location: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + const: Location + description: Represents location + messages: + Location: + payload: + $ref: '#/components/schemas/Location' + description: Represents Snowpeak location resource +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_int_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_int_return.yaml new file mode 100644 index 000000000..5cf198463 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_int_return.yaml @@ -0,0 +1,52 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Location' +components: + schemas: + Location: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + const: Location + description: Represents location + messages: + Location: + payload: + $ref: '#/components/schemas/Location' + description: Represents Snowpeak location resource + x-response: + payload: + type: integer + format: int64 + description: '`Location` representation' + x-required: false + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_multiple_type_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_multiple_type_return.yaml new file mode 100644 index 000000000..bfdc39aad --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_multiple_type_return.yaml @@ -0,0 +1,82 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: object + additionalProperties: {} + - $ref: '#/components/messages/LocationReturn' + publish: + message: + $ref: '#/components/messages/Location' +components: + schemas: + Location: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + const: Location + description: Represents location + LocationReturn: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + description: Represents location + messages: + LocationReturn: + payload: + $ref: '#/components/schemas/LocationReturn' + Location: + payload: + $ref: '#/components/schemas/Location' + description: Represents Snowpeak location resource + x-response: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: object + additionalProperties: {} + - $ref: '#/components/messages/LocationReturn' + description: '`Location` representation' + extensions: + x-required: false + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_two_union_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_two_union_return.yaml new file mode 100644 index 000000000..dc3fbbf32 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/optional/optional_two_union_return.yaml @@ -0,0 +1,59 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + publish: + message: + $ref: '#/components/messages/Location' +components: + schemas: + Location: + type: object + required: + - id + - event + properties: + id: + type: string + description: Unique identification + event: + type: string + const: Location + description: Represents location + messages: + Location: + payload: + $ref: '#/components/schemas/Location' + description: Represents Snowpeak location resource + x-response: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + description: '`Location` representation' + extensions: + x-required: false + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario01.yaml new file mode 100644 index 000000000..49548787d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario01.yaml @@ -0,0 +1,19 @@ +channels: + /: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + offset: + type: integer + format: int64 + diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario02.yaml new file mode 100644 index 000000000..9bd3b5f80 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario02.yaml @@ -0,0 +1,21 @@ +channels: + /: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + offset: + type: integer + format: int64 + extensions: + x-nullable: true + diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario03.yaml new file mode 100644 index 000000000..4034c590a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario03.yaml @@ -0,0 +1,19 @@ +channels: + /: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + tags: + type: array + items: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario04.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario04.yaml new file mode 100644 index 000000000..99d235709 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario04.yaml @@ -0,0 +1,22 @@ +channels: + /: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + pet: + type: array + items: + type: integer + format: int64 + extensions: + x-nullable: true \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario05.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario05.yaml new file mode 100644 index 000000000..b7462fef8 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario05.yaml @@ -0,0 +1,18 @@ +#paths: +# /pets: +# get: +# summary: Mock example +# operationId: getPets +# parameters: +# - name: pet +# in: query +# description: Mock optional query parameter Description +# required: true +# schema: +# type: number +# format: double +# nullable: true +# responses: +# "200": +# description: Ok +#components: {} diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario06.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario06.yaml new file mode 100644 index 000000000..8db1844b5 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario06.yaml @@ -0,0 +1,92 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /hello: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + pet: + type: string + default: hello + offsetInteger: + type: integer + format: int64 + default: "5" + offsetDecimal: + type: number + format: double + default: "100.08" + offsetBoolean: + type: boolean + default: "true" + offsetFloat: + type: number + format: float + default: "100.08" + offsetIntegerArray: + type: array + items: + type: integer + format: int64 + default: "[2, 1, 3, 4]" + offset: + type: integer + format: int64 + extensions: + x-nullable: true + default: null + offsetNullableJson: + type: object + additionalProperties: {} + extensions: + x-nullable: true + default: "{x: {id: sss}}" + offsetJson: + type: object + additionalProperties: {} + default: "{x: {id: sss}}" +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: string + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario07.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario07.yaml new file mode 100644 index 000000000..2db95c82b --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario07.yaml @@ -0,0 +1,22 @@ +channels: + /hello: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + test: + type: array + items: + type: integer + format: int64 + extensions: + x-nullable: true \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario08.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario08.yaml new file mode 100644 index 000000000..372791c5e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/query/query_scenario08.yaml @@ -0,0 +1,24 @@ +channels: + /hello: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + definedY: + type: string + prefixDefinedY: + type: string + offset: + type: integer + format: int64 + limitV: + type: string \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/array_record.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/array_record.yaml new file mode 100644 index 000000000..cf8e696f4 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/array_record.yaml @@ -0,0 +1,63 @@ +#openapi: 3.0.1 +#info: +# title: PayloadV +# version: 0.0.0 +#servers: +# - url: "{server}:{port}/payloadV" +# variables: +# server: +# default: http://localhost +# port: +# default: "9090" +#paths: +# /locations: +# get: +# summary: Represents Snowpeak location resource +# operationId: getLocations +# responses: +# "200": +# description: Ok +# content: +# application/json: +# schema: +# type: array +# items: +# $ref: '#/components/schemas/Location' +#components: +# schemas: +# Links: +# type: object +# properties: +# links: +# type: array +# items: +# $ref: '#/components/schemas/Link' +# Link: +# type: object +# properties: +# mediaTypes: +# type: array +# description: link mediatype +# items: +# type: string +# rel: +# type: string +# description: linnk rel +# href: +# type: string +# description: link href +# description: Link details +# Location: +# allOf: +# - $ref: '#/components/schemas/Links' +# - type: object +# properties: +# address: +# type: string +# description: Address of the location +# name: +# type: string +# description: Name of the location +# id: +# type: string +# description: Unique identification diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/cyclic_record.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/cyclic_record.yaml new file mode 100644 index 000000000..7ef0a4144 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/cyclic_record.yaml @@ -0,0 +1,207 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /albums/{id}: + subscribe: + message: + oneOf: + - $ref: '#/components/messages/ResponseError' + - $ref: '#/components/messages/ResponseError02' + - $ref: '#/components/messages/ResponseError03' + - $ref: '#/components/messages/ResponseError04' + - $ref: '#/components/messages/ResponseError05' + - $ref: '#/components/messages/ResponseError06' + - $ref: '#/components/messages/ResponseError07' + publish: + message: + oneOf: + - $ref: '#/components/messages/ResponseError' + - $ref: '#/components/messages/ResponseError02' + - $ref: '#/components/messages/ResponseError03' + - $ref: '#/components/messages/ResponseError04' + - $ref: '#/components/messages/ResponseError05' + - $ref: '#/components/messages/ResponseError06' + - $ref: '#/components/messages/ResponseError07' + parameters: + id: + schema: + type: string +components: + schemas: + ResponseError: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + $ref: '#/components/schemas/ResponseError' + event: + type: string + const: ResponseError + ResponseError02: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + oneOf: + - $ref: '#/components/schemas/ResponseError02' + - type: string + event: + type: string + const: ResponseError02 + ResponseError03: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + type: array + items: + $ref: '#/components/schemas/ResponseError03' + event: + type: string + const: ResponseError03 + ResponseError04: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + type: array + items: + type: array + items: + $ref: '#/components/schemas/ResponseError04' + event: + type: string + const: ResponseError04 + ResponseError05: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + $ref: '#/components/schemas/ResponseError05' + x-nullable: true + event: + type: string + const: ResponseError05 + ResponseError06: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + type: array + items: + $ref: '#/components/schemas/ResponseError06' + x-nullable: true + event: + type: string + const: ResponseError06 + ResponseError07: + type: object + required: + - id + - resError + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + resError: + type: array + items: + $ref: '#/components/schemas/ResponseError07' + x-nullable: true + event: + type: string + const: ResponseError07 + messages: + ResponseError: + payload: + $ref: '#/components/schemas/ResponseError' + x-response: + $ref: '#/components/messages/ResponseError' + x-response-type: simple-rpc + ResponseError02: + payload: + $ref: '#/components/schemas/ResponseError02' + x-response: + $ref: '#/components/messages/ResponseError02' + x-response-type: simple-rpc + ResponseError03: + payload: + $ref: '#/components/schemas/ResponseError03' + x-response: + $ref: '#/components/messages/ResponseError03' + x-response-type: simple-rpc + ResponseError04: + payload: + $ref: '#/components/schemas/ResponseError04' + x-response: + $ref: '#/components/messages/ResponseError04' + x-response-type: simple-rpc + ResponseError05: + payload: + $ref: '#/components/schemas/ResponseError05' + x-response: + $ref: '#/components/messages/ResponseError05' + x-response-type: simple-rpc + ResponseError06: + payload: + $ref: '#/components/schemas/ResponseError06' + x-response: + $ref: '#/components/messages/ResponseError06' + x-response-type: simple-rpc + ResponseError07: + payload: + $ref: '#/components/schemas/ResponseError07' + x-response: + $ref: '#/components/messages/ResponseError07' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable01.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable01.yaml new file mode 100644 index 000000000..8cb03ec9d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable01.yaml @@ -0,0 +1,58 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pet: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Link' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + $ref: '#/components/schemas/Link' +components: + schemas: + Link: + type: object + required: + - href + - event + properties: + rel: + type: string + x-nullable: true + href: + type: string + event: + type: string + const: Link + messages: + Link: + payload: + $ref: '#/components/schemas/Link' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable02.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable02.yaml new file mode 100644 index 000000000..41f004644 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable02.yaml @@ -0,0 +1,65 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pet: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Link' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + type: integer + format: int64 +components: + schemas: + Link: + type: object + required: + - rel + - href + - event + properties: + rel: + type: string + href: + type: string + x-nullable: true + mediaTypes: + type: array + items: + type: string + x-nullable: true + event: + type: string + const: Link + messages: + Link: + payload: + $ref: '#/components/schemas/Link' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable03.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable03.yaml new file mode 100644 index 000000000..7771e6dee --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/nullable03.yaml @@ -0,0 +1,70 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pet: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Link' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + $ref: '#/components/schemas/Link' +components: + schemas: + Pet: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + name: + type: string + x-nullable: true + Link: + type: object + required: + - rel + - event + properties: + rel: + type: string + x-nullable: true + pet: + $ref: '#/components/schemas/Pet' + x-nullable: true + event: + type: string + const: Link + messages: + Link: + payload: + $ref: '#/components/schemas/Link' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/optional.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/optional.yaml new file mode 100644 index 000000000..4c9960cb9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/optional.yaml @@ -0,0 +1,73 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pet: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Link' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + queryParam: + $ref: '#/components/schemas/Pet' +components: + schemas: + Pet: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + name: + type: string + Link: + type: object + required: + - href + - test + properties: + rel: + type: string + href: + type: string + mediaTypes: + type: array + items: + type: string + pet: + $ref: '#/components/schemas/Pet' + test: + type: string + const: Link + messages: + Link: + payload: + $ref: '#/components/schemas/Link' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: test \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/typeInclusion.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/typeInclusion.yaml new file mode 100644 index 000000000..9195829f2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/typeInclusion.yaml @@ -0,0 +1,129 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pathParam: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/ReservationReceipt' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + queryParam: + $ref: '#/components/schemas/ReservationReceipt' +components: + schemas: + Link: + type: object + properties: + rel: + type: string + href: + type: string + mediaTypes: + type: array + items: + type: string + Links: + type: object + properties: + links: + type: array + items: + $ref: '#/components/schemas/Link' + linkid: + type: integer + format: int64 + ReservationReceipt: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - event + properties: + id: + type: string + event: + type: string + const: ReservationReceipt + Depth: + type: integer + format: int64 + x-nullable: true + Interval: + type: integer + format: int64 + x-nullable: true + MaxRateCount: + type: integer + format: int64 + x-nullable: true + Token: + type: string + x-nullable: true + Subscribe: + type: object + required: + - name + - event + properties: + depth: + $ref: '#/components/schemas/Depth' + interval: + $ref: '#/components/schemas/Interval' + maxratecount: + $ref: '#/components/schemas/MaxRateCount' + name: + type: string + enum: + - book + - ohlc + - openOrders + - ownTrades + - spread + - ticker + - trade + token: + $ref: '#/components/schemas/Token' + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc + ReservationReceipt: + payload: + $ref: '#/components/schemas/ReservationReceipt' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union.yaml new file mode 100644 index 000000000..38909b0d7 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union.yaml @@ -0,0 +1,83 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "443" +channels: + /pet: + subscribe: + message: + $ref: '#/components/messages/Cat' + publish: + message: + $ref: '#/components/messages/Dog' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + $ref: '#/components/schemas/Link' +components: + schemas: + Dog: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + x-nullable: true + name: + type: string + event: + type: string + const: Dog + Cat: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + eat: + type: string + event: + type: string + Link: + type: object + required: + - rel + - pet + properties: + rel: + type: string + pet: + oneOf: + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Cat' + messages: + Cat: + payload: + $ref: '#/components/schemas/Cat' + Dog: + payload: + $ref: '#/components/schemas/Dog' + x-response: + $ref: '#/components/messages/Cat' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union_with_nullable.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union_with_nullable.yaml new file mode 100644 index 000000000..ede4eb050 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union_with_nullable.yaml @@ -0,0 +1,84 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pet: + subscribe: + message: + $ref: '#/components/messages/Cat' + publish: + message: + $ref: '#/components/messages/Dog' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + $ref: '#/components/schemas/Link' +components: + schemas: + Dog: + type: object + required: + - id + - testing + properties: + id: + type: integer + format: int64 + x-nullable: true + name: + type: string + testing: + type: string + const: Dog + Cat: + type: object + required: + - id + - testing + properties: + id: + type: integer + format: int64 + eat: + type: string + testing: + type: string + Link: + type: object + required: + - rel + - pet + properties: + rel: + type: string + pet: + oneOf: + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Cat' + x-nullable: true + messages: + Cat: + payload: + $ref: '#/components/schemas/Cat' + Dog: + payload: + $ref: '#/components/schemas/Dog' + x-response: + $ref: '#/components/messages/Cat' + x-response-type: simple-rpc +x-dispatcherKey: testing \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union_with_primitive.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union_with_primitive.yaml new file mode 100644 index 000000000..26b1c83d9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/union_with_primitive.yaml @@ -0,0 +1,86 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://petstore.swagger.io + port: + default: "443" +channels: + /pet: + subscribe: + message: + $ref: '#/components/messages/Cat' + publish: + message: + $ref: '#/components/messages/Dog' + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + payload: + $ref: '#/components/schemas/Link' +components: + schemas: + Cat: + type: object + required: + - id + - testing + properties: + id: + type: integer + format: int64 + eat: + type: string + testing: + type: string + Link: + type: object + required: + - rel + - pet + - testing + properties: + rel: + type: string + pet: + oneOf: + - type: string + - $ref: '#/components/schemas/Cat' + testing: + type: string + Dog: + type: object + required: + - id + - testing + properties: + id: + type: integer + format: int64 + x-nullable: true + name: + type: string + testing: + type: string + const: Dog + messages: + Cat: + payload: + $ref: '#/components/schemas/Cat' + Dog: + payload: + $ref: '#/components/schemas/Dog' + x-response: + $ref: '#/components/messages/Cat' + x-response-type: simple-rpc +x-dispatcherKey: testing \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/with_read_only_keyword.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/with_read_only_keyword.yaml new file mode 100644 index 000000000..1ff632a02 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/record/with_read_only_keyword.yaml @@ -0,0 +1,63 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: port +channels: + /albums/{id}: + subscribe: + message: + payload: + type: array + items: + $ref: '#/components/schemas/Album' + publish: + message: + $ref: '#/components/messages/Album' + parameters: + id: + schema: + type: string +components: + schemas: + Album: + type: object + required: + - title + - id + - artist + - price + - event + properties: + title: + type: string + id: + type: string + artist: + type: string + price: + type: number + format: double + event: + type: string + const: Album + messages: + Album: + payload: + $ref: '#/components/schemas/Album' + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/Album' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario01_json.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario01_json.yaml new file mode 100644 index 000000000..6992bd82d --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario01_json.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /hello: + subscribe: + message: + payload: + type: object + additionalProperties: {} + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: object + additionalProperties: {} + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario02_simple_name_reference_record.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario02_simple_name_reference_record.yaml new file mode 100644 index 000000000..6e491fd88 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario02_simple_name_reference_record.yaml @@ -0,0 +1,58 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + $ref: '#/components/messages/SubscriptionStatus' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + SubscriptionStatus: + type: object + required: + - id + - type1 + properties: + id: + type: integer + format: int64 + type1: + type: string + messages: + SubscriptionStatus: + payload: + $ref: '#/components/schemas/SubscriptionStatus' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/SubscriptionStatus' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario03_builtin_array.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario03_builtin_array.yaml new file mode 100644 index 000000000..132ce019e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario03_builtin_array.yaml @@ -0,0 +1,89 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - payload: + type: array + items: + $ref: '#/components/schemas/SubscriptionStatus' + - payload: + type: array + items: + type: string + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/UnSubscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + SubscriptionStatus: + type: object + required: + - id + - type1 + properties: + id: + type: integer + format: int64 + type1: + type: string + UnSubscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: UnSubscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/SubscriptionStatus' + x-response-type: simple-rpc + UnSubscribe: + payload: + $ref: '#/components/schemas/UnSubscribe' + x-response: + payload: + type: array + items: + type: string + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario04_builtin.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario04_builtin.yaml new file mode 100644 index 000000000..2b893d6e1 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario04_builtin.yaml @@ -0,0 +1,46 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: string + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario05_inline_record_builtin.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario05_inline_record_builtin.yaml new file mode 100644 index 000000000..a84abd351 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario05_inline_record_builtin.yaml @@ -0,0 +1,58 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: object + properties: + id: + type: integer + format: int64 + body: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: object + properties: + id: + type: integer + format: int64 + body: + type: string + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario06_xml.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario06_xml.yaml new file mode 100644 index 000000000..589c7452e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario06_xml.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: object + additionalProperties: {} + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: object + additionalProperties: {} + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario07_inline_record_type_reference.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario07_inline_record_type_reference.yaml new file mode 100644 index 000000000..a6c31e6c6 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario07_inline_record_type_reference.yaml @@ -0,0 +1,69 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: object + properties: + id: + type: integer + format: int64 + body: + $ref: '#/components/schemas/Test' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + Test: + type: object + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: object + properties: + id: + type: integer + format: int64 + body: + $ref: '#/components/schemas/Test' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario08_float.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario08_float.yaml new file mode 100644 index 000000000..3ea96ad6a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario08_float.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: number + format: float + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: number + format: float + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario09_decimal.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario09_decimal.yaml new file mode 100644 index 000000000..7a4e12e95 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario09_decimal.yaml @@ -0,0 +1,48 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + payload: + type: number + format: double + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: number + format: double + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario10_inline_record_type_inclusion.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario10_inline_record_type_inclusion.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario11_record_including_type_inclusion.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario11_record_including_type_inclusion.yaml new file mode 100644 index 000000000..04130cfb2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario11_record_including_type_inclusion.yaml @@ -0,0 +1,165 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Represents Snowpeak location resource + subscribe: + message: + oneOf: + - $ref: '#/components/messages/ReservationCreated' + - $ref: '#/components/messages/ReservationConflict' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + Link: + type: object + required: + - rel + - href + properties: + rel: + type: string + description: linnk rel + href: + type: string + description: link href + mediaTypes: + type: array + items: + type: string + description: mediaTypes + actions: + type: array + items: + type: string + enum: + - GET + - POST + - PUT + - DELETE + - PATCH + description: actions + description: Link details + Links: + type: object + required: + - links + properties: + links: + type: array + items: + $ref: '#/components/schemas/Link' + description: Array links + description: Link details + ReserveRoom: + type: object + required: + - id + - count + properties: + id: + type: string + description: Unique identification of the room + count: + type: integer + description: Number of rooms + format: int64 + description: Represents rooms be reserved + Reservation: + type: object + required: + - reserveRooms + - startDate + - endDate + properties: + reserveRooms: + type: array + items: + $ref: '#/components/schemas/ReserveRoom' + description: Rooms to be reserved + startDate: + type: string + description: Start date in yyyy-mm-dd + endDate: + type: string + description: End date in yyyy-mm-dd + description: Represents a reservation of rooms + ReservationReceipt: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - id + - expiryDate + - lastUpdated + - reservation + properties: + id: + type: string + description: Unique identification + expiryDate: + type: string + description: Expiry date in yyyy-mm-dd + lastUpdated: + type: string + description: Last updated time stamp + reservation: + $ref: '#/components/schemas/Reservation' + description: Reservation + description: Represents a receipt for the reservation + ReservationCreated: + type: object + required: + - body + properties: + body: + $ref: '#/components/schemas/ReservationReceipt' + ReservationConflict: + type: object + required: + - body + properties: + body: + type: string + messages: + ReservationCreated: + payload: + $ref: '#/components/schemas/ReservationCreated' + ReservationConflict: + payload: + $ref: '#/components/schemas/ReservationConflict' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + oneOf: + - $ref: '#/components/messages/ReservationCreated' + - $ref: '#/components/messages/ReservationConflict' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario12_array_record.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario12_array_record.yaml new file mode 100644 index 000000000..8ac739c19 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario12_array_record.yaml @@ -0,0 +1,99 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /locations: + description: Represents Snowpeak location resource + subscribe: + message: + payload: + type: array + items: + $ref: '#/components/schemas/Location' + publish: + message: + $ref: '#/components/messages/Subscribe' +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + Link: + type: object + required: + - rel + - href + properties: + rel: + type: string + description: linnk rel + href: + type: string + description: link href + mediaTypes: + type: array + items: + type: string + description: link mediatype + description: Link details + Links: + type: object + required: + - links + properties: + links: + type: array + items: + $ref: '#/components/schemas/Link' + description: Array links + description: Link details + Location: + allOf: + - $ref: '#/components/schemas/Links' + - type: object + required: + - name + - id + - address + properties: + name: + type: string + description: Name of the location + id: + type: string + description: Unique identification + address: + type: string + description: Address of the location + description: Represents locations + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: array + items: + $ref: '#/components/schemas/Location' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario13_multiple_builtin_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario13_multiple_builtin_return.yaml new file mode 100644 index 000000000..0e99c09f9 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario13_multiple_builtin_return.yaml @@ -0,0 +1,114 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9090" +channels: + /: + subscribe: + message: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: boolean + - payload: + type: object + additionalProperties: {} + - payload: + type: object + additionalProperties: + type: string + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/Payment' +components: + schemas: + Subscribe: + type: object + required: + - body + - event + properties: + body: + type: string + event: + type: string + const: Subscribe + Payment: + type: object + required: + - cardholderName + - cardNumber + - expiryMonth + - expiryYear + - event + properties: + cardholderName: + type: string + description: Name of the card holder + cardNumber: + type: integer + description: Card number + format: int64 + expiryMonth: + type: string + description: Expiration month of the card in mm + expiryYear: + type: string + description: Expiaration year of the card in yyyy + event: + type: string + const: Payment + description: Event description + description: Reperesents payement for rooms + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: boolean + x-response-type: simple-rpc + Payment: + payload: + $ref: '#/components/schemas/Payment' + description: Payment representation + description: Represents Snowpeak payment resource + x-response: + oneOf: + - payload: + type: integer + format: int64 + - payload: + type: string + - payload: + type: object + additionalProperties: {} + - payload: + type: object + additionalProperties: + type: string + description: '`PaymentCreated` or `PaymentConflict` representation' + x-response-type: simple-rpc +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario14_stream_string_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario14_stream_string_return.yaml new file mode 100644 index 000000000..288de4b70 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario14_stream_string_return.yaml @@ -0,0 +1,63 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /v1/{id}/v2/{name}: + subscribe: + message: + payload: + type: string + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + schema: + type: integer + format: int64 + name: + schema: + type: string + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + tag: + type: integer + format: int64 +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: string + x-response-type: server-streaming +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario15_multiple_stream_types_return.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario15_multiple_stream_types_return.yaml new file mode 100644 index 000000000..88f9cb8f0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/response/rs_scenario15_multiple_stream_types_return.yaml @@ -0,0 +1,75 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "80" +channels: + /v1/{id}/v2/{name}: + subscribe: + message: + oneOf: + - payload: + type: string + - payload: + type: integer + format: int64 + - payload: + type: boolean + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + schema: + type: integer + format: int64 + name: + schema: + type: string + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + tag: + type: integer + format: int64 +components: + schemas: + Subscribe: + type: object + required: + - id + - event + properties: + id: + type: integer + format: int64 + event: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + oneOf: + - payload: + type: string + - payload: + type: integer + format: int64 + - payload: + type: boolean + x-response-type: server-streaming +x-dispatcherKey: event \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/security/secure_socket_present.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/security/secure_socket_present.yaml new file mode 100644 index 000000000..25024967c --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/security/secure_socket_present.yaml @@ -0,0 +1,65 @@ +asyncapi: 2.5.0 +info: + title: PayloadV + version: 0.0.0 +servers: + development: + url: "{server}:{port}/payloadV" + protocol: ws + protocolVersion: "13" + variables: + server: + default: wss://localhost + port: + default: "80" +channels: + /v1/{id}/v2/{name}: + subscribe: + message: + payload: + type: integer + format: int64 + publish: + message: + $ref: '#/components/messages/Subscribe' + parameters: + id: + schema: + type: integer + format: int64 + name: + schema: + type: string + bindings: + ws: + bindingVersion: 0.1.0 + query: + type: object + properties: + tag: + type: integer + format: int64 +components: + schemas: + Subscribe: + type: object + required: + - id + - type1 + properties: + id: + type: integer + format: int64 + type1: + type: string + const: Subscribe + messages: + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + payload: + type: integer + format: int64 + x-response-type: simple-rpc +x-dispatcherKey: type1 \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/service/multiple_service_empty_file.yaml b/asyncapi-cli/src/test/resources/websockets/ballerina-to-asyncapi/yaml_outputs/service/multiple_service_empty_file.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/check_websocket_serviceConfig_annotation.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/check_websocket_serviceConfig_annotation.bal new file mode 100644 index 000000000..cd37f6565 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/check_websocket_serviceConfig_annotation.bal @@ -0,0 +1,42 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + int event; +}; + +public type Ticker record { + int id; +}; + +service / on helloEp { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_not_present_in_annotation.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_not_present_in_annotation.bal new file mode 100644 index 000000000..b368b1c25 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_not_present_in_annotation.bal @@ -0,0 +1,43 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +@websocket:ServiceConfig{subProtocols: []} +service / on helloEp { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_not_present_in_record.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_not_present_in_record.bal new file mode 100644 index 000000000..5800f5549 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_not_present_in_record.bal @@ -0,0 +1,42 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; +}; + +public type Ticker record { + int id; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_string_type_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_string_type_check.bal new file mode 100644 index 000000000..290cf95b0 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/dispatcherKey_field_string_type_check.bal @@ -0,0 +1,43 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + int event; +}; + +public type Ticker record{ + int id; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/empty_dispatcherKey_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/empty_dispatcherKey_check.bal new file mode 100644 index 000000000..284746343 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/empty_dispatcherKey_check.bal @@ -0,0 +1,43 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event; +}; + +public type Ticker record { + int id; +}; + +@websocket:ServiceConfig{dispatcherKey: ""} +service / on helloEp { + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/no_service_class_present.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/no_service_class_present.bal new file mode 100644 index 000000000..fe00c65ce --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/no_service_class_present.bal @@ -0,0 +1,43 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns int { + return 1; + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/nullable_dispatcherKey_present.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/nullable_dispatcherKey_present.bal new file mode 100644 index 000000000..6cda3f10a --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/nullable_dispatcherKey_present.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string? event; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onBinaryMessage_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onBinaryMessage_check.bal new file mode 100644 index 000000000..c744d35ac --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onBinaryMessage_check.bal @@ -0,0 +1,48 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker{ + return {id:1}; + } + + remote function onBinaryMessage(websocket:Caller caller, byte[] data) returns websocket:Error? { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onClose_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onClose_check.bal new file mode 100644 index 000000000..5d71a6528 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onClose_check.bal @@ -0,0 +1,46 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onClose(websocket:Caller caller, int statusCode) { + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onError_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onError_check.bal new file mode 100644 index 000000000..c046c3aac --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onError_check.bal @@ -0,0 +1,48 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onError(websocket:Caller caller, websocket:Error err) returns websocket:Error? { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onIdleTimeOut_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onIdleTimeOut_check.bal new file mode 100644 index 000000000..da8deda58 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onIdleTimeOut_check.bal @@ -0,0 +1,48 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onIdleTimeout(websocket:Caller caller) { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onMessage_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onMessage_check.bal new file mode 100644 index 000000000..8d8e25bff --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onMessage_check.bal @@ -0,0 +1,48 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onMessage(websocket:Caller caller, string data) returns websocket:Error? { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onOpen_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onOpen_check.bal new file mode 100644 index 000000000..eac1b07d2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onOpen_check.bal @@ -0,0 +1,48 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onOpen(websocket:Caller caller) returns websocket:Error? { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onPing_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onPing_check.bal new file mode 100644 index 000000000..251e394ca --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onPing_check.bal @@ -0,0 +1,58 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event; +}; + +public type Ticker record{ + int id; +}; + +public type Ping record { + string event; + Reqid reqid?; +}; + +public type Pong record { + string event?; + Reqid reqid?; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onPing(websocket:Caller caller, byte[] data) returns byte[] { + return [4,5]; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onPong_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onPong_check.bal new file mode 100644 index 000000000..244be7a6e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onPong_check.bal @@ -0,0 +1,58 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event; +}; + +public type Ticker record { + int id; +}; + +public type Ping record { + string event; + Reqid reqid?; +}; + +public type Pong record { + string event?; + Reqid reqid?; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onPong(websocket:Caller caller, byte[] data) { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onTextMessage_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onTextMessage_check.bal new file mode 100644 index 000000000..2f4e86807 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/onTextMessage_check.bal @@ -0,0 +1,48 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } + + remote function onTextMessage(websocket:Caller caller, string text) returns websocket:Error? { + + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/optional_dispatcherKey_present.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/optional_dispatcherKey_present.bal new file mode 100644 index 000000000..6d6ddaf92 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/optional_dispatcherKey_present.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event?; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/path_param_dash_contain.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/path_param_dash_contain.bal new file mode 100644 index 000000000..e4159b524 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/path_param_dash_contain.bal @@ -0,0 +1,66 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import ballerina/http; + +@websocket:ServiceConfig {dispatcherKey: "type1"} +service /v1/abc\-hello on new websocket:Listener(9090) { + # Description + # + # + path\-param - Path Parameter Description + # + q\-paramter - Query Parameter Description + resource function get say\-hello/[string path\-param](string q\-paramter,string ชื่\u{E2D}) returns websocket:Service|websocket:UpgradeError { + return new FirstChatServer(); + } +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /'limit on new websocket:Listener(9091) { + # Query parameter + # + # + 'limit - QParameter Description + # + 'check - HParameter Description + resource function get steps/'from/date/[int 'join]/พิมพ์ชื่อ(@http:Header string 'check,string 'limit,string ชื่อ) returns websocket:Service|websocket:UpgradeError { + return new SecondChatServer(); + } + +} +service class FirstChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, Subscribe message) returns int { + return 5; + } +} + +service class SecondChatServer{ + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller, UnSubscribe message)returns string { + return "testing"; + } +} + +public type Subscribe record { + int id; + string type1; +}; + +public type UnSubscribe record { + string id; + string event; +}; diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remoteFunction_Function_signature_not_match.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remoteFunction_Function_signature_not_match.bal new file mode 100644 index 000000000..3b0c1741e --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remoteFunction_Function_signature_not_match.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event?; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onUnSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remoteFunction_name_start.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remoteFunction_name_start.bal new file mode 100644 index 000000000..1f4bf73f2 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remoteFunction_name_start.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record{ + int id; + string event?; +}; + +public type Ticker record{ + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function Subscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remotefunction_camelCase_not_present.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remotefunction_camelCase_not_present.bal new file mode 100644 index 000000000..74ecbd711 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/remotefunction_camelCase_not_present.bal @@ -0,0 +1,44 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe record { + int id; + string event?; +}; + +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer { + *websocket:Service; + + remote function onsubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/request_type_record_check.bal b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/request_type_record_check.bal new file mode 100644 index 000000000..f216de5dc --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/cmd/ballerina-to-asyncapi/exceptions/request_type_record_check.bal @@ -0,0 +1,40 @@ +// Copyright (c) 2023 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +listener websocket:Listener helloEp = new (80); + +public type Subscribe int; +public type Ticker record { + int id; +}; + +public type Reqid int?; +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on helloEp { + resource function get .() returns websocket:Service| websocket:UpgradeError { + return new ChatServer(); + } +} + +service class ChatServer{ + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller,Subscribe message) returns Ticker { + return {id:1}; + } +} diff --git a/asyncapi-cli/src/test/resources/websockets/out/.gitignore b/asyncapi-cli/src/test/resources/websockets/out/.gitignore new file mode 100644 index 000000000..b8eb8c376 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/out/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!placeholder.txt \ No newline at end of file diff --git a/asyncapi-cli/src/test/resources/websockets/out/placeholder.txt b/asyncapi-cli/src/test/resources/websockets/out/placeholder.txt new file mode 100644 index 000000000..1a58b2f90 --- /dev/null +++ b/asyncapi-cli/src/test/resources/websockets/out/placeholder.txt @@ -0,0 +1 @@ +This is a placeholder file to push the directory. \ No newline at end of file diff --git a/build.gradle b/build.gradle index 9943afcfd..b0c0da2dd 100644 --- a/build.gradle +++ b/build.gradle @@ -3,11 +3,11 @@ import org.apache.tools.ant.taskdefs.condition.Os plugins { id "base" id 'maven-publish' - id "com.github.spotbugs" version "5.0.14" - id "com.github.johnrengelman.shadow" version "8.1.1" - id "de.undercouch.download" version "5.4.0" - id "net.researchgate.release" version "2.8.0" - id 'org.javamodularity.moduleplugin' version '1.7.0' apply false + id "com.github.spotbugs" version "${githubSpotbugsVersion}" + id "com.github.johnrengelman.shadow" version "${githubJohnrengelmanShadowVersion}" + id "de.undercouch.download" version "${underCouchDownloadVersion}" + id "net.researchgate.release" version "${researchgateReleaseVersion}" + id 'org.javamodularity.moduleplugin' version "${javaModularityVersion}" apply false } apply plugin: 'java' @@ -79,10 +79,10 @@ allprojects { subprojects { apply plugin: 'java' dependencies { - implementation 'io.apicurio:apicurio-data-models:1.1.15' - implementation 'org.apache.logging.log4j:log4j-core:2.14.1' + implementation "io.apicurio:apicurio-data-models:${apiCurioVersion}" + implementation "org.apache.logging.log4j:log4j-core:${log4jVersion}" implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${jacksonDataformatYamlVersion}" - implementation 'commons-io:commons-io:2.11.0' + implementation "commons-io:commons-io:${commonsIoVersion}" implementation "org.ballerinalang:ballerina-lang:${ballerinaLangVersion}" implementation "org.ballerinalang:ballerina-parser:${ballerinaLangVersion}" implementation "org.ballerinalang:ballerina-cli:${ballerinaLangVersion}" @@ -90,8 +90,8 @@ subprojects { implementation "org.ballerinalang:ballerina-tools-api:${ballerinaLangVersion}" implementation "io.ballerina.stdlib:http-native:${stdlibHttpVersion}" implementation "org.ballerinalang:language-server-commons:${ballerinaLangVersion}" - implementation "info.picocli:picocli:4.0.1" - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' + implementation "info.picocli:picocli:${picocliVersion}" + testImplementation "org.junit.jupiter:junit-jupiter-api:5.6.0" testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' testImplementation "org.testng:testng:${testngVersion}" } @@ -153,7 +153,7 @@ shadowJar { dependencies { include(dependency('com.github.jknack:handlebars')) include(dependency('org.antlr:antlr4:4.5')) - include(dependency('io.apicurio:apicurio-data-models:1.1.15')) + include(dependency("io.apicurio:apicurio-data-models:${apiCurioVersion}")) include(dependency('com.atlassian.commonmark:commonmark')) include(dependency('com.atlassian.commonmark:commonmark-ext-gfm-tables')) exclude('META-INF/*.SF') diff --git a/config/checkstyle/build/checkstyle.xml b/config/checkstyle/build/checkstyle.xml new file mode 100644 index 000000000..31c845105 --- /dev/null +++ b/config/checkstyle/build/checkstyle.xml @@ -0,0 +1,402 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/build/suppressions.xml b/config/checkstyle/build/suppressions.xml new file mode 100644 index 000000000..69bff56c1 --- /dev/null +++ b/config/checkstyle/build/suppressions.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/spec/spec.md b/docs/spec/spec.md new file mode 100644 index 000000000..cfd7d12e0 --- /dev/null +++ b/docs/spec/spec.md @@ -0,0 +1,259 @@ +# Specification: Ballerina AsyncAPI for WebSockets + +_Authors_: @thushalya @hasathcharu +_Reviewers_: @bhashinee @shafreenAnfar +_Created_: 2024/06/27 +_Updated_: 2024/06/28 +_Edition_: Swan Lake + +## Introduction + +This is the specification for the AsyncApi Tools of [Ballerina language](https://ballerina.io/), which supports generation of client API from an AsyncAPI specification for WebSocket protocols. This also allows the generation of an AsyncAPI specification for a given Ballerina service running on WebSockets. + +The AsyncAPI Tools specification has evolved and may continue to evolve in the future. The released versions of the specification can be found under the relevant GitHub tag. + +If you have any feedback or suggestions about the tool, start a discussion via a [GitHub issue](https://github.com/ballerina-platform/ballerina-library/issues) or in the [Discord server](https://discord.gg/ballerinalang). Based on the outcome of the discussion, the specification and implementation can be updated. Community feedback is always welcome. Any accepted proposal, which affects the specification is stored under `/docs/proposals`. Proposals under discussion can be found with the label `type/proposal` in GitHub. + +The conforming implementation of the specification is released and included in the distribution. Any deviation from the specification is considered a bug. + +## Contents + +1. [Overview](#1-overview) +2. [Generating the specification](#2-generating-the-specification) +3. [Generating the Ballerina client](#3-generating-the-ballerina-client) + +## 1. Overview +This specification elaborates on the `AsyncAPI CLI Tool` commands. + +## 2. Generating the specification + +This tool enables the generation of an AsyncAPI specification for a given service running on WebSockets. It can be done by running the following command. + +```bash +bal asyncapi --protocol ws -i --o +``` + +| Command Parameter | Description | Mandatory | Default Value | +|:-----------------:|:----------------------------------------------------------------:|:---------:|:-------------------:| +| --protocol | indicates the protocol used | No | http | +| <-i, --input> | specifies the entry file of the service | Yes | - | +| <-o, --output> | specifies the output directory | No | | +| --service | specifies the specific service to generate the specification for | No | | +| --json | specifies whether to generate in `json` format | No | false | + + +The command generates an AsyncAPI specification for the given service running on WebSockets. The generated specification will be saved in the specified output directory. If the output directory is not specified, the specification will be saved in the current directory. + +Behaviour of the command, +- The tool generates a specification only if the provided input file is a Ballerina file. +- Users should provide an input file which does not contain any compilation errors. +- If executed within a Ballerina project, the tool will generate the specification for all the services in the project, including all the types defined within modules. +- If there are multiple services in the project, the tool will generate a separate specification for each service, by equating each service to a channel. +- The generated specification is of version 2.5.0. + +### How the AsyncAPI specification is generated + +#### Info Object + +```yaml +info: + title: + version: +``` + +The `service_name` is derived from the name of the service. If the name of the service is `/`, the `service_name` will be derived from the file name. Otherwise, the `service_name` will be the name of the service. + +The `package_version` is derived from the version defined in the `Ballerina.toml` file, if available. If the version is not defined in the `Ballerina.toml` file, the `package_version` will be `0.0.0`. + +#### Server Object + +```yaml +servers: + "development": + url: "{server}:{port}/" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9092" +``` + +The server name will be `development` by default, which can be changed by the user once the specification is generated. +The `server` URL will be `ws://localhost`, and if the `websocket:Listener` has SSL configurations, the `server` URL will be `wss://localhost`. The `port` will be derived from the port number that the `websocket:Listener` is attached to. The protocol will be `ws`, and the WebSocket protocol version used will be `13`. + +#### Channel Object + +```yaml +channels: + /: + description: An echo service that echoes the messages sent by the client. + subscribe: + message: + $ref: '#/components/messages/Response' + publish: + message: + $ref: '#/components/messages/Hello' +``` + +Currently, this tool supports only one channel per specification. If there are multiple services in the project, the tool will generate a separate specification for each service, by equating each service to a channel. +The equivalent Ballerina service class is given below. The `description` will be the doc comment provided on the `resource` function of the service. + +```Ballerina +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on websocketListener { + # An echo service that echoes the messages sent by the client. + # + return - User status + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsService(); + } +} +``` + +When there are path parameters in the `resource` function, the `parameters` object will be added to the `channel` object with the relevant path parameters. + +When there are query parameters in the `resource` function, the `bindings` object will be added to the `channel` object with the relevant query parameters under the `query` object. + +When there are headers in the `resource` function, the `bindings` object will be added to the `channel` object with the relevant headers under the `headers` object. + +Here, the `bindingsVersion` will be same as the `version` in the `info` object. + +The returned `WsService` class is as follows. + +```Ballerina +service class WsService { + *websocket:Service; + + remote function onHello(Hello clientData) returns Response? { + return {message:"You sent: " + clientData.message}; + } + +} +``` + +The `subscribe` and `publish` objects will be derived from the `remote` functions available in the service class. +When there are multiple `subscribe` and `publish` payload types, the tool will add them all with the `oneOf` property. + +#### Components Object + +The `components` object will contain the `messages` and `schemas` objects. `messages` refer to what you can `subscribe` to and `publish` in the channel. `schemas` refer to the data types used in `messages`. + +`publish` messages must always be a `record` type of the name of the `remote` function without the `on` word. For example, if the `remote` function is `onHello`, the `publish` message type shall be `Hello`. +`subscribe` messages can be of type `any`. + +Refer to the following Ballerina records. + +```Ballerina +public type Hello record {| + string message; + string event; +|}; + +# Representation of a response +# +# + event - dispatcher key +# + message - message to be sent +public type Response record {| + string event = "just a message"; + string message; +|}; +``` + +These are the records that are used in the `WsService` class. These records will be mapped to the `components` object in the AsyncAPI specification as follows. If the fields are properly documented with comments, they will be added to the `description` field in the AsyncAPI specification. + +```yaml +components: + schemas: + Hello: + type: object + required: + - message + - event + properties: + message: + type: string + event: + type: string + const: Hello + Response: + type: object + required: + - event + - message + properties: + event: + type: string + description: dispatcher key + message: + type: string + description: message to be sent + description: Representation of a response + messages: + Response: + payload: + $ref: '#/components/schemas/Response' + Hello: + payload: + $ref: '#/components/schemas/Hello' + x-response: + $ref: '#/components/messages/Response' + x-required: false + x-response-type: simple-rpc +``` + +Here, for optional fields, the `x-required` property will be set to `false`. The `x-response-type` property will be set to `simple-rpc` if the `remote` function returns a single response. If the `remote` function returns a `stream` of responses, the `x-response-type` property will be set to `server-streaming`. + +#### Extended Properties + +The `x-dispathcherKey` property is added if there is a `@websocket:ServiceConfig` annotation with a `dispatcherKey` value in the service class. + +The `x-dispatcherStreamId` property is added if there is a `@websocket:ServiceConfig` annotation with a `dipatcherStreamId` value in the service class. + +## 3. Generating the Ballerina client + +This tool enables the generation of a WebSocket client based on a given AsyncAPI specification. It can be done by running the following command. + +```bash +bal asyncapi --protocol ws -i --o +``` + +| Command Parameter | Description | Mandatory | Default Value | +|:-----------------:|:----------------------------------------------------------------:|:---------:|:-------------------:| +| --protocol | indicates the protocol used. | No | http | +| <-i, --input> | specifies the file containing the specification | Yes | - | +| <-o, --output> | specifies the output directory | No | | +| --with-tests | specifies whether to generate a test skeleton | No | false | +| --license | specifies the path for a text file containing the license header | No | - | + + +The command generates an AsyncAPI specification for the given service running on WebSockets. The generated client will be generated in the specified output directory. If the output directory is not specified, the client will be generated in the current directory. + +Behaviour of the command, +- The tool will only generate a client if the provided input file is a valid AsyncAPI specification. +- The command will generate a `client.bal` file, a `types.bal` file, and a `utils.bal` file. If the `--with-tests` flag is provided, the tool will generate a `tests/tests.bal` file as well. +- If the `--license` flag is provided, the tool will add the license header to the generated files. + +### The `client.bal` file + +The generated client contains two workers, one to handle the write operations and the other to handle the read operations to the WebSocket server. + +The client will also use a `writeMessageQueue` to queue the messages to be sent to the server. + +The `x-dispatcherKey` property is used to determine the dispatcher key of the message, in which a pipe is created to handle the response of the message for a specific event. + +If the `x-dispatcherStreamId` property is available, the client will instead use the `dispatcherStreamId` to create pipes to produce the messages. + +These pipes are consumed by the respective `remote` functions. + +For each `publish` message type in the `channels` section, the tool will generate a `remote` function to send the message to the server. If the server responds with a single response, i.e., if the `x-response-type` property is set to `simple-rpc`, the generated function will return the response. If the server responds with a stream of responses, i.e., if the `x-response-type` property is set to `server-streaming`, the generated function will return a `stream` of responses. + +### The `utils.bal` file + +This file will contain a `PipesMap` class to manage the pipes created for each event. + +If a `stream` of responses are expected to be returned by one or more of the `remote` functions, then a `StreamGenerator` class will also be generated. + +### The `types.bal` file + +This file will contain the types used in the `client.bal` file. The types will be derived from the `components` object in the AsyncAPI specification. \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index f7898f834..8fe349873 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,36 +3,55 @@ group=io.ballerina version=0.8.0-SNAPSHOT #dependency -ballerinaLangVersion=2201.9.0-20240502-141200-0a49fa42 +ballerinaLangVersion=2201.9.0 testngVersion=7.6.1 slf4jVersion=1.7.30 puppycrawlCheckstyleVersion=10.12.0 +commonsIoVersion=2.11.0 jacksonDataformatYamlVersion=2.15.3 org.gradle.jvmargs=-Xmx4096M +log4jVersion=2.14.1 +picocliVersion=4.7.4 +apiCurioVersion=2.0.4 +githubJohnrengelmanShadowVersion=8.1.1 +underCouchDownloadVersion=5.4.0 +githubSpotbugsVersion=5.0.14 +javaModularityVersion=1.8.15 +researchgateReleaseVersion=2.8.0 # Stdlib Level 01 +stdlibConstraintVersion=1.5.0 stdlibIoVersion=1.6.0 stdlibRegexVersion=1.4.3 stdlibTimeVersion=2.4.0 stdlibUrlVersion=2.4.0 stdlibXmldataVersion=2.7.0 +observeVersion=1.2.3 # Stdlib Level 02 -stdlibCryptoVersion=2.7.0-20240502-172300-6b356e2 +stdlibCryptoVersion=2.7.1 stdlibLogVersion=2.9.0 stdlibOsVersion=1.8.0 stdlibTaskVersion=2.5.0 +observeInternalVersion=1.2.2 # Stdlib Level 03 -stdlibCacheVersion=3.8.0-20240409-101100-e2d7f4e +stdlibCacheVersion=3.8.0 stdlibFileVersion=1.9.0 stdlibMimeVersion=2.9.0 -stdlibUuidVersion=1.8.0-20240502-184000-71c8d75 +stdlibUuidVersion=1.8.0 # Stdlib Level 04 -stdlibAuthVersion=2.11.0-20240502-184600-96868c0 -stdlibJwtVersion=2.11.0-20240502-184700-00ec094 -stdlibOAuth2Version=2.11.0-20240502-185000-b5e4bc8 +stdlibAuthVersion=2.11.0 +stdlibJwtVersion=2.11.0 +stdlibOAuth2Version=2.11.0 # Stdlib Level 05 -stdlibHttpVersion=2.11.0-20240502-194500-bb0bced +stdlibHttpVersion=2.11.0 + +# Stdlib Level 06 +stdlibWebsocketVersion=2.11.0 + +# Ballerinax +stdlibKafkaVersion=4.0.0 +stdlibRabbitMqVersion=3.0.0 \ No newline at end of file diff --git a/samples/basic-chat/README.md b/samples/basic-chat/README.md new file mode 100644 index 000000000..f86cf35b7 --- /dev/null +++ b/samples/basic-chat/README.md @@ -0,0 +1,42 @@ +# Ballerina WebSockets Test Examples + +## Overview + +This is a set of Ballerina WebSocket test examples. The examples demonstrates how to use the AsyncAPI tools to generate the specification from a Ballerina WebSocket service and how to use the generated specification to create a Ballerina WebSocket client. Moreover, the examples demonstrate how to use the generated WebSockets client to write a simple client application. + +## Generating the AsyncAPI specification + +You can generate a demo AsyncAPI specification using the `server-demo` package. A pregenerated specification already exists in the `specs` directory. If you want to generate the specification again, you can use the following command, where `main.bal` is the Ballerina file that contains the entry point to the WebSocket service. + +```bash +cd server-demo +bal asyncapi --protocol ws -i main.bal -o specs +``` + +## A client-server example + +The `client` and `server` packages exemplify a basic client-server application. The client sends a message to the server, which responds with a message, and the client logs the response. The client continuously listens for messages from the server. + +You can have two instances of the client to pass messages between them through the server. + +In the `client` package, the files `client.bal`, `types.bal`, and `utils.bal` are generated by the AsyncAPI tool, whereas the `main.bal` file is an example usage of the generated client. + +In the `server` package, the `messages.md` file provides example messages outlining the expected structure by the server. The `main.bal` file contains the WebSocket server implementation. + +You can regenerate the client using the following command: + +```bash +cd client +bal asyncapi --protocol ws -i asyncapi.yaml +``` + +You can run the server and client using the following commands: + +```bash +bal run server +bal run client +``` + +## A client-server example with a dispatcher stream id + +The same application can be run with a dispatcher stream id using the `client-with-dispatcherStreamId` package and the `server-with-dispatcherStreamId` package. \ No newline at end of file diff --git a/samples/basic-chat/client-with-dispatcherStreamId/Ballerina.toml b/samples/basic-chat/client-with-dispatcherStreamId/Ballerina.toml new file mode 100644 index 000000000..529d692b8 --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "wso2" +name = "test_websocket" +version = "0.1.0" +distribution = "2201.9.0" + +[build-options] +observabilityIncluded = true diff --git a/samples/basic-chat/client-with-dispatcherStreamId/Dependencies.toml b/samples/basic-chat/client-with-dispatcherStreamId/Dependencies.toml new file mode 100644 index 000000000..30980c398 --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/Dependencies.toml @@ -0,0 +1,348 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.9.0" + +[[package]] +org = "ballerina" +name = "auth" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"} +] + +[[package]] +org = "ballerina" +name = "cache" +version = "3.8.0" +dependencies = [ + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "task"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "constraint" +version = "1.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "crypto" +version = "2.7.2" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "file" +version = "1.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "os"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "http" +version = "2.11.2" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "file"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.decimal"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.regexp"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "mime"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "observe"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "io" +version = "1.6.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] +modules = [ + {org = "ballerina", packageName = "io", moduleName = "io"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "jwt" +version = "2.12.1" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "lang.__internal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.array" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"} +] + +[[package]] +org = "ballerina" +name = "lang.decimal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.int" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.object" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "lang.regexp" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.runtime" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.string" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.regexp"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerina", packageName = "log", moduleName = "log"} +] + +[[package]] +org = "ballerina" +name = "mime" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"} +] + +[[package]] +org = "ballerina" +name = "oauth2" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.2.3" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "os" +version = "1.8.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "task" +version = "2.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "time" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "url" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "uuid" +version = "1.8.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "uuid", moduleName = "uuid"} +] + +[[package]] +org = "ballerina" +name = "websocket" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "http"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "websocket", moduleName = "websocket"} +] + +[[package]] +org = "ballerinai" +name = "observe" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerinai", packageName = "observe", moduleName = "observe"} +] + +[[package]] +org = "haritha" +name = "test_websocket" +version = "0.1.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "uuid"}, + {org = "ballerina", name = "websocket"}, + {org = "ballerinai", name = "observe"}, + {org = "xlibb", name = "pipe"} +] +modules = [ + {org = "haritha", packageName = "test_websocket", moduleName = "test_websocket"} +] + +[[package]] +org = "xlibb" +name = "pipe" +version = "1.4.1" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] +modules = [ + {org = "xlibb", packageName = "pipe", moduleName = "pipe"} +] + diff --git a/samples/basic-chat/client-with-dispatcherStreamId/asyncapi.yaml b/samples/basic-chat/client-with-dispatcherStreamId/asyncapi.yaml new file mode 100644 index 000000000..adb82d358 --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/asyncapi.yaml @@ -0,0 +1,124 @@ +asyncapi: 2.5.0 +info: + title: User + version: 0.1.0 +servers: + development: + url: "{server}:{port}/user" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9092" +channels: + /: + description: Allows clients to get real-time data on users and chat with them. + subscribe: + message: + $ref: '#/components/messages/Response' + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/Unsubscribe' + - $ref: '#/components/messages/Chat' +components: + schemas: + Subscribe: + type: object + required: + - event + - name + - gender + - id + properties: + event: + type: string + const: Subscribe + description: type of event + name: + type: string + description: name of the user + gender: + type: string + description: gender of the user + id: + type: string + description: dispathcherStreamId of the message + description: Representation of a subscription. + Response: + type: object + required: + - event + - message + - id + properties: + event: + type: string + description: dispatcher key + message: + type: string + description: message to be sent + id: + type: string + description: dispathcherStreamId of the message + description: Representation of a response + Unsubscribe: + type: object + required: + - event + - id + properties: + event: + type: string + const: Unsubscribe + description: dispatcher key + id: + type: string + description: dispathcherStreamId of the message + description: Representation of an unsubscribe message. + Chat: + type: object + required: + - message + - event + - toUserId + - id + properties: + message: + type: string + description: 'message to be sent ' + event: + type: string + const: Chat + description: dispatcher key + toUserId: + type: string + description: user id to send the message + id: + type: string + description: dispathcherStreamId of the message + description: Repersentation of a message. + messages: + Response: + payload: + $ref: '#/components/schemas/Response' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/Response' + x-response-type: server-streaming + Unsubscribe: + payload: + $ref: '#/components/schemas/Unsubscribe' + Chat: + payload: + $ref: '#/components/schemas/Chat' + x-response: + $ref: '#/components/messages/Response' + x-response-type: simple-rpc +x-dispatcherKey: event +x-dispatcherStreamId: id diff --git a/samples/basic-chat/client-with-dispatcherStreamId/client.bal b/samples/basic-chat/client-with-dispatcherStreamId/client.bal new file mode 100644 index 000000000..b0fff54e1 --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/client.bal @@ -0,0 +1,200 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class UserClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9092/user") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe; + MessageWithId|error messageWithId = message.cloneWithType(MessageWithId); + if messageWithId is MessageWithId { + pipe = self.pipes.getPipe(messageWithId.id); + } else { + pipe = self.pipes.getPipe(message.event); + } + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + ResponseStreamGenerator streamGenerator = new (self.pipes, subscribe.id, timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doUnsubscribe(Unsubscribe unsubscribe, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = unsubscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + remote isolated function doChat(Chat chat, decimal timeout) returns Response|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = chat.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe(chat.id).consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + error? pipeCloseError = self.pipes.removePipe(chat.id); + if pipeCloseError is error { + log:printDebug("PipeError: Error in closing pipe.", pipeCloseError); + } + Response|error response = responseMessage.cloneWithType(); + if response is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", response); + } + return response; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/samples/basic-chat/client-with-dispatcherStreamId/main.bal b/samples/basic-chat/client-with-dispatcherStreamId/main.bal new file mode 100644 index 000000000..96fbdca7d --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/main.bal @@ -0,0 +1,57 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/io; +import ballerina/uuid; + +UserClient chatClient = check new (); + +public function main() returns error? { + worker subscribe returns error? { + io:println("Subscribing to the chat service"); + stream subscription = check chatClient->doSubscribe({"event":"subscribe","name":"Ballerina","gender":"Female", "id":uuid:createType1AsString()}, 10); + // the server will send two responses to the subscription request immediately + printSingleResponse(subscription); + printSingleResponse(subscription); + //to notify the subscription is done + true ->> function; + while true { + printSingleResponse(subscription); + } + } + boolean waitForSubscribe = check <- subscribe; + if waitForSubscribe is true { + io:print("Enter your message: "); + string message = io:readln(); + io:print("Enter to whom you want to send the message: "); + string toUser = io:readln(); + Response|error response = chatClient->doChat({"event":"chat","message":message, "toUserId": toUser, "id":uuid:createType1AsString()}, 10); + if response is error { + io:println("Error occurred: " + response.message()); + } + io:println("RESPONSE: ", response); + } + check wait subscribe; +} + +function printSingleResponse(stream subscription) { + record {|Response value;|}|error? message = subscription.next(); + if message is record {|Response value;|} { + io:println(message.value); + } else if message is error { + io:println("Error occurred at worker: " + message.message()); + } +} diff --git a/samples/basic-chat/client-with-dispatcherStreamId/types.bal b/samples/basic-chat/client-with-dispatcherStreamId/types.bal new file mode 100644 index 000000000..c19e62ef9 --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/types.bal @@ -0,0 +1,61 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +public type Message readonly & record {string event;}; + +public type MessageWithId readonly & record {string event; string id;}; + +# Representation of a subscription. +public type Subscribe record { + # type of event + string event; + # name of the user + string name; + # gender of the user + string gender; + # dispathcherStreamId of the message + string id; +}; + +# Representation of a response +public type Response record { + # dispatcher key + string event; + # message to be sent + string message; + # dispathcherStreamId of the message + string id; +}; + +# Representation of an unsubscribe message. +public type Unsubscribe record { + # dispatcher key + string event; + # dispathcherStreamId of the message + string id; +}; + +# Repersentation of a message. +public type Chat record { + # message to be sent + string message; + # dispatcher key + string event; + # user id to send the message + string toUserId; + # dispathcherStreamId of the message + string id; +}; diff --git a/samples/basic-chat/client-with-dispatcherStreamId/utils.bal b/samples/basic-chat/client-with-dispatcherStreamId/utils.bal new file mode 100644 index 000000000..31f53d41c --- /dev/null +++ b/samples/basic-chat/client-with-dispatcherStreamId/utils.bal @@ -0,0 +1,121 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import xlibb/pipe; + +# Stream generator class for Response return type +public client isolated class ResponseStreamGenerator { + *Generator; + private final PipesMap pipes; + private final string pipeId; + private final decimal timeout; + + # StreamGenerator + # + # + pipe - Pipe to hold stream messages + # + timeout - Waiting time + public isolated function init(PipesMap pipes, string pipeId, decimal timeout) { + self.pipes = pipes; + self.pipeId = pipeId; + self.timeout = timeout; + } + + public isolated function next() returns record {|Response value;|}|error { + while true { + anydata|error? message = self.pipes.getPipe(self.pipeId).consume(self.timeout); + if message is error? { + continue; + } + Response response = check message.cloneWithType(); + return {value: response}; + } + } + + public isolated function close() returns error? { + check self.pipes.removePipe(self.pipeId); + } +} + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# StreamGeneratorsMap class to handle generated stream generators +public isolated class StreamGeneratorsMap { + private final Generator[] streamGenerators; + + public isolated function init() { + self.streamGenerators = []; + } + + public isolated function addStreamGenerator(Generator streamGenerator) { + lock { + self.streamGenerators.push(streamGenerator); + } + } + + public isolated function removeStreamGenerators() returns error? { + lock { + foreach Generator streamGenerator in self.streamGenerators { + check streamGenerator.close(); + } + } + } +} + +# Generator object type for type inclusion +public type Generator isolated object { + public isolated function next() returns record {|anydata value;|}|error; + public isolated function close() returns error?; +}; diff --git a/samples/basic-chat/client/Ballerina.toml b/samples/basic-chat/client/Ballerina.toml new file mode 100644 index 000000000..529d692b8 --- /dev/null +++ b/samples/basic-chat/client/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "wso2" +name = "test_websocket" +version = "0.1.0" +distribution = "2201.9.0" + +[build-options] +observabilityIncluded = true diff --git a/samples/basic-chat/client/Dependencies.toml b/samples/basic-chat/client/Dependencies.toml new file mode 100644 index 000000000..fab3f420d --- /dev/null +++ b/samples/basic-chat/client/Dependencies.toml @@ -0,0 +1,333 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.9.0" + +[[package]] +org = "ballerina" +name = "auth" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"} +] + +[[package]] +org = "ballerina" +name = "cache" +version = "3.8.0" +dependencies = [ + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "task"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "constraint" +version = "1.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "crypto" +version = "2.7.2" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "file" +version = "1.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "os"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "http" +version = "2.11.2" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "file"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.decimal"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.regexp"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "mime"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "observe"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "io" +version = "1.6.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] +modules = [ + {org = "ballerina", packageName = "io", moduleName = "io"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "jwt" +version = "2.12.1" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "lang.__internal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.array" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"} +] + +[[package]] +org = "ballerina" +name = "lang.decimal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.int" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.object" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "lang.regexp" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.runtime" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.string" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.regexp"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerina", packageName = "log", moduleName = "log"} +] + +[[package]] +org = "ballerina" +name = "mime" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"} +] + +[[package]] +org = "ballerina" +name = "oauth2" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.2.3" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "os" +version = "1.8.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "task" +version = "2.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "time" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "url" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "websocket" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "http"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "websocket", moduleName = "websocket"} +] + +[[package]] +org = "ballerinai" +name = "observe" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerinai", packageName = "observe", moduleName = "observe"} +] + +[[package]] +org = "haritha" +name = "test_websocket" +version = "0.1.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "websocket"}, + {org = "ballerinai", name = "observe"}, + {org = "xlibb", name = "pipe"} +] +modules = [ + {org = "haritha", packageName = "test_websocket", moduleName = "test_websocket"} +] + +[[package]] +org = "xlibb" +name = "pipe" +version = "1.4.1" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] +modules = [ + {org = "xlibb", packageName = "pipe", moduleName = "pipe"} +] + diff --git a/samples/basic-chat/client/asyncapi.yaml b/samples/basic-chat/client/asyncapi.yaml new file mode 100644 index 000000000..d0b08496f --- /dev/null +++ b/samples/basic-chat/client/asyncapi.yaml @@ -0,0 +1,107 @@ +asyncapi: 2.5.0 +info: + title: User + version: 0.1.0 +servers: + development: + url: "{server}:{port}/user" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9092" +channels: + /: + description: Allows clients to get real-time data on users and chat with them. + subscribe: + message: + $ref: '#/components/messages/Response' + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/Unsubscribe' + - $ref: '#/components/messages/Chat' +components: + schemas: + Subscribe: + type: object + required: + - event + - name + - gender + properties: + event: + type: string + const: Subscribe + description: type of event + name: + type: string + description: name of the user + gender: + type: string + description: gender of the user + description: Representation of a subscription. + Response: + type: object + required: + - event + - message + properties: + event: + type: string + description: dispatcher key + message: + type: string + description: message to be sent + description: Representation of a response + Unsubscribe: + type: object + required: + - event + properties: + event: + type: string + const: Unsubscribe + description: dispatcher key + description: Representation of an unsubscribe message. + Chat: + type: object + required: + - message + - event + - toUserId + properties: + message: + type: string + description: 'message to be sent ' + event: + type: string + const: Chat + description: dispatcher key + toUserId: + type: string + description: user id to send the message + description: Repersentation of a message. + messages: + Response: + payload: + $ref: '#/components/schemas/Response' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/Response' + x-response-type: server-streaming + Unsubscribe: + payload: + $ref: '#/components/schemas/Unsubscribe' + Chat: + payload: + $ref: '#/components/schemas/Chat' + x-response: + $ref: '#/components/messages/Response' + x-response-type: simple-rpc +x-dispatcherKey: event diff --git a/samples/basic-chat/client/client.bal b/samples/basic-chat/client/client.bal new file mode 100644 index 000000000..0dd1b6ec4 --- /dev/null +++ b/samples/basic-chat/client/client.bal @@ -0,0 +1,190 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/log; +import ballerina/websocket; + +import xlibb/pipe; + +public client isolated class UserClient { + private final websocket:Client clientEp; + private final pipe:Pipe writeMessageQueue; + private final PipesMap pipes; + private final StreamGeneratorsMap streamGenerators; + private boolean isActive; + + # Gets invoked to initialize the `connector`. + # + # + config - The configurations to be used when initializing the `connector` + # + serviceUrl - URL of the target service + # + return - An error if connector initialization failed + public isolated function init(websocket:ClientConfiguration clientConfig = {}, string serviceUrl = "ws://localhost:9092/user") returns error? { + self.pipes = new (); + self.streamGenerators = new (); + self.writeMessageQueue = new (1000); + websocket:Client websocketEp = check new (serviceUrl, clientConfig); + self.clientEp = websocketEp; + self.isActive = true; + self.startMessageWriting(); + self.startMessageReading(); + return; + } + + # Used to write messages to the websocket. + # + private isolated function startMessageWriting() { + worker writeMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|pipe:Error message = self.writeMessageQueue.consume(5); + if message is pipe:Error { + if message.message() == "Operation has timed out" { + continue; + } + log:printError("PipeError: Failed to consume message from the pipe", message); + self.attemptToCloseConnection(); + return; + } + websocket:Error? wsErr = self.clientEp->writeMessage(message); + if wsErr is websocket:Error { + log:printError("WsError: Failed to write message to the client", wsErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + # Used to read messages from the websocket. + # + private isolated function startMessageReading() { + worker readMessage { + while true { + lock { + if !self.isActive { + break; + } + } + Message|websocket:Error message = self.clientEp->readMessage(Message); + if message is websocket:Error { + log:printError("WsError: Failed to read message from the client", message); + self.attemptToCloseConnection(); + return; + } + pipe:Pipe pipe = self.pipes.getPipe(message.event); + pipe:Error? pipeErr = pipe.produce(message, 5); + if pipeErr is pipe:Error { + log:printError("PipeError: Failed to produce message to the pipe", pipeErr); + self.attemptToCloseConnection(); + return; + } + } + } + } + + remote isolated function doSubscribe(Subscribe subscribe, decimal timeout) returns stream|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = subscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + stream streamMessages; + lock { + ResponseStreamGenerator streamGenerator = new (self.pipes, "subscribe", timeout); + self.streamGenerators.addStreamGenerator(streamGenerator); + streamMessages = new (streamGenerator); + } + return streamMessages; + } + + remote isolated function doUnsubscribe(Unsubscribe unsubscribe, decimal timeout) returns error? { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = unsubscribe.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + } + + remote isolated function doChat(Chat chat, decimal timeout) returns Response|error { + lock { + if !self.isActive { + return error("ConnectionError: Connection has been closed"); + } + } + Message|error message = chat.cloneWithType(); + if message is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", message); + } + pipe:Error? pipeErr = self.writeMessageQueue.produce(message, timeout); + if pipeErr is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in producing message", pipeErr); + } + Message|pipe:Error responseMessage = self.pipes.getPipe("chat").consume(timeout); + if responseMessage is pipe:Error { + self.attemptToCloseConnection(); + return error("PipeError: Error in consuming message", responseMessage); + } + Response|error response = responseMessage.cloneWithType(); + if response is error { + self.attemptToCloseConnection(); + return error("DataBindingError: Error in cloning message", response); + } + return response; + } + + isolated function attemptToCloseConnection() { + error? connectionClose = self->connectionClose(); + if connectionClose is error { + log:printError("ConnectionError", connectionClose); + } + } + + remote isolated function connectionClose() returns error? { + lock { + self.isActive = false; + check self.writeMessageQueue.immediateClose(); + check self.pipes.removePipes(); + check self.streamGenerators.removeStreamGenerators(); + check self.clientEp->close(); + } + }; +} diff --git a/samples/basic-chat/client/main.bal b/samples/basic-chat/client/main.bal new file mode 100644 index 000000000..ec31195c1 --- /dev/null +++ b/samples/basic-chat/client/main.bal @@ -0,0 +1,56 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/io; + +UserClient chatClient = check new (); + +public function main() returns error? { + worker subscribe returns error? { + io:println("Subscribing to the chat service"); + stream subscription = check chatClient->doSubscribe({"event":"subscribe","name":"Ballerina","gender":"Female"}, 10); + // the server will send two responses to the subscription request immediately + printSingleResponse(subscription); + printSingleResponse(subscription); + //to notify the subscription is done + true ->> function; + while true { + printSingleResponse(subscription); + } + } + boolean waitForSubscribe = check <- subscribe; + if waitForSubscribe is true { + io:print("Enter your message: "); + string message = io:readln(); + io:print("Enter to whom you want to send the message: "); + string toUser = io:readln(); + Response|error response = chatClient->doChat({"event":"chat","message":message, "toUserId": toUser}, 10); + if response is error { + io:println("Error occurred: " + response.message()); + } + io:println("RESPONSE: ", response); + } + check wait subscribe; +} + +function printSingleResponse(stream subscription) { + record {|Response value;|}|error? message = subscription.next(); + if message is record {|Response value;|} { + io:println(message.value); + } else if message is error { + io:println("Error occurred at worker: " + message.message()); + } +} diff --git a/samples/basic-chat/client/types.bal b/samples/basic-chat/client/types.bal new file mode 100644 index 000000000..a679348fc --- /dev/null +++ b/samples/basic-chat/client/types.bal @@ -0,0 +1,51 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +public type Message readonly & record {string event;}; + +# Representation of a subscription. +public type Subscribe record { + # type of event + string event; + # name of the user + string name; + # gender of the user + string gender; +}; + +# Representation of a response +public type Response record { + # dispatcher key + string event; + # message to be sent + string message; +}; + +# Representation of an unsubscribe message. +public type Unsubscribe record { + # dispatcher key + string event; +}; + +# Repersentation of a message. +public type Chat record { + # message to be sent + string message; + # dispatcher key + string event; + # user id to send the message + string toUserId; +}; diff --git a/samples/basic-chat/client/utils.bal b/samples/basic-chat/client/utils.bal new file mode 100644 index 000000000..31f53d41c --- /dev/null +++ b/samples/basic-chat/client/utils.bal @@ -0,0 +1,121 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import xlibb/pipe; + +# Stream generator class for Response return type +public client isolated class ResponseStreamGenerator { + *Generator; + private final PipesMap pipes; + private final string pipeId; + private final decimal timeout; + + # StreamGenerator + # + # + pipe - Pipe to hold stream messages + # + timeout - Waiting time + public isolated function init(PipesMap pipes, string pipeId, decimal timeout) { + self.pipes = pipes; + self.pipeId = pipeId; + self.timeout = timeout; + } + + public isolated function next() returns record {|Response value;|}|error { + while true { + anydata|error? message = self.pipes.getPipe(self.pipeId).consume(self.timeout); + if message is error? { + continue; + } + Response response = check message.cloneWithType(); + return {value: response}; + } + } + + public isolated function close() returns error? { + check self.pipes.removePipe(self.pipeId); + } +} + +# PipesMap class to handle generated pipes +public isolated class PipesMap { + private final map pipes; + + public isolated function init() { + self.pipes = {}; + } + + public isolated function addPipe(string id, pipe:Pipe pipe) { + lock { + self.pipes[id] = pipe; + } + } + + public isolated function getPipe(string id) returns pipe:Pipe { + lock { + if (self.pipes.hasKey(id)) { + return self.pipes.get(id); + } + pipe:Pipe pipe = new (100); + self.addPipe(id, pipe); + return pipe; + } + } + + public isolated function removePipe(string id) returns error? { + lock { + _ = check self.getPipe(id).gracefulClose(); + _ = self.pipes.remove(id); + } + } + + public isolated function removePipes() returns error? { + lock { + foreach pipe:Pipe pipe in self.pipes { + check pipe.gracefulClose(); + } + self.pipes.removeAll(); + } + } +} + +# StreamGeneratorsMap class to handle generated stream generators +public isolated class StreamGeneratorsMap { + private final Generator[] streamGenerators; + + public isolated function init() { + self.streamGenerators = []; + } + + public isolated function addStreamGenerator(Generator streamGenerator) { + lock { + self.streamGenerators.push(streamGenerator); + } + } + + public isolated function removeStreamGenerators() returns error? { + lock { + foreach Generator streamGenerator in self.streamGenerators { + check streamGenerator.close(); + } + } + } +} + +# Generator object type for type inclusion +public type Generator isolated object { + public isolated function next() returns record {|anydata value;|}|error; + public isolated function close() returns error?; +}; diff --git a/samples/basic-chat/server-demo/Ballerina.toml b/samples/basic-chat/server-demo/Ballerina.toml new file mode 100644 index 000000000..2c61b61bc --- /dev/null +++ b/samples/basic-chat/server-demo/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "wso2" +name = "websocket_test" +version = "0.1.0" +distribution = "2201.9.0" + +[build-options] +observabilityIncluded = true diff --git a/samples/basic-chat/server-demo/Dependencies.toml b/samples/basic-chat/server-demo/Dependencies.toml new file mode 100644 index 000000000..66545b816 --- /dev/null +++ b/samples/basic-chat/server-demo/Dependencies.toml @@ -0,0 +1,318 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.9.0" + +[[package]] +org = "ballerina" +name = "auth" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"} +] + +[[package]] +org = "ballerina" +name = "cache" +version = "3.8.0" +dependencies = [ + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "task"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "constraint" +version = "1.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "crypto" +version = "2.7.2" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "file" +version = "1.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "os"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "http" +version = "2.11.2" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "file"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.decimal"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.regexp"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "mime"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "observe"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "io" +version = "1.6.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] +modules = [ + {org = "ballerina", packageName = "io", moduleName = "io"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "jwt" +version = "2.12.1" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "lang.__internal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.array" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"} +] + +[[package]] +org = "ballerina" +name = "lang.decimal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.int" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.object" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "lang.regexp" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.runtime" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.string" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.regexp"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] + +[[package]] +org = "ballerina" +name = "mime" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"} +] + +[[package]] +org = "ballerina" +name = "oauth2" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.2.3" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "os" +version = "1.8.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "task" +version = "2.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "time" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "url" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "websocket" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "http"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "websocket", moduleName = "websocket"} +] + +[[package]] +org = "ballerinai" +name = "observe" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerinai", packageName = "observe", moduleName = "observe"} +] + +[[package]] +org = "haritha" +name = "websocket_test" +version = "0.1.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "websocket"}, + {org = "ballerinai", name = "observe"} +] +modules = [ + {org = "haritha", packageName = "websocket_test", moduleName = "websocket_test"}, + {org = "haritha", packageName = "websocket_test", moduleName = "websocket_test.types"} +] + diff --git a/samples/basic-chat/server-demo/main.bal b/samples/basic-chat/server-demo/main.bal new file mode 100644 index 000000000..e9640c691 --- /dev/null +++ b/samples/basic-chat/server-demo/main.bal @@ -0,0 +1,110 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import websocket_test.types; +import ballerina/io; + +listener websocket:Listener websocketListener = check new(9092); +map users = {}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on websocketListener { + # An echo service that echoes the messages sent by the client. + # + return - User status + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsService(); + } + +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /user on websocketListener { + # Allows clients to get real-time data on users and chat with them. + # + return - websocket service + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsServiceUser(); + } + +} + +service class WsService { + *websocket:Service; + + remote function onHello(types:Hello clientData) returns types:Response? { + return {message:"You sent: " + clientData.message}; + } + +} + +service class WsServiceUser { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, types:Subscribe sub) returns stream|error { + string callerId = caller.getConnectionId(); + io:println(sub.name + " subscribed: " + callerId); + types:User user = {caller: caller, gender: sub.gender, name: sub.name, id: callerId}; + users[callerId] = user; + broadcast("System: User " + user.name + " (" + callerId + ")" + " has joined the chat"); + types:Response[] response = [{message: "System: Welcome to the chat!", event:"subscribe"}]; + return response.toStream(); + } + + remote function onUnsubscribe(websocket:Caller caller, types:Unsubscribe unsubscribe) returns error? { + string callerId = caller.getConnectionId(); + broadcast("System: User " + users.get(callerId).name + " has left the chat"); + _ = users.remove(callerId); + } + + // remote function onClose(websocket:Caller caller) returns websocket:Error? { + // string callerId = caller.getConnectionId(); + // if (users.hasKey(callerId)) { + // _ = users.remove(callerId); + // } + // } + + remote function onChat(websocket:Caller caller, types:Chat message) returns types:Response|error { + string callerId = caller.getConnectionId(); + if (!users.hasKey(callerId)) { + return { message: "Please subscribe first to send messages"}; + } + types:User sender = users.get(callerId); + if (!users.hasKey(message.toUserId)) { + return {message:"User not found"}; + } + websocket:Caller? receiver = users.get(message.toUserId).caller; + if (receiver is ()) { + return {message:"User not found"}; + } + _ = check receiver->writeMessage({message: sender.name + ": " + message.message, event:"subscribe"}); + return {message:"You: " + message.message, event: "chat"}; + } + +} + +function broadcast(string message) { + users.forEach(function (types:User user) { + websocket:Caller? caller = user.caller; + if (caller is ()) { + return; + } + types:Response response = {message: message, event: "subscribe"}; + error? err = caller->writeMessage(response); + if (err is error) { + io:println("Error broadcasting message: " + err.message()); + } + }); +} diff --git a/samples/basic-chat/server-demo/messages.md b/samples/basic-chat/server-demo/messages.md new file mode 100644 index 000000000..708a2b48f --- /dev/null +++ b/samples/basic-chat/server-demo/messages.md @@ -0,0 +1,17 @@ +## Subscribe Message Example + +```json +{"event":"subscribe","name":"Gopi","gender":"Male"} +``` + +## Unsubscribe Message Example + +```json +{"event":"unsubscribe"} +``` + +## Chat Message Example + +```json +{"event":"chat","message":"Hello Ballerina", "toUserId": "cc6b1efffe42ea75-0001e3b1-00000002-237f98c8d2877f67-d7aa765b"} +``` \ No newline at end of file diff --git a/samples/basic-chat/server-demo/modules/types/types.bal b/samples/basic-chat/server-demo/modules/types/types.bal new file mode 100644 index 000000000..d996b0d58 --- /dev/null +++ b/samples/basic-chat/server-demo/modules/types/types.bal @@ -0,0 +1,89 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Representation of a response +# +# + event - dispatcher key +# + message - message to be sent +public type Response record {| + string event = "just a message"; + string message; +|}; + +# Representation of an unsubscribe message. +# +# + event - dispatcher key +public type Unsubscribe record {| + string event; +|}; + +# Representation of an info message. +# +# + event - dispatcher key +public type Info record {| + string event; +|}; + +# Representation of a subscription. +# +# + event - type of event +# + name - name of the user +# + gender - gender of the user +public type Subscribe record {| + string event; + string name; + string gender; +|}; + +# Representation of a user. +# +# + name - name of the user +# + gender - gender of the user +# + id - id of the user (connection id) +# + caller - websocket caller object +public type User record {| + string name; + string gender; + string id; + websocket:Caller caller; +|}; + +# Repersentation of a message. +# +# + message - message to be sent +# + event - dispatcher key +# + toUserId - user id to send the message +public type Chat record {| + string message; + string event; + string toUserId; +|}; + +public type Hello record {| + string message; + string event; +|}; + +# Representation of a basic event. +# +# + event - type of event +# + id - id of the event +public type ClientData record {| + string event; + string id; +|}; diff --git a/samples/basic-chat/server-demo/specs/main_asyncapi.yaml b/samples/basic-chat/server-demo/specs/main_asyncapi.yaml new file mode 100644 index 000000000..fdbcd3095 --- /dev/null +++ b/samples/basic-chat/server-demo/specs/main_asyncapi.yaml @@ -0,0 +1,61 @@ +asyncapi: 2.5.0 +info: + title: / + version: 0.1.0 +servers: + development: + url: "{server}:{port}/" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9092" +channels: + /: + description: An echo service that echoes the messages sent by the client. + subscribe: + message: + $ref: '#/components/messages/Response' + publish: + message: + $ref: '#/components/messages/Hello' +components: + schemas: + Hello: + type: object + required: + - message + - event + properties: + message: + type: string + event: + type: string + const: Hello + Response: + type: object + required: + - event + - message + properties: + event: + type: string + description: dispatcher key + message: + type: string + description: message to be sent + description: Representation of a response + messages: + Response: + payload: + $ref: '#/components/schemas/Response' + Hello: + payload: + $ref: '#/components/schemas/Hello' + x-response: + $ref: '#/components/messages/Response' + x-required: false + x-response-type: simple-rpc +x-dispatcherKey: event diff --git a/samples/basic-chat/server-demo/specs/user_asyncapi.yaml b/samples/basic-chat/server-demo/specs/user_asyncapi.yaml new file mode 100644 index 000000000..d0b08496f --- /dev/null +++ b/samples/basic-chat/server-demo/specs/user_asyncapi.yaml @@ -0,0 +1,107 @@ +asyncapi: 2.5.0 +info: + title: User + version: 0.1.0 +servers: + development: + url: "{server}:{port}/user" + protocol: ws + protocolVersion: "13" + variables: + server: + default: ws://localhost + port: + default: "9092" +channels: + /: + description: Allows clients to get real-time data on users and chat with them. + subscribe: + message: + $ref: '#/components/messages/Response' + publish: + message: + oneOf: + - $ref: '#/components/messages/Subscribe' + - $ref: '#/components/messages/Unsubscribe' + - $ref: '#/components/messages/Chat' +components: + schemas: + Subscribe: + type: object + required: + - event + - name + - gender + properties: + event: + type: string + const: Subscribe + description: type of event + name: + type: string + description: name of the user + gender: + type: string + description: gender of the user + description: Representation of a subscription. + Response: + type: object + required: + - event + - message + properties: + event: + type: string + description: dispatcher key + message: + type: string + description: message to be sent + description: Representation of a response + Unsubscribe: + type: object + required: + - event + properties: + event: + type: string + const: Unsubscribe + description: dispatcher key + description: Representation of an unsubscribe message. + Chat: + type: object + required: + - message + - event + - toUserId + properties: + message: + type: string + description: 'message to be sent ' + event: + type: string + const: Chat + description: dispatcher key + toUserId: + type: string + description: user id to send the message + description: Repersentation of a message. + messages: + Response: + payload: + $ref: '#/components/schemas/Response' + Subscribe: + payload: + $ref: '#/components/schemas/Subscribe' + x-response: + $ref: '#/components/messages/Response' + x-response-type: server-streaming + Unsubscribe: + payload: + $ref: '#/components/schemas/Unsubscribe' + Chat: + payload: + $ref: '#/components/schemas/Chat' + x-response: + $ref: '#/components/messages/Response' + x-response-type: simple-rpc +x-dispatcherKey: event diff --git a/samples/basic-chat/server-with-dispatcherStreamId/Ballerina.toml b/samples/basic-chat/server-with-dispatcherStreamId/Ballerina.toml new file mode 100644 index 000000000..2c61b61bc --- /dev/null +++ b/samples/basic-chat/server-with-dispatcherStreamId/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "wso2" +name = "websocket_test" +version = "0.1.0" +distribution = "2201.9.0" + +[build-options] +observabilityIncluded = true diff --git a/samples/basic-chat/server-with-dispatcherStreamId/Dependencies.toml b/samples/basic-chat/server-with-dispatcherStreamId/Dependencies.toml new file mode 100644 index 000000000..66545b816 --- /dev/null +++ b/samples/basic-chat/server-with-dispatcherStreamId/Dependencies.toml @@ -0,0 +1,318 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.9.0" + +[[package]] +org = "ballerina" +name = "auth" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"} +] + +[[package]] +org = "ballerina" +name = "cache" +version = "3.8.0" +dependencies = [ + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "task"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "constraint" +version = "1.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "crypto" +version = "2.7.2" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "file" +version = "1.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "os"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "http" +version = "2.11.2" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "file"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.decimal"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.regexp"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "mime"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "observe"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "io" +version = "1.6.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] +modules = [ + {org = "ballerina", packageName = "io", moduleName = "io"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "jwt" +version = "2.12.1" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "lang.__internal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.array" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"} +] + +[[package]] +org = "ballerina" +name = "lang.decimal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.int" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.object" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "lang.regexp" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.runtime" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.string" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.regexp"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] + +[[package]] +org = "ballerina" +name = "mime" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"} +] + +[[package]] +org = "ballerina" +name = "oauth2" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.2.3" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "os" +version = "1.8.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "task" +version = "2.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "time" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "url" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "websocket" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "http"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "websocket", moduleName = "websocket"} +] + +[[package]] +org = "ballerinai" +name = "observe" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerinai", packageName = "observe", moduleName = "observe"} +] + +[[package]] +org = "haritha" +name = "websocket_test" +version = "0.1.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "websocket"}, + {org = "ballerinai", name = "observe"} +] +modules = [ + {org = "haritha", packageName = "websocket_test", moduleName = "websocket_test"}, + {org = "haritha", packageName = "websocket_test", moduleName = "websocket_test.types"} +] + diff --git a/samples/basic-chat/server-with-dispatcherStreamId/main.bal b/samples/basic-chat/server-with-dispatcherStreamId/main.bal new file mode 100644 index 000000000..cf35779c1 --- /dev/null +++ b/samples/basic-chat/server-with-dispatcherStreamId/main.bal @@ -0,0 +1,110 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import websocket_test.types; +import ballerina/io; + +listener websocket:Listener websocketListener = check new(9092); +map users = {}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on websocketListener { + # An echo service that echoes the messages sent by the client. + # + return - User status + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsService(); + } + +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /user on websocketListener { + # Allows clients to get real-time data on users and chat with them. + # + return - websocket service + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsServiceUser(); + } + +} + +service class WsService { + *websocket:Service; + + remote function onHello(types:Hello clientData) returns types:Response? { + return {message:"You sent: " + clientData.message, id: "null"}; + } + +} + +service class WsServiceUser { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, types:Subscribe sub) returns types:Response { + string callerId = caller.getConnectionId(); + io:println(sub.name + " subscribed: " + callerId); + types:User user = {caller: caller, gender: sub.gender, name: sub.name, id: callerId, streamId: sub.id}; + users[callerId] = user; + broadcast("System: User " + user.name + " (" + callerId + ")" + " has joined the chat"); + return {message: "System: Welcome to the chat!", event:"chat", id: sub.id}; + } + + remote function onUnsubscribe(websocket:Caller caller, types:Unsubscribe unsubscribe) returns error? { + string callerId = caller.getConnectionId(); + broadcast("System: User " + users.get(callerId).name + " has left the chat"); + _ = users.remove(callerId); + } + + remote function onClose(websocket:Caller caller) returns websocket:Error? { + string callerId = caller.getConnectionId(); + if (users.hasKey(callerId)) { + _ = users.remove(callerId); + } + } + + remote function onChat(websocket:Caller caller, types:Chat message) returns types:Response|error { + string callerId = caller.getConnectionId(); + if (!users.hasKey(callerId)) { + return { message: "Please subscribe first to send messages", id: message.id, event:"chat"}; + } + types:User sender = users.get(callerId); + if (!users.hasKey(message.toUserId)) { + return {message:"User not found", id: message.id, event:"chat"}; + } + types:User receiver = users.get(message.toUserId); + websocket:Caller? receiverCaller = receiver.caller; + if (receiverCaller is ()) { + return {message:"User not found", id: message.id, event:"chat"}; + } + _ = check receiverCaller->writeMessage({message: sender.name + ": " + message.message, event:"chat", id: receiver.streamId}); + return {message:"You: " + message.message, event: "chat", id: message.id}; + } + +} + +function broadcast(string message) { + users.forEach(function (types:User user) { + websocket:Caller? caller = user.caller; + if (caller is ()) { + return; + } + types:Response response = {message: message, event: "chat", id: user.streamId}; + error? err = caller->writeMessage(response); + if (err is error) { + io:println("Error broadcasting message: " + err.message()); + } + }); +} diff --git a/samples/basic-chat/server-with-dispatcherStreamId/messages.md b/samples/basic-chat/server-with-dispatcherStreamId/messages.md new file mode 100644 index 000000000..7063740ec --- /dev/null +++ b/samples/basic-chat/server-with-dispatcherStreamId/messages.md @@ -0,0 +1,17 @@ +## Subscribe Message Example + +```json +{"event":"subscribe","name":"Gopi","gender":"Male", "id":"ALOHA"} +``` + +## Unsubscribe Message Example + +```json +{"event":"unsubscribe", id:"UNSUB_ID"} +``` + +## Chat Message Example + +```json +{"event":"chat","message":"Hello Ballerina", "toUserId": "cc6b1efffe42ea75-000420c8-00000002-3ff441ce1aa91480-ef8175ca", "id":"CHAT_ID"} +``` \ No newline at end of file diff --git a/samples/basic-chat/server-with-dispatcherStreamId/modules/types/types.bal b/samples/basic-chat/server-with-dispatcherStreamId/modules/types/types.bal new file mode 100644 index 000000000..1d79e4d98 --- /dev/null +++ b/samples/basic-chat/server-with-dispatcherStreamId/modules/types/types.bal @@ -0,0 +1,99 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Representation of a response +# +# + event - dispatcher key +# + message - message to be sent +# + id - dispatcher stream id of the event +public type Response record {| + string event = "just a message"; + string message; + string id; +|}; + +# Representation of an unsubscribe message. +# +# + event - dispatcher key +# + id - dispatcher stream id of the event +public type Unsubscribe record {| + string event; + string id; +|}; + +# Representation of an info message. +# +# + event - dispatcher key +public type Info record {| + string event; +|}; + +# Representation of a subscription. +# +# + event - type of event +# + name - name of the user +# + gender - gender of the user +# + id - dispatcher stream id of the event +public type Subscribe record {| + string event; + string name; + string gender; + string id; +|}; + +# Representation of a user. +# +# + name - name of the user +# + gender - gender of the user +# + id - id of the user (connection id) +# + caller - websocket caller object +# + streamId - dispatcher stream id of the event subscription +public type User record {| + string name; + string gender; + string id; + websocket:Caller caller; + string streamId; +|}; + +# Repersentation of a message. +# +# + message - message to be sent +# + event - dispatcher key +# + toUserId - user id to send the message +# + id - dispatcher stream id of the event +public type Chat record {| + string message; + string event; + string toUserId; + string id; +|}; + +public type Hello record {| + string message; + string event; +|}; + +# Representation of a basic event. +# +# + event - type of event +# + id - id of the event +public type ClientData record {| + string event; + string id; +|}; diff --git a/samples/basic-chat/server/Ballerina.toml b/samples/basic-chat/server/Ballerina.toml new file mode 100644 index 000000000..2c61b61bc --- /dev/null +++ b/samples/basic-chat/server/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "wso2" +name = "websocket_test" +version = "0.1.0" +distribution = "2201.9.0" + +[build-options] +observabilityIncluded = true diff --git a/samples/basic-chat/server/Dependencies.toml b/samples/basic-chat/server/Dependencies.toml new file mode 100644 index 000000000..66545b816 --- /dev/null +++ b/samples/basic-chat/server/Dependencies.toml @@ -0,0 +1,318 @@ +# AUTO-GENERATED FILE. DO NOT MODIFY. + +# This file is auto-generated by Ballerina for managing dependency versions. +# It should not be modified by hand. + +[ballerina] +dependencies-toml-version = "2" +distribution-version = "2201.9.0" + +[[package]] +org = "ballerina" +name = "auth" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"} +] + +[[package]] +org = "ballerina" +name = "cache" +version = "3.8.0" +dependencies = [ + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "task"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "constraint" +version = "1.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "crypto" +version = "2.7.2" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "file" +version = "1.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "os"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "http" +version = "2.11.2" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "file"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.decimal"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.regexp"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "mime"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "observe"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "io" +version = "1.6.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"} +] +modules = [ + {org = "ballerina", packageName = "io", moduleName = "io"} +] + +[[package]] +org = "ballerina" +name = "jballerina.java" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "jwt" +version = "2.12.1" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "lang.__internal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.array" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"} +] + +[[package]] +org = "ballerina" +name = "lang.decimal" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.int" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.__internal"}, + {org = "ballerina", name = "lang.object"} +] + +[[package]] +org = "ballerina" +name = "lang.object" +version = "0.0.0" + +[[package]] +org = "ballerina" +name = "lang.regexp" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.runtime" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "lang.string" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.regexp"} +] + +[[package]] +org = "ballerina" +name = "lang.value" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "log" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "observe"} +] + +[[package]] +org = "ballerina" +name = "mime" +version = "2.9.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "lang.int"} +] + +[[package]] +org = "ballerina" +name = "oauth2" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "cache"}, + {org = "ballerina", name = "crypto"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "time"}, + {org = "ballerina", name = "url"} +] + +[[package]] +org = "ballerina" +name = "observe" +version = "1.2.3" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "os" +version = "1.8.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "task" +version = "2.5.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "time"} +] + +[[package]] +org = "ballerina" +name = "time" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "url" +version = "2.4.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"} +] + +[[package]] +org = "ballerina" +name = "websocket" +version = "2.11.0" +dependencies = [ + {org = "ballerina", name = "auth"}, + {org = "ballerina", name = "constraint"}, + {org = "ballerina", name = "http"}, + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "jwt"}, + {org = "ballerina", name = "lang.array"}, + {org = "ballerina", name = "lang.runtime"}, + {org = "ballerina", name = "lang.string"}, + {org = "ballerina", name = "lang.value"}, + {org = "ballerina", name = "log"}, + {org = "ballerina", name = "oauth2"}, + {org = "ballerina", name = "time"} +] +modules = [ + {org = "ballerina", packageName = "websocket", moduleName = "websocket"} +] + +[[package]] +org = "ballerinai" +name = "observe" +version = "0.0.0" +dependencies = [ + {org = "ballerina", name = "jballerina.java"}, + {org = "ballerina", name = "observe"} +] +modules = [ + {org = "ballerinai", packageName = "observe", moduleName = "observe"} +] + +[[package]] +org = "haritha" +name = "websocket_test" +version = "0.1.0" +dependencies = [ + {org = "ballerina", name = "io"}, + {org = "ballerina", name = "websocket"}, + {org = "ballerinai", name = "observe"} +] +modules = [ + {org = "haritha", packageName = "websocket_test", moduleName = "websocket_test"}, + {org = "haritha", packageName = "websocket_test", moduleName = "websocket_test.types"} +] + diff --git a/samples/basic-chat/server/main.bal b/samples/basic-chat/server/main.bal new file mode 100644 index 000000000..5efb87482 --- /dev/null +++ b/samples/basic-chat/server/main.bal @@ -0,0 +1,109 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; +import websocket_test.types; +import ballerina/io; + +listener websocket:Listener websocketListener = check new(9092); +map users = {}; + +@websocket:ServiceConfig{dispatcherKey: "event"} +service / on websocketListener { + # An echo service that echoes the messages sent by the client. + # + return - User status + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsService(); + } + +} + +@websocket:ServiceConfig{dispatcherKey: "event"} +service /user on websocketListener { + # Allows clients to get real-time data on users and chat with them. + # + return - websocket service + resource function get .() returns websocket:Service|websocket:UpgradeError { + return new WsServiceUser(); + } + +} + +service class WsService { + *websocket:Service; + + remote function onHello(types:Hello clientData) returns types:Response? { + return {message:"You sent: " + clientData.message}; + } + +} + +service class WsServiceUser { + *websocket:Service; + + remote function onSubscribe(websocket:Caller caller, types:Subscribe sub) returns types:Response { + string callerId = caller.getConnectionId(); + io:println(sub.name + " subscribed: " + callerId); + types:User user = {caller: caller, gender: sub.gender, name: sub.name, id: callerId}; + users[callerId] = user; + broadcast("System: User " + user.name + " (" + callerId + ")" + " has joined the chat"); + return {message: "System: Welcome to the chat!", event:"subscribe"}; + } + + remote function onUnsubscribe(websocket:Caller caller, types:Unsubscribe unsubscribe) returns error? { + string callerId = caller.getConnectionId(); + broadcast("System: User " + users.get(callerId).name + " has left the chat"); + _ = users.remove(callerId); + } + + remote function onClose(websocket:Caller caller) returns websocket:Error? { + string callerId = caller.getConnectionId(); + if (users.hasKey(callerId)) { + _ = users.remove(callerId); + } + } + + remote function onChat(websocket:Caller caller, types:Chat message) returns types:Response|error { + string callerId = caller.getConnectionId(); + if (!users.hasKey(callerId)) { + return { message: "Please subscribe first to send messages"}; + } + types:User sender = users.get(callerId); + if (!users.hasKey(message.toUserId)) { + return {message:"User not found"}; + } + websocket:Caller? receiver = users.get(message.toUserId).caller; + if (receiver is ()) { + return {message:"User not found"}; + } + _ = check receiver->writeMessage({message: sender.name + ": " + message.message, event:"subscribe"}); + return {message:"You: " + message.message, event: "chat"}; + } + +} + +function broadcast(string message) { + users.forEach(function (types:User user) { + websocket:Caller? caller = user.caller; + if (caller is ()) { + return; + } + types:Response response = {message: message, event: "subscribe"}; + error? err = caller->writeMessage(response); + if (err is error) { + io:println("Error broadcasting message: " + err.message()); + } + }); +} diff --git a/samples/basic-chat/server/messages.md b/samples/basic-chat/server/messages.md new file mode 100644 index 000000000..11a0bc442 --- /dev/null +++ b/samples/basic-chat/server/messages.md @@ -0,0 +1,17 @@ +## Subscribe Message Example + +```json +{"event":"subscribe","name":"Gopi","gender":"Male"} +``` + +## Unsubscribe Message Example + +```json +{"event":"unsubscribe"} +``` + +## Chat Message Example + +```json +{"event":"chat","message":"Hello Ballerina", "toUserId": "cc6b1efffe42ea75-0003c7e2-00000002-aa19eabfbcf62d1d-48179b7d"} +``` \ No newline at end of file diff --git a/samples/basic-chat/server/modules/types/types.bal b/samples/basic-chat/server/modules/types/types.bal new file mode 100644 index 000000000..d996b0d58 --- /dev/null +++ b/samples/basic-chat/server/modules/types/types.bal @@ -0,0 +1,89 @@ +// Copyright (c) 2024 WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you 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 +// +// http://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. + +import ballerina/websocket; + +# Representation of a response +# +# + event - dispatcher key +# + message - message to be sent +public type Response record {| + string event = "just a message"; + string message; +|}; + +# Representation of an unsubscribe message. +# +# + event - dispatcher key +public type Unsubscribe record {| + string event; +|}; + +# Representation of an info message. +# +# + event - dispatcher key +public type Info record {| + string event; +|}; + +# Representation of a subscription. +# +# + event - type of event +# + name - name of the user +# + gender - gender of the user +public type Subscribe record {| + string event; + string name; + string gender; +|}; + +# Representation of a user. +# +# + name - name of the user +# + gender - gender of the user +# + id - id of the user (connection id) +# + caller - websocket caller object +public type User record {| + string name; + string gender; + string id; + websocket:Caller caller; +|}; + +# Repersentation of a message. +# +# + message - message to be sent +# + event - dispatcher key +# + toUserId - user id to send the message +public type Chat record {| + string message; + string event; + string toUserId; +|}; + +public type Hello record {| + string message; + string event; +|}; + +# Representation of a basic event. +# +# + event - type of event +# + id - id of the event +public type ClientData record {| + string event; + string id; +|}; diff --git a/websockets/module-ballerina-asyncapi/Module.md b/websockets/module-ballerina-asyncapi/Module.md new file mode 100644 index 000000000..69af1753d --- /dev/null +++ b/websockets/module-ballerina-asyncapi/Module.md @@ -0,0 +1,44 @@ +## Module Overview + +This module provides the Ballerina AsyncAPI tooling, which will currently creates AsyncAPI definitions according to given Ballerina service file + +The AsyncAPI tools currently provide the following capabilities. + + 1. Export the AsyncAPI definition of a Ballerina service. + +The `asyncapi` command in Ballerina is used for Ballerina to AsyncAPI code generations. + +### Ballerina to AsyncAPI +#### Service to AsyncAPI Export +```bash + bal asyncapi -i + [(-o|--output) output asyncapi file path] + [--protocol ] +``` +Export the Ballerina service to an AsyncAPI Specification 2.5.0 definition. For the export to work properly, +the input Ballerina service should be defined using the basic service level @websocket:ServiceConfig annotation with the dispatcherKey. + +If you need to document an AsyncAPI contract for only one given service, then use this command. +```bash + bal asyncapi -i --service + [--protocol ] +``` + +### Samples for AsyncAPI Commands + +#### Generate an AsyncAPI Contract from a Service + + ```bash + bal asyncapi -i modules/helloworld/helloService.bal --protocol ws + ``` +This will generate the AsyncAPI contracts for the Ballerina services, which are in the `hello.bal` Ballerina file. + ```bash + bal asyncapi -i modules/helloworld/helloService.bal --service helloworld --protocol ws + ``` +This command will generate the `helloworld-asyncapi.yaml` file that is related to the `helloworld` service inside the + `helloService.bal` file. + ```bash + bal asyncapi -i modules/helloworld/helloService.bal --json --protocol ws + ``` +This `--json` option can be used with the Ballerina to AsyncAPI command to generate the `helloworld-asyncapi.json` file +instead of generating the YAML file.